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 could output the country code and you could match your filter based on that?</p>\n\n<p>A StringMatchFilter should probably be able to match it for you.</p>\n\n<p>Couldn't get the below address to work properly as a link, but if you look at it, it has some stuff on separate file logging using filters.</p>\n\n<p><a href=\"http://mail-archives.apache.org/mod_mbox/logging-log4j-user/200512.mbox/\" rel=\"nofollow noreferrer\">http://mail-archives.apache.org/mod_mbox/logging-log4j-user/200512.mbox/</a><1CC26C83B6E5AA49A9540FAC8D35158B01E2968E@pune.kaleconsultants.com > (just remove the space before the >)</p>\n\n<p><a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html\" rel=\"nofollow noreferrer\">http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html</a></p>\n"
},
{
"answer_id": 143018,
"author": "jt.",
"author_id": 4362,
"author_profile": "https://Stackoverflow.com/users/4362",
"pm_score": 1,
"selected": false,
"text": "<p>I may be completely off base on my understanding of what you are attempting to accomplish, but I will take a stab at the solution. It sounds like you want a separate log file for each country for which you are processing email. Based on that understanding, here is a possible solution:</p>\n\n<ol>\n<li><p>Set up an appender in your log4j configuration for each country for which you wish to log separately (US example provided):</p>\n\n<p>log4j.appender.usfile=org.apache.log4j.FileAppender</p>\n\n<p>log4j.appender.usfile.File=us.log</p>\n\n<p>log4j.appender.usfile.layout=org.apache.log4j.PatternLayout</p>\n\n<p>log4j.appender.usfile.layout.ConversionPattern=%m%n</p></li>\n<li><p>Create a logger for each country and direct each of them to the appropriate appender (US example provided):</p>\n\n<p>log4j.logger.my-us-logger=debug,usfile</p></li>\n<li><p>In your code, create your Logger based on the country for which the email is being processed:</p>\n\n<p>Logger logger = Logger.getLogger(\"my-us-logger\");</p></li>\n<li><p>Determine how you will accomplish step 3 for the subsequent method calls. You could repeat step 3 in each class/method; or you could modify the method signatures to accept a Logger as input; or you could possibly use <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html\" rel=\"nofollow noreferrer\">ThreadLocal</a> to pass the Logger between methods.</p></li>\n</ol>\n\n<p>Extra info: If you do not want the log statements going to parent loggers (e.g. the rootLogger), you can set their additivity flags to false (US example provided):</p>\n\n<pre><code>log4j.additivity.my-us-logger=false\n</code></pre>\n"
},
{
"answer_id": 144184,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n\n<p>In your <code>Job</code>:</p>\n\n<pre><code>...\npublic static final String MDC_COUNTRY = \"com.y.foo.Country\";\npublic void execute(JobExecutionContext context)\n /* Just guessing that you have the country in your JobContext. */\n MDC.put(MDC_COUNTRY, context.get(MDC_COUNTRY));\n try {\n /* Perform your job here. */\n ...\n } finally {\n MDC.remove(MDC_COUNTRY);\n }\n}\n...\n</code></pre>\n\n<p>Write a custom <a href=\"http://logging.apache.org/log4j/1.2/apidocs/org/apache/log4j/spi/Filter.html\" rel=\"nofollow noreferrer\">Filter</a>:</p>\n\n<pre><code>package com.y.log4j;\n\nimport org.apache.log4j.spi.LoggingEvent;\n\n/**\n * This is a general purpose filter. If its \"value\" property is null, \n * it requires only that the specified key be set in the MDC. If its \n * value is not null, it further requires that the value in the MDC \n * is equal.\n */\npublic final class ContextFilter extends org.apache.log4j.spi.Filter {\n\n public int decide(LoggingEvent event) {\n Object ctx = event.getMDC(key);\n if (value == null)\n return (ctx != null) ? NEUTRAL : DENY;\n else\n return value.equals(ctx) ? NEUTRAL : DENY;\n }\n\n private String key;\n private String value;\n\n public void setContextKey(String key) { this.key = key; }\n public String getContextKey() { return key; }\n public void setValue(String value) { this.value = value; }\n public String getValue() { return value; }\n\n}\n</code></pre>\n\n<p>In your log4j.xml:</p>\n\n<pre><code><appender name=\"fr\" class=\"org.apache.log4j.FileAppender\">\n <param name=\"file\" value=\"france.log\"/>\n ...\n <filter class=\"com.y.log4j.ContextFilter\">\n <param name=\"key\" value=\"com.y.foo.Country\" />\n <param name=\"value\" value=\"fr\" />\n </filter>\n</appender> \n</code></pre>\n"
},
{
"answer_id": 144434,
"author": "Robin",
"author_id": 21925,
"author_profile": "https://Stackoverflow.com/users/21925",
"pm_score": 1,
"selected": false,
"text": "<p>Why not just call Thread.setName() when your job starts to set the name the Thread? If there is an access problem, configure quartz to use your own thread pool.</p>\n"
}
]
| 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 Workspace by specifying an empty directory.</li>\n<li>Make sure you're in the Java perspective by selecting Window -> Open Perspective ..., select Other... and then Java</li>\n<li>Right click anywhere in the Package Explorer pane and select New -> Java Project</li>\n<li>In the dialog that opens give the project a name and then click the option that says \"Crate project from existing sources.\"</li>\n<li>In the text box below the option you selected in Step 4 point to the root directory where you checked out the project. This should be the directory that contains \"com\"</li>\n<li>Click Finish. For this particular project you don't need to do any additional setup for your classpath since it only depends on classes that are part of the Java SE API.</li>\n</ol>\n"
},
{
"answer_id": 142881,
"author": "Kevin Day",
"author_id": 10973,
"author_profile": "https://Stackoverflow.com/users/10973",
"pm_score": 5,
"selected": true,
"text": "<ol>\n<li><p>Create a new Java project in Eclipse. This will create a src folder (to contain your source files).</p></li>\n<li><p>Also create a lib folder (the name isn't that important, but it follows standard conventions).</p></li>\n<li><p>Copy the <code>./com/*</code> folders into the <code>/src</code> folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).</p></li>\n<li><p>Copy any dependencies (<code>jar</code> files that your project itself depends on) into <code>/lib</code> (note that this <strong>should NOT</strong> include the <code>TGGL jar</code> - <em>thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!</em>)</p></li>\n<li><p>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)</p></li>\n<li><p>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.</p></li>\n<li><p>The content of the <code>/src</code> folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). <strong>If you have dependencies</strong> (which you don't in your current project, but I'll include this here for completeness), <strong>the compile will fail initially because you are missing the dependency <code>jar files</code> from the project classpath.</strong></p></li>\n<li><p>Finally, open the <code>/lib</code> folder in Eclipse, <code>right click</code> on each required <code>jar file</code> and choose <code>Build Path->Add</code> to build path.</p></li>\n</ol>\n\n<p>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.</p>\n"
},
{
"answer_id": 4179201,
"author": "Thotman",
"author_id": 427789,
"author_profile": "https://Stackoverflow.com/users/427789",
"pm_score": 4,
"selected": false,
"text": "<p>I think you'll have to import the project via the file->import wizard: </p>\n\n<p><a href=\"http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse\" rel=\"noreferrer\">http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse</a></p>\n\n<p>It's not the last step, but it will start you on your way. </p>\n\n<p>I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).</p>\n"
},
{
"answer_id": 11733990,
"author": "Hrqls",
"author_id": 1564812,
"author_profile": "https://Stackoverflow.com/users/1564812",
"pm_score": 3,
"selected": false,
"text": "<p>In the menu go to :\n- File\n- Import\n- as the filter select 'Existing Projects into Workspace'\n- click next\n- browse to the project directory at 'select root directory'\n- click on 'finish'</p>\n"
}
]
| 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 this file in a text editor and look for the line<br>\nListen 8080<br>\nor<br>\nListen {ip address}:8080 </p>\n\n<p>Change the port number and either restart the web server or just reboot the machine.</p>\n"
},
{
"answer_id": 143090,
"author": "tardate",
"author_id": 6329,
"author_profile": "https://Stackoverflow.com/users/6329",
"pm_score": 1,
"selected": false,
"text": "<p>There are many Oracle components that run a web service, so it's not clear which you are referring to.</p>\n\n<p>For example, the web site port for standalone OC4J is configured in the j2ee/home/config/default-web-site.xml file:</p>\n\n<pre><code><web-site xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\nxsi:noNamespaceSchemaLocation=\"http://xmlns.oracle.com/oracleas/schema/web-site-10_0.xsd\"\nport=\"8888\" display-name=\"OC4J 10g (10.1.3) Default Web Site\"\nschema-major-version=\"10\" schema-minor-version=\"0\" > \n</code></pre>\n"
},
{
"answer_id": 145615,
"author": "pappes",
"author_id": 19494,
"author_profile": "https://Stackoverflow.com/users/19494",
"pm_score": 2,
"selected": false,
"text": "<p>Oracle (database) can use many ports.\nwhen you install the software it scans for free ports and decides which port to use then.</p>\n\n<p>The database listener defaults to 1520 but will use 1521 or 1522 if 1520 is not available.\nThis can be adjusted in the listener.ora files.</p>\n\n<p>The Enterprise Manager, web-based database administration tool defaults to port 80 but will use 8080 if 80 is not available.</p>\n\n<p>See here for details on how to change the port number for enterprise manager:\n<a href=\"http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853\" rel=\"nofollow noreferrer\">http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853</a></p>\n"
},
{
"answer_id": 1011180,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>From <a href=\"http://daust.blogspot.com/2006/01/xe-changing-default-http-port.html\" rel=\"noreferrer\">this</a> blog post:</p>\n\n<blockquote>\n <p><strong>XE: Changing the default http port</strong></p>\n \n <p>Oracle XE uses the embedded http listener that comes with the XML DB\n (XDB) to serve http requests. The default port for HTTP access is\n 8080.</p>\n</blockquote>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Update 8080 port to which port(9090 for example) you like </p>\n\n<pre><code>SQL> -- set http port\nSQL> begin\n 2 dbms_xdb.sethttpport('9090');\n 3 end;\n 4 /\n</code></pre>\n\n<p>After changing the port, when we start Oracle it will go on port 8080, we should type manually new port(9090) in the address bar to run Oracle XE.</p>\n"
},
{
"answer_id": 4097449,
"author": "Nigel_V_Thomas",
"author_id": 192040,
"author_profile": "https://Stackoverflow.com/users/192040",
"pm_score": 3,
"selected": false,
"text": "<p>Execute <code>Exec DBMS_XDB.SETHTTPPORT(8181);</code> as SYS/SYSTEM. Replace 8181 with the port you'd like changing to. Tested this with Oracle 10g.</p>\n\n<p>Source : <a href=\"http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html\" rel=\"noreferrer\">http://hodentekhelp.blogspot.com/2008/08/my-oracle-10g-xe-is-on-port-8080-can-i.html</a></p>\n"
},
{
"answer_id": 11839354,
"author": "susheel",
"author_id": 1580852,
"author_profile": "https://Stackoverflow.com/users/1580852",
"pm_score": 8,
"selected": false,
"text": "<p>From Start | Run open a command window.\nAssuming your environmental variables are set correctly start with the following:</p>\n\n<pre><code>C:\\>sqlplus /nolog\nSQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008\nCopyright (c) 1982, 2005, Oracle. All rights reserved.\n\nSQL> connect\nEnter user-name: system\nEnter password: <enter password if will not be visible>\nConnected.\n\nSQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port] \nPL/SQL procedure successfully completed.\n\nSQL>quit \n</code></pre>\n\n<p>then open browser and use 3010 port.</p>\n"
},
{
"answer_id": 35176566,
"author": "Hareesh Chowdary",
"author_id": 3559196,
"author_profile": "https://Stackoverflow.com/users/3559196",
"pm_score": 4,
"selected": false,
"text": "<p>Just open <code>Run SQL Command Line</code> and login as sysadmin and then enter below command </p>\n\n<pre>\nExec DBMS_XDB.SETHTTPPORT(8181);\n</pre>\n\n<p>That's it. You are done.....</p>\n"
},
{
"answer_id": 57443244,
"author": "Lova Chittumuri",
"author_id": 5256337,
"author_profile": "https://Stackoverflow.com/users/5256337",
"pm_score": 0,
"selected": false,
"text": "<p>Login in with System Admin User Account and execute below SQL Procedure.</p>\n\n<pre><code>begin\ndbms_xdb.sethttpport('Your Port Number');\nend;\n</code></pre>\n\n<p>Then open the Browser and access the below URL</p>\n\n<p><a href=\"http://127.0.0.1:YourPortNumber/apex/\" rel=\"nofollow noreferrer\">http://127.0.0.1:YourPortNumber/apex/</a></p>\n"
}
]
| 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 names of the files existing in the current directory:</p>\n\n<pre><code>#define EXISTS_FILE1_C\n#define EXISTS_FILE1_H\n#define EXISTS_FILE2_C\n</code></pre>\n\n<p>Then, include that file from within your source code, and then your source can test the <code>EXISTS_*</code> defines to see whether a file exists or not.</p>\n"
},
{
"answer_id": 142921,
"author": "Logan",
"author_id": 3518,
"author_profile": "https://Stackoverflow.com/users/3518",
"pm_score": 6,
"selected": true,
"text": "<p>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:</p>\n\n<pre><code>cat > .test.h <<'EOM'\n#include <asdf.h>\nEOM\nif gcc -E .test.h\n then\n echo '#define HAVE_ASDF_H 1' >> config.h\n else \n echo '#ifdef HAVE_ASDF_H' >> config.h\n echo '# undef HAVE_ASDF_H' >> config.h\n echo '#endif' >> config.h\n fi\n</code></pre>\n\n<p>A pretty thorough framework for portably working with portability checks like this (as well as thousands others) is <a href=\"http://www.gnu.org/software/autoconf/\" rel=\"noreferrer\">autoconf</a>.</p>\n"
},
{
"answer_id": 142926,
"author": "bmdhacks",
"author_id": 14032,
"author_profile": "https://Stackoverflow.com/users/14032",
"pm_score": 4,
"selected": false,
"text": "<p>The preprocessor itself cannot identify the existence of files but you certainly can use the build environment to do so. I'm mostly familiar with make, which would allow you to do something like this in your makefile:</p>\n\n<pre><code>ifdef $(test -f filename && echo \"present\")\n DEFINE=-DFILENAME_PRESENT\nendif\n</code></pre>\n\n<p>Of course, you'd have to find an analog to this in other build environments like VisualStudio, but I'm sure they exist.</p>\n"
},
{
"answer_id": 142934,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>So far as I know cpp does not have a directive regarding the existence of a file.</p>\n\n<p>You might be able to accomplish this with a bit of help from the Makefile, if you're using the same make across platforms. You can detect the presence of a file in the Makefile:</p>\n\n<pre><code>foo.o: foo.c\n if [ -f header1.h ]; then CFLAGS+=-DHEADER1_INC\n</code></pre>\n\n<p>As @Greg Hewgill mentions, you can then make your #includes be conditional:</p>\n\n<pre><code>#ifdef HEADER1_INC\n#include <header1.h>\n#endif\n</code></pre>\n"
},
{
"answer_id": 142988,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 3,
"selected": false,
"text": "<p>Another possibility: populate a directory somewhere with zero-length versions of all of the headers you wish to optionally include. Pass a -I argument to this directory as the <i>last</i> such option.</p>\n\n<p>The GCC cpp searches its include directories in order, if it finds a header file in an earlier directory it will use it. Otherwise, it will eventually find the zero-length file, and be happy.</p>\n\n<p>I presume that other cpp implementations also search their include directories in the order specified.</p>\n"
},
{
"answer_id": 142995,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 6,
"selected": false,
"text": "<p>Create a special folder for missing headers, and make that folder to be searched last<br>\n<em>(that is compliler specific - last item in \"INCLUDES\" environment variable, something like that)</em></p>\n\n<p>Then if some header1.h can be missing, create in that folder a stub</p>\n\n<p>header1.h:</p>\n\n<pre><code>#define header1_is_missing\n</code></pre>\n\n<p>Now you can always write</p>\n\n<pre><code>#include <header1.h>\n#ifdef header1_is_missing\n\n // there is no header1.h \n\n#endif\n</code></pre>\n"
},
{
"answer_id": 1073873,
"author": "Ahmad Mushtaq",
"author_id": 35065,
"author_profile": "https://Stackoverflow.com/users/35065",
"pm_score": 1,
"selected": false,
"text": "<p><strong>I had to do something similar for the Symbian OS. This is how i did it:\nlets say you want to check if the file \"file_strange.h\" exists and you want to include some headers or link to some libraries depending on the existance of that file.</strong></p>\n\n<p><strong>first creat a small batch file for checking the existence of that file.</strong></p>\n\n<p>autoconf is good but an over kill for many small projects.</p>\n\n<p>----------check.bat</p>\n\n<pre><code>@echo off\n\nIF EXIST [\\epoc32\\include\\domain\\middleware\\file_strange] GOTO NEW_API\nGOTO OLD_API\nGOTO :EOF\n\n:NEW_API\necho.#define NEW_API_SUPPORTED>../inc/file_strange_supported.h\nGOTO :EOF\n\n:OLD_API\necho.#define OLD_API_SUPPORTED>../inc/file_strange_supported.h\nGOTO :EOF\n</code></pre>\n\n<p>----------check.bat ends</p>\n\n<p><strong>then i created a gnumake file</strong></p>\n\n<p>----------checkmedialist.mk</p>\n\n<pre><code>do_nothing :\n @rem do_nothing\n\nMAKMAKE : \n check.bat\n\nBLD : do_nothing\n\nCLEAN : do_nothing\n\nLIB : do_nothing\n\nCLEANLIB : do_nothing\n\nRESOURCE : do_nothing\n\nFREEZE : do_nothing\n\nSAVESPACE : do_nothing\n\nRELEASABLES : do_nothing\n\nFINAL : do_nothing\n</code></pre>\n\n<p>----------check.mk ends</p>\n\n<p><strong>include the check.mk file in your bld.inf file, it MUST be before your MMP files</strong></p>\n\n<pre><code>PRJ_MMPFILES\ngnumakefile checkmedialist.mk\n</code></pre>\n\n<p><strong>now at compile time the file <code>file_strange_supported.h</code> will have an appropriate flag set.\nyou can use this flag in your cpp files or even in the mmp file\nfor example in mmp</strong></p>\n\n<pre><code>#include \"../inc/file_strange_supported.h\"\n#ifdef NEW_API_SUPPORTED\nLIBRARY newapi.lib\n#else\nLIBRARY oldapi.lib\n#endif\n</code></pre>\n\n<p><strong>and in .cpp</strong></p>\n\n<pre><code>#include \"../inc/file_strange_supported.h\"\n#ifdef NEW_API_SUPPORTED\nCStrangeApi* api = Api::NewLC();\n#else\n// ..\n#endif\n</code></pre>\n"
},
{
"answer_id": 33260104,
"author": "Setepenre",
"author_id": 2721950,
"author_profile": "https://Stackoverflow.com/users/2721950",
"pm_score": 7,
"selected": false,
"text": "<h1>Little Update</h1>\n\n<p>Some compilers might support <code>__has_include ( header-name )</code>.</p>\n\n<p>The extension was added to the <a href=\"https://isocpp.org/files/papers/p0636r0.html\" rel=\"noreferrer\">C++17 standard</a> (<a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/p0061r1.html\" rel=\"noreferrer\">P0061R1</a>).</p>\n\n<h2>Compiler Support</h2>\n\n<ul>\n<li>Clang</li>\n<li>GCC from 5.X</li>\n<li>Visual Studio from VS2015 Update 2 (?)</li>\n</ul>\n\n<h2>Example (from clang website):</h2>\n\n<pre><code>// Note the two possible file name string formats.\n#if __has_include(\"myinclude.h\") && __has_include(<stdint.h>)\n# include \"myinclude.h\"\n#endif\n</code></pre>\n\n<h1>Sources</h1>\n\n<ul>\n<li><a href=\"https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations\" rel=\"noreferrer\">SD-6: SG10 Feature Test Recommendations</a></li>\n<li><a href=\"http://clang.llvm.org/docs/LanguageExtensions.html#langext-has-include\" rel=\"noreferrer\">Clang Language Extensions</a></li>\n</ul>\n"
},
{
"answer_id": 52275443,
"author": "Christoph Lipka",
"author_id": 8178357,
"author_profile": "https://Stackoverflow.com/users/8178357",
"pm_score": 2,
"selected": false,
"text": "<p>Contrary to some claims here and on the internet, Visual Studio 2015 does NOT support the <code>__has_include</code> feature - at least according to my experience. Tested with Update 3.</p>\n\n<p>The rumors may have arisen from the fact that VS 2017 is also referred to as \"Version 15\"; VS 2015 is instead referred to as \"Version 14\". Support for the feature seems to have been officially introduced with \"Visual Studio 2017 Version 15.3\".</p>\n"
}
]
| 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 (untested):</p>\n\n<pre><code>string oneSpace = \" \";\nstring fiftySpace = \" \";\n\nvar query = \n from person in db.Persons\n let lastname = person.cn.Replace(oneSpace, fiftySpace).SubString(0, 50).Trim()\n group person by lastname into g\n select new { Key = g.Key, Count = g.Count };\n</code></pre>\n"
},
{
"answer_id": 143086,
"author": "Erik Forbes",
"author_id": 16942,
"author_profile": "https://Stackoverflow.com/users/16942",
"pm_score": 1,
"selected": false,
"text": "<p>The reason your first attempt didn't work is because LINQ to SQL uses Expression Trees to translate your query into SQL. As a result any code that isn't directly translatable into SQL is an exception - this includes the call to Split.</p>\n"
},
{
"answer_id": 143735,
"author": "Andrew Queisser",
"author_id": 18321,
"author_profile": "https://Stackoverflow.com/users/18321",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks guys, I'll try the \"Replace\" trick to see if that runs. I'm very intrigued by LINQ but now it looks like there's some hidden mysteriousness where you have to know what your LINQ queries translate into before being able to use it effectively.</p>\n\n<p>The core problem is of course that I don't know SQL very well so that's where I'll start.</p>\n\n<p>Edit:</p>\n\n<p>I finally tried the \"Replace\" today and it works. I even got to sort the grouped results by count so now I have a pareto of name in my company. It's horrendously slow, though. Much faster to select everything and do the bucketing in C# directly.</p>\n\n<p>Thanks again,</p>\n\n<p>Andrew</p>\n"
}
]
| 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.html\" rel=\"nofollow noreferrer\">From the idevkit.com forums:</a></p>\n\n<pre><code>#define kFilteringFactor 0.1\nstatic UIAccelerationValue rollingX=0, rollingY=0, rollingZ=0;\n\n\n- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {\n\n // Calculate low pass values\n\n rollingX = (acceleration.x * kFilteringFactor) + (rollingX * (1.0 - kFilteringFactor));\n rollingY = (acceleration.y * kFilteringFactor) + (rollingY * (1.0 - kFilteringFactor));\n rollingZ = (acceleration.z * kFilteringFactor) + (rollingZ * (1.0 - kFilteringFactor));\n\n // Subtract the low-pass value from the current value to get a simplified high-pass filter\n\n float accelX = acceleration.x - rollingX;\n float accelY = acceleration.y - rollingY;\n float accelZ = acceleration.z - rollingZ;\n\n // Use the acceleration data.\n\n}\n</code></pre>\n"
},
{
"answer_id": 160826,
"author": "Mike Akers",
"author_id": 17188,
"author_profile": "https://Stackoverflow.com/users/17188",
"pm_score": 3,
"selected": false,
"text": "<p>Just in case someone wants to know, the highpass filter can be found in the <a href=\"https://developer.apple.com/library/ios/samplecode/AccelerometerGraph/Introduction/Intro.html\" rel=\"nofollow noreferrer\">Accelerometer Graph sample</a>.</p>\n"
},
{
"answer_id": 7498693,
"author": "Christoph",
"author_id": 835102,
"author_profile": "https://Stackoverflow.com/users/835102",
"pm_score": 1,
"selected": false,
"text": "<p>Here's the link, i was looking for this one too. This is an example for adaptive / non adaptive highpass and lowpass filter: <a href=\"https://developer.apple.com/library/ios/samplecode/AccelerometerGraph/Introduction/Intro.html\" rel=\"nofollow\">Apple iOS Reference Library - AccelerometerGraph Example</a></p>\n"
}
]
| 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>The ruby world (or the RoR) does more of the same stuff and they call it routing.</p>\n\n<p>So, there's no getting around it (Unless you want to use smart regex through out -- which has been tried and it works just fine).</p>\n"
},
{
"answer_id": 143136,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 2,
"selected": true,
"text": "<p>Check out a related <a href=\"https://stackoverflow.com/questions/125359/any-clever-ways-of-handling-the-context-in-a-web-app\">question</a></p>\n\n<p>Also consider <a href=\"http://tuckey.org/urlrewrite/\" rel=\"nofollow noreferrer\">URLRewriteFilter</a></p>\n\n<p>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.</p>\n\n<p>This change can be easily done \"en masse\", using something like sed.</p>\n\n<pre><code>sed -e 's/<a/<t:a/g' -e 's/<\\/a>/<\\/t:a>/g' old/x.jsp > new/x.jsp\n</code></pre>\n\n<p>Form actions may be a bit trickier than sed, but you get the idea.</p>\n"
}
]
| 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 from VBRocks...</p>\n\n<pre><code>Imports System\nImports System.IO\nImports System.Text\nImports System.Text.Encoding\n\n\n\n'4/20/07 submission includes a line spacing addition when a control character is used:\n' The line spacing is calculated off of the 3rd control character.\n'\n' Also includes the 4/18 modification of determining end of file.\n\n'4/26/07 submission inclues an addition of 6 to the record length when the 4th control\n' character is an 8. This is because these records were being truncated.\n\n\n'Authored by Gary A. Lima, aka. VBRocks\n\n\n\n''' <summary>\n''' Translates an EBCDIC file to an ASCII file.\n''' </summary>\n''' <remarks></remarks>\nPublic Class EBCDIC_to_ASCII_Translator\n\n#Region \" Example\"\n\n Private Sub Example()\n 'Set your source file and destination file paths\n Dim sSourcePath As String = \"c:\\Temp\\MyEBCDICFile\"\n Dim sDestinationPath As String = \"c:\\Temp\\TranslatedFile.txt\"\n\n Dim trans As New EBCDIC_to_ASCII_Translator()\n\n 'If your EBCDIC file uses Control records to determine the length of a record, then this to True\n trans.UseControlRecord = True\n\n 'If the first record of your EBCDIC file is filler (junk), then set this to True\n trans.IgnoreFirstRecord = True\n\n 'EBCDIC files are written in block lengths, set your block length (Example: 134, 900, Etc.)\n trans.BlockLength = 900\n\n 'This method will actually translate your source file and output it to the specified destination file path\n trans.TranslateFile(sSourcePath, sDestinationPath)\n\n\n 'Here is a alternate example:\n 'No Control record is used\n 'trans.UseControlRecord = False\n\n 'Translate the whole file, including the first record\n 'trans.IgnoreFirstRecord = False\n\n 'Set the block length\n 'trans.BlockLength = 134\n\n 'Translate...\n 'trans.TranslateFile(sSourcePath, sDestinationPath)\n\n\n\n '*** Some additional methods that you can use are:\n\n 'Trim off leading characters from left side of string (position 0 to...)\n 'trans.LTrim = 15\n\n 'Translate 1 EBCDIC character to an ASCII character\n 'Dim strASCIIChar as String = trans.TranslateCharacter(\"S\")\n\n 'Translate an EBCDIC character array to an ASCII string\n 'trans.TranslateCharacters(chrEBCDICArray)\n\n 'Translates an EBCDIC string to an ASCII string\n 'Dim strASCII As String = trans.TranslateString(\"EBCDIC String\")\n\n\n End Sub\n\n#End Region 'Example\n\n 'Translate characters from EBCDIC to ASCII\n\n Private ASCIIEncoding As Encoding = Encoding.ASCII\n Private EBCDICEncoding As Encoding = Encoding.GetEncoding(37) 'EBCDIC\n\n 'Block Length: Can be fixed (Ex: 134). \n Private miBlockLength As Integer = 0\n Private mbUseControlRec As Boolean = True 'If set to False, will return exact block length\n Private mbIgnoreFirstRecord As Boolean = True 'Will Ignore first record if set to true (First record may be filler)\n Private miLTrim As Integer = 0\n\n ''' <summary>\n ''' Translates SourceFile from EBCDIC to ASCII. Writes output to file path specified by DestinationFile parameter.\n ''' Set the BlockLength Property to designate block size to read.\n ''' </summary>\n ''' <param name=\"SourceFile\">Enter the path of the Source File.</param>\n ''' <param name=\"DestinationFile\">Enter the path of the Destination File.</param>\n ''' <remarks></remarks>\n Public Sub TranslateFile(ByVal SourceFile As String, ByVal DestinationFile As String)\n\n Dim iRecordLength As Integer 'Stores length of a record, not including the length of the Control Record (if used)\n Dim sRecord As String = \"\" 'Stores the actual record\n Dim iLineSpace As Integer = 1 'LineSpace: 1 for Single Space, 2 for Double Space, 3 for Triple Space...\n\n Dim iControlPosSix As Byte() 'Stores the 6th character of a Control Record (used to calculate record length)\n Dim iControlRec As Byte() 'Stores the EBCDIC Control Record (First 6 characters of record)\n Dim bEOR As Boolean 'End of Record Flag\n Dim bBOF As Boolean = True 'Beginning of file\n Dim iConsumedChars As Integer = 0 'Stores the number of consumed characters in the current block\n Dim bIgnoreRecord As Boolean = mbIgnoreFirstRecord 'Ignores the first record if set.\n\n Dim ControlArray(5) As Char 'Stores Control Record (first 6 bytes)\n Dim chrArray As Char() 'Stores characters just after read from file\n\n Dim sr As New StreamReader(SourceFile, EBCDICEncoding)\n Dim sw As New StreamWriter(DestinationFile)\n\n 'Set the RecordLength to the RecordLength Property (below)\n iRecordLength = miBlockLength\n\n 'Loop through entire file\n Do Until sr.EndOfStream = True\n\n 'If using a Control Record, then check record for valid data.\n If mbUseControlRec = True Then\n 'Read the Control Record (first 6 characters of the record)\n sr.ReadBlock(ControlArray, 0, 6)\n\n 'Update the value of consumed (read) characters\n iConsumedChars += ControlArray.Length\n\n 'Get the bytes of the Control Record Array\n iControlRec = EBCDICEncoding.GetBytes(ControlArray)\n\n 'Set the line spacing (position 3 divided by 64)\n ' (64 decimal = Single Spacing; 128 decimal = Double Spacing)\n iLineSpace = iControlRec(2) / 64\n\n\n 'Check the Control record for End of File\n 'If the Control record has a 8 or 10 in position 1, and a 1 in postion 2, then it is the end of the file\n If (iControlRec(0) = 8 OrElse iControlRec(0) = 10) AndAlso _\n iControlRec(1) = 1 Then\n\n If bBOF = False Then\n Exit Do\n\n Else\n 'The Beginning of file flag is set to true by default, so when the first\n ' record is encountered, it is bypassed and the bBOF flag is set to False\n bBOF = False\n\n End If 'If bBOF = Fals\n\n End If 'If (iControlRec(0) = 8 OrElse\n\n\n\n 'Set the default value for the End of Record flag to True\n ' If the Control Record has all zeros, then it's True, else False\n bEOR = True\n\n 'If the Control record contains all zeros, bEOR will stay True, else it will be set to False\n For i As Integer = 0 To 5\n If iControlRec(i) > 0 Then\n bEOR = False\n\n Exit For\n\n End If 'If iControlRec(i) > 0\n\n Next 'For i As Integer = 0 To 5\n\n If bEOR = False Then\n 'Convert EBCDIC character to ASCII\n 'Multiply the 6th byte by 6 to get record length\n ' Why multiply by 6? Because it works.\n iControlPosSix = EBCDICEncoding.GetBytes(ControlArray(5))\n\n 'If the 4th position of the control record is an 8, then add 6\n ' to the record length to pick up remaining characters.\n If iControlRec(3) = 8 Then\n iRecordLength = CInt(iControlPosSix(0)) * 6 + 6\n\n Else\n iRecordLength = CInt(iControlPosSix(0)) * 6\n\n End If\n\n 'Add the length of the record to the Consumed Characters counter\n iConsumedChars += iRecordLength\n\n Else\n 'If the Control Record had all zeros in it, then it is the end of the Block.\n\n 'Consume the remainder of the block so we can continue at the beginning of the next block.\n ReDim chrArray(miBlockLength - iConsumedChars - 1)\n 'ReDim chrArray(iRecordLength - iConsumedChars - 1)\n\n 'Consume (read) the remaining characters in the block. \n ' We are not doing anything with them because they are not actual records.\n 'sr.ReadBlock(chrArray, 0, iRecordLength - iConsumedChars)\n sr.ReadBlock(chrArray, 0, miBlockLength - iConsumedChars)\n\n 'Reset the Consumed Characters counter\n iConsumedChars = 0\n\n 'Set the Record Length to 0 so it will not be processed below.\n iRecordLength = 0\n\n End If ' If bEOR = False\n\n End If 'If mbUseControlRec = True\n\n\n\n If iRecordLength > 0 Then\n 'Resize our array, dumping previous data. Because Arrays are Zero (0) based, subtract 1 from the Record length.\n ReDim chrArray(iRecordLength - 1)\n\n 'Read the specfied record length, without the Control Record, because we already consumed (read) it.\n sr.ReadBlock(chrArray, 0, iRecordLength)\n\n 'Copy Character Array to String Array, Converting in the process, then Join the Array to a string\n sRecord = Join(Array.ConvertAll(chrArray, New Converter(Of Char, String)(AddressOf ChrToStr)), \"\")\n\n 'If the record length was 0, then the Join method may return Nothing\n If IsNothing(sRecord) = False Then\n\n If bIgnoreRecord = True Then\n 'Do nothing - bypass record\n\n 'Reset flag\n bIgnoreRecord = False\n\n Else\n 'Write the line out, LTrimming the specified number of characters.\n If sRecord.Length >= miLTrim Then\n sw.WriteLine(sRecord.Remove(0, miLTrim))\n\n Else\n sw.WriteLine(sRecord.Remove(0, sRecord.Length))\n\n End If ' If sRecord.Length >= miLTrim\n\n 'Write out the number of blank lines specified by the 3rd control character.\n For i As Integer = 1 To iLineSpace - 1\n sw.WriteLine(\"\")\n\n Next 'For i As Integer = 1 To iLineSpace\n\n End If 'If bIgnoreRecord = True\n\n\n 'Obviously, if we have read more characters from the file than the designated size of the block,\n ' then subtract the number of characters we have read into the next block from the block size.\n If iConsumedChars > miBlockLength Then\n 'If iConsumedChars > iRecordLength Then\n iConsumedChars = iConsumedChars - miBlockLength\n 'iConsumedChars = iConsumedChars - iRecordLength\n\n End If\n\n End If 'If IsNothing(sRecord) = False\n\n End If 'If iRecordLength > 0\n\n 'Allow computer to process (works in a class module, not in a dll)\n 'Application.DoEvents()\n\n Loop\n\n 'Destroy StreamReader (sr)\n sr.Close()\n sr.Dispose()\n\n 'Destroy StreamWriter (sw)\n sw.Close()\n sw.Dispose()\n\n End Sub\n\n\n\n ''' <summary>\n ''' Translates 1 EBCDIC Character (Char) to an ASCII String\n ''' </summary>\n ''' <param name=\"chr\"></param>\n ''' <returns></returns>\n ''' <remarks></remarks>\n Private Function ChrToStr(ByVal chr As Char) As String\n Dim sReturn As String = \"\"\n\n 'Convert character into byte\n Dim EBCDICbyte As Byte() = EBCDICEncoding.GetBytes(chr)\n\n 'Convert EBCDIC byte to ASCII byte\n Dim ASCIIByte As Byte() = Encoding.Convert(EBCDICEncoding, ASCIIEncoding, EBCDICbyte)\n\n sReturn = Encoding.ASCII.GetString(ASCIIByte)\n\n Return sReturn\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates an EBCDIC String to an ASCII String\n ''' </summary>\n ''' <param name=\"sStringToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks></remarks>\n Public Function TranslateString(ByVal sStringToTranslate As String) As String\n Dim i As Integer = 0\n Dim sReturn As New System.Text.StringBuilder()\n\n 'Loop through the string and translate each character\n For i = 0 To sStringToTranslate.Length - 1\n sReturn.Append(ChrToStr(sStringToTranslate.Substring(i, 1)))\n\n Next\n\n Return sReturn.ToString()\n\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates 1 EBCDIC Character (Char) to an ASCII String\n ''' </summary>\n ''' <param name=\"sCharacterToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks></remarks>\n Public Function TranslateCharacter(ByVal sCharacterToTranslate As Char) As String\n\n Return ChrToStr(sCharacterToTranslate)\n\n End Function\n\n\n\n ''' <summary>\n ''' Translates an EBCDIC Character (Char) Array to an ASCII String\n ''' </summary>\n ''' <param name=\"sCharacterArrayToTranslate\"></param>\n ''' <returns>String</returns>\n ''' <remarks>Remarks</remarks>\n Public Function TranslateCharacters(ByVal sCharacterArrayToTranslate As Char()) As String\n Dim sReturn As String = \"\"\n\n 'Copy Character Array to String Array, Converting in the process, then Join the Array to a string\n sReturn = Join(Array.ConvertAll(sCharacterArrayToTranslate, _\n New Converter(Of Char, String)(AddressOf ChrToStr)), \"\")\n\n Return sReturn\n\n End Function\n\n\n ''' <summary>\n ''' Block Length must be set. You can set the BlockLength for specific block sizes (Ex: 134).\n ''' Set UseControlRecord = False for files with specific block sizes (Default is True)\n ''' </summary>\n ''' <value>0</value>\n ''' <returns>Integer</returns>\n ''' <remarks></remarks>\n Public Property BlockLength() As Integer\n Get\n Return miBlockLength\n\n End Get\n Set(ByVal value As Integer)\n miBlockLength = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Determines whether a ControlKey is used to calculate RecordLength of valid data\n ''' </summary>\n ''' <value>Default value is True</value>\n ''' <returns>Boolean</returns>\n ''' <remarks></remarks>\n Public Property UseControlRecord() As Boolean\n Get\n Return mbUseControlRec\n\n End Get\n Set(ByVal value As Boolean)\n mbUseControlRec = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Ignores first record if set (Default is True)\n ''' </summary>\n ''' <value>Default is True</value>\n ''' <returns>Boolean</returns>\n ''' <remarks></remarks>\n Public Property IgnoreFirstRecord() As Boolean\n Get\n Return mbIgnoreFirstRecord\n\n End Get\n\n Set(ByVal value As Boolean)\n mbIgnoreFirstRecord = value\n\n End Set\n End Property\n\n\n\n ''' <summary>\n ''' Trims the left side of every string the specfied number of characters. Default is 0.\n ''' </summary>\n ''' <value>Default is 0.</value>\n ''' <returns>Integer</returns>\n ''' <remarks></remarks>\n Public Property LTrim() As Integer\n Get\n Return miLTrim\n\n End Get\n\n Set(ByVal value As Integer)\n miLTrim = value\n\n End Set\n End Property\n\n\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 143024,
"author": "Paul Keister",
"author_id": 19500,
"author_profile": "https://Stackoverflow.com/users/19500",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>Once you've dealt with the EOL problem, the COMP-3 conversion is pretty straigtforward. I was able to find <a href=\"http://support.microsoft.com/kb/65323\" rel=\"nofollow noreferrer\">this article</a> in the MS knowledgebase with sample code in BASIC. See below for a VB.NET port of this code.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>Imports Microsoft.VisualBasic\n\nModule Module1\n\n'Sample COMP-3 conversion code\n'Adapted from http://support.microsoft.com/kb/65323\n'This code has not been tested\n\nSub Main()\n\n Dim Digits%(15) 'Holds the digits for each number (max = 16).\n Dim Basiceqv#(1000) 'Holds the Basic equivalent of each COMP-3 number.\n\n 'Added to make code compile\n Dim MyByte As Char, HighPower%, HighNibble%\n Dim LowNibble%, Digit%, E%, Decimal%, FileName$\n\n\n 'Clear the screen, get the filename and the amount of decimal places\n 'desired for each number, and open the file for sequential input:\n FileName$ = InputBox(\"Enter the COBOL data file name: \")\n Decimal% = InputBox(\"Enter the number of decimal places desired: \")\n\n FileOpen(1, FileName$, OpenMode.Binary)\n\n Do Until EOF(1) 'Loop until the end of the file is reached.\n Input(1, MyByte)\n If MyByte = Chr(0) Then 'Check if byte is 0 (ASC won't work on 0).\n Digits%(HighPower%) = 0 'Make next two digits 0. Increment\n Digits%(HighPower% + 1) = 0 'the high power to reflect the\n HighPower% = HighPower% + 2 'number of digits in the number\n 'plus 1.\n Else\n HighNibble% = Asc(MyByte) \\ 16 'Extract the high and low\n LowNibble% = Asc(MyByte) And &HF 'nibbles from the byte. The\n Digits%(HighPower%) = HighNibble% 'high nibble will always be a\n 'digit.\n If LowNibble% <= 9 Then 'If low nibble is a\n 'digit, assign it and\n Digits%(HighPower% + 1) = LowNibble% 'increment the high\n HighPower% = HighPower% + 2 'power accordingly.\n Else\n HighPower% = HighPower% + 1 'Low nibble was not a digit but a\n Digit% = 0 '+ or - signals end of number.\n\n 'Start at the highest power of 10 for the number and multiply\n 'each digit by the power of 10 place it occupies.\n For Power% = (HighPower% - 1) To 0 Step -1\n Basiceqv#(E%) = Basiceqv#(E%) + (Digits%(Digit%) * (10 ^ Power%))\n Digit% = Digit% + 1\n Next\n\n 'If the sign read was negative, make the number negative.\n If LowNibble% = 13 Then\n Basiceqv#(E%) = Basiceqv#(E%) - (2 * Basiceqv#(E%))\n End If\n\n 'Give the number the desired amount of decimal places, print\n 'the number, increment E% to point to the next number to be\n 'converted, and reinitialize the highest power.\n Basiceqv#(E%) = Basiceqv#(E%) / (10 ^ Decimal%)\n Print(Basiceqv#(E%))\n E% = E% + 1\n HighPower% = 0\n End If\n End If\n Loop\n\n FileClose() 'Close the COBOL data file, and end.\nEnd Sub\n\nEnd Module\n</code></pre>\n"
},
{
"answer_id": 263188,
"author": "Paul Morgan",
"author_id": 16322,
"author_profile": "https://Stackoverflow.com/users/16322",
"pm_score": 2,
"selected": false,
"text": "<p>If the original data was in EBCDIC your COMP-3 field has been garbled. The FTP process has done an EBCDIC to ASCII translation of the byte values in the COMP-3 field which isn't what you want. To correct this you can: </p>\n\n<p>1) Use BINARY mode for the transfer so you get the raw EBCDIC data. Then you convert the COMP-3 field to a number and translate any other EBCDIC text on the record to ASCII. A packed field stores each digit in a half byte with the lower half byte as a sign (F is positive and other values, usually D or E, are negative). Storing 123.4 in a PIC 999.99 USAGE COMP-3 would be X'01234F' (three bytes) and -123 in the same field is X'01230D'.</p>\n\n<p>2) Have the sender convert the field into a USAGE IS DISPLAY SIGN IS LEADING(or TRAILING) numeric field. This stores the number as a string of EBCDIC numeric digits with the sign as a separate negative(-) or blank character. All digits and the sign translate correctly to their ASCII equivalent on the FTP transfer.</p>\n"
},
{
"answer_id": 1465911,
"author": "bubbassauro",
"author_id": 1328,
"author_profile": "https://Stackoverflow.com/users/1328",
"pm_score": 0,
"selected": false,
"text": "<p>Some useful links for EBCDIC translation:</p>\n\n<p>Translation table - useful to do check some of the values in the packed decimal fields:\n<a href=\"http://www.simotime.com/asc2ebc1.htm\" rel=\"nofollow noreferrer\">http://www.simotime.com/asc2ebc1.htm</a></p>\n\n<p>List of code pages in msdn:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx</a></p>\n\n<p>And a piece of code to convert the byte array fields in C#:</p>\n\n<pre><code>// 500 is the code page for IBM EBCDIC International \nSystem.Text.Encoding enc = new System.Text.Encoding(500);\nstring value = enc.GetString(byteArrayField);\n</code></pre>\n"
},
{
"answer_id": 2039871,
"author": "Steve old guy",
"author_id": 247786,
"author_profile": "https://Stackoverflow.com/users/247786",
"pm_score": 0,
"selected": false,
"text": "<p>The packed fields are the same in EBCDIC or ASCII. Do not run the EBCDIC to ASCII conversion on them. In .Net dump them into a byte[].</p>\n\n<p>You use bitwise masks and shifts to pack/unpack.\n-- But bitwise ops only apply to integer types in .Net so you need to jump through some hoops!</p>\n\n<p>A good COBOL or C artist can point you in the right direction.</p>\n\n<p>Find one of the old guys and pay your dues (about three beers should do it).</p>\n"
},
{
"answer_id": 10200388,
"author": "John",
"author_id": 1339951,
"author_profile": "https://Stackoverflow.com/users/1339951",
"pm_score": 3,
"selected": false,
"text": "<p>I have been watching the posts on numerous boards concerning converting Comp-3 BCD data from \"legacy\" mainframe files to something useable in C#. First, I would like to say that I am less than enamoured by the responses that some of these posts have received - especially those that have said essentially \"why are you bothering us with these non-C#/C++ related posts\" and also \"If you need an answer about some sort of COBOL convention, why don't you go visit a COBOL oriented site\". This, to me, is complete BS as there is going to be a need for probably many years to come, (unfortunately), for software developers to understand how to deal with some of these legacy issues that exist in THE REAL WORLD. So, even if I get slammed on this post for the following code, I am going to share with you a REAL WORLD experience that I had to deal with regarding COMP-3/EBCDIC conversion (and yes, I am he who talks of \"floppy disks, paper-tape, Disc Packs etc... - I have been a software engineer since 1979\").</p>\n\n<p>First - understand that any file that you read from a legacy main-frame system like IBM is going to present the data to you in EBCDIC format and in order to convert any of that data to a C#/C++ string you can deal with you are going to have to use the proper code page translation to get the data into ASCII format. A good example of how to handle this would be:</p>\n\n<p>StreamReader readFile = new StreamReader(path, Encoding.GetEncoding(037); // 037 = EBCDIC to ASCII translation.</p>\n\n<p>This will ensure that anything that you read from this stream will then be converted to ASCII and can be used in a string format. This includes \"Zoned Decimal\" (Pic 9) and \"Text\" (Pic X) fields as declared by COBOL. However, this does not necessarily convert COMP-3 fields to the correct \"binary\" equivelant when read into a char[] or byte[] array. To do this, the only way that you are ever going to get this translated properly (even using UTF-8, UTF-16, Default or whatever) code pages, you are going to want to open the file like this:</p>\n\n<p>FileStream fileStream = new FileStream(path, FIleMode.Open, FIleAccess.Read, FileShare.Read);</p>\n\n<p>Of course, the \"FileShare.Read\" option is \"optional\".</p>\n\n<p>When you have isolated the field that you want to convert to a decimal value (and then subsequently to an ASCII string if need be), you can use the following code - and this has been basically stolen from the MicroSoft \"UnpackDecimal\" posting that you can get at:</p>\n\n<p><a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=0e4bba52-cc52-4d89-8590-cda297ff7fbd&displaylang=en\" rel=\"noreferrer\">http://www.microsoft.com/downloads/details.aspx?familyid=0e4bba52-cc52-4d89-8590-cda297ff7fbd&displaylang=en</a></p>\n\n<p>I have isolated (I think) what are the most important parts of this logic and consolidated it into two a method that you can do with what you want. For my purposes, I chose to leave this as returning a Decimal value which I could then do with what I wanted. Basically, the method is called \"unpack\" and you pass it a byte[] array (no longer than 12 bytes) and the scale as an int, which is the number of decimal places you want to have returned in the Decimal value. I hope this works for you as well as it did for me.</p>\n\n<pre><code> private Decimal Unpack(byte[] inp, int scale)\n {\n long lo = 0;\n long mid = 0;\n long hi = 0;\n bool isNegative;\n\n // this nybble stores only the sign, not a digit. \n // \"C\" hex is positive, \"D\" hex is negative, and \"F\" hex is unsigned. \n switch (nibble(inp, 0))\n {\n case 0x0D:\n isNegative = true;\n break;\n case 0x0F:\n case 0x0C:\n isNegative = false;\n break;\n default:\n throw new Exception(\"Bad sign nibble\");\n }\n long intermediate;\n long carry;\n long digit;\n for (int j = inp.Length * 2 - 1; j > 0; j--)\n {\n // multiply by 10\n intermediate = lo * 10;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = mid * 10 + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = hi * 10 + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // By limiting input length to 14, we ensure overflow will never occur\n\n digit = nibble(inp, j);\n if (digit > 9)\n {\n throw new Exception(\"Bad digit\");\n }\n intermediate = lo + digit;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = mid + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = hi + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // carry should never be non-zero. Back up with validation\n }\n }\n }\n return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale);\n }\n\n private int nibble(byte[] inp, int nibbleNo)\n {\n int b = inp[inp.Length - 1 - nibbleNo / 2];\n return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4);\n }\n</code></pre>\n\n<p>If you have any questions, post them on here - because I suspect that I am going to get \"flamed\" like everyone else who has chosen to post questions that are pertinent to todays issues...</p>\n\n<p>Thanks,\nJohn - The Elder.</p>\n"
},
{
"answer_id": 62224734,
"author": "Sathyaraj Palanisamy",
"author_id": 1693613,
"author_profile": "https://Stackoverflow.com/users/1693613",
"pm_score": 0,
"selected": false,
"text": "<p>The “ASCII transfer type” will transfer the files as regular text files. So files becoming corrupt when we transfer packed decimal or binary data files in ASCII transfer type. The “Binary transfer type” will transfer the data in binary mode which handles the files as binary data instead of text data. So we have to use Binary transfer type here.\nReference : <a href=\"https://www.codeproject.com/Tips/673240/EBCDIC-to-ASCII-Converter\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Tips/673240/EBCDIC-to-ASCII-Converter</a></p>\n\n<p>Once your file is ready, here is the code to convert packed decimal to human readable decimal.</p>\n\n<pre><code> using System;\n using System.Collections.Generic;\n using System.IO;\n using System.Linq;\n using System.Text;\n using System.Threading.Tasks;\n\n namespace ConsoleApp2\n {\n class Program\n {\n static void Main(string[] args)\n {\n var path = @\"C:\\FileName.BIN.dat\";\n var templates = new List<Template>\n {\n new Template{StartPos=1,CharLength=4,Type=\"AlphaNum\"},\n new Template{StartPos=5,CharLength=1,Type=\"AlphaNum\"},\n new Template{StartPos=6,CharLength=8,Type=\"AlphaNum\"},\n new Template{StartPos=14,CharLength=1,Type=\"AlphaNum\"},\n new Template{StartPos=46,CharLength=4,Type=\"Packed\",DecimalPlace=2},\n new Template{StartPos=54,CharLength=5,Type=\"Packed\",DecimalPlace=0},\n new Template{StartPos=60,CharLength=4,Type=\"Packed\",DecimalPlace=2},\n new Template{StartPos=64,CharLength=1,Type=\"AlphaNum\"}\n };\n\n var allBytes = File.ReadAllBytes(path);\n for (int i = 0; i < allBytes.Length; i += 66)\n {\n var IsLastline = (allBytes.Length - i) < 66;\n var lineLength = IsLastline ? 64 : 66;\n byte[] lineBytes = new byte[lineLength];\n Array.Copy(allBytes, i, lineBytes, 0, lineLength);\n\n\n var outArray = new string[templates.Count];\n int index = 0;\n foreach (var temp in templates)\n {\n byte[] amoutBytes = new byte[temp.CharLength];\n Array.Copy(lineBytes, temp.StartPos - 1, amoutBytes, 0, \n temp.CharLength);\n var final = \"\";\n if (temp.Type == \"Packed\")\n {\n final = Unpack(amoutBytes, temp.DecimalPlace).ToString();\n }\n else\n {\n final = ConvertEbcdicString(amoutBytes);\n }\n\n outArray[index] = final;\n index++;\n\n }\n\n Console.WriteLine(string.Join(\" \", outArray));\n\n }\n\n Console.ReadLine();\n }\n\n\n private static string ConvertEbcdicString(byte[] ebcdicBytes)\n {\n if (ebcdicBytes.All(p => p == 0x00 || p == 0xFF))\n {\n //Every byte is either 0x00 or 0xFF (fillers)\n return string.Empty;\n }\n\n Encoding ebcdicEnc = Encoding.GetEncoding(\"IBM037\");\n string result = ebcdicEnc.GetString(ebcdicBytes); // convert EBCDIC Bytes -> \n Unicode string\n return result;\n }\n\n private static Decimal Unpack(byte[] inp, int scale)\n {\n long lo = 0;\n long mid = 0;\n long hi = 0;\n bool isNegative;\n\n // this nybble stores only the sign, not a digit. \n // \"C\" hex is positive, \"D\" hex is negative, AlphaNumd \"F\" hex is unsigned. \n var ff = nibble(inp, 0);\n switch (ff)\n {\n case 0x0D:\n isNegative = true;\n break;\n case 0x0F:\n case 0x0C:\n isNegative = false;\n break;\n default:\n throw new Exception(\"Bad sign nibble\");\n }\n long intermediate;\n long carry;\n long digit;\n for (int j = inp.Length * 2 - 1; j > 0; j--)\n {\n // multiply by 10\n intermediate = lo * 10;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = mid * 10 + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n intermediate = hi * 10 + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // By limiting input length to 14, we ensure overflow will never occur\n\n digit = nibble(inp, j);\n if (digit > 9)\n {\n throw new Exception(\"Bad digit\");\n }\n intermediate = lo + digit;\n lo = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = mid + carry;\n mid = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n if (carry > 0)\n {\n intermediate = hi + carry;\n hi = intermediate & 0xffffffff;\n carry = intermediate >> 32;\n // carry should never be non-zero. Back up with validation\n }\n }\n }\n return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale);\n }\n\n private static int nibble(byte[] inp, int nibbleNo)\n {\n int b = inp[inp.Length - 1 - nibbleNo / 2];\n return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4);\n }\n\n class Template\n {\n public string Name { get; set; }\n public string Type { get; set; }\n public int StartPos { get; set; }\n public int CharLength { get; set; }\n public int DecimalPlace { get; set; }\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 62325357,
"author": "Will",
"author_id": 13468495,
"author_profile": "https://Stackoverflow.com/users/13468495",
"pm_score": 0,
"selected": false,
"text": "<p>Files must be transferred as binary. Here's a much shorter way to do it:</p>\n\n<pre><code>using System.Linq;\n\nnamespace SomeNamespace\n{\n public static class SomeExtensionClass\n {\n /// <summary>\n /// computes the actual decimal value from an IBM \"Packed Decimal\" 9(x)v9 (COBOL) format\n /// </summary>\n /// <param name=\"value\">byte[]</param>\n /// <param name=\"precision\">byte; decimal places, default 2</param>\n /// <returns>decimal</returns>\n public static decimal FromPackedDecimal(this byte[] value, byte precision = 2)\n {\n if (value.Length < 1)\n {\n throw new System.InvalidOperationException(\"Cannot unpack empty bytes.\");\n }\n double power = System.Math.Pow(10, precision);\n if (power > long.MaxValue)\n {\n throw new System.InvalidOperationException(\n $\"Precision too large for valid calculation: {precision}\");\n }\n string hex = System.BitConverter.ToString(value).Replace(\"-\", \"\");\n var bytes = Enumerable.Range(0, hex.Length)\n .Select(x => System.Convert.ToByte($\"0{hex.Substring(x, 1)}\", 16))\n .ToList();\n long place = 1;\n decimal ret = 0;\n for (int i = bytes.Count - 2; i > -1; i--)\n {\n ret += (bytes[i] * place);\n place *= 10;\n }\n ret /= (long)power;\n return (bytes.Last() & (1 << 7)) != 0 ? ret * -1 : ret;\n }\n }\n}\n</code></pre>\n"
}
]
| 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 the compiler is padding the struct.</p>\n"
},
{
"answer_id": 143033,
"author": "Fred Larson",
"author_id": 10077,
"author_profile": "https://Stackoverflow.com/users/10077",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you mean 'struct', not 'strict', and 'char' instead of 'Char'.</p>\n\n<p>The size will be implementation dependent. On most 32-bit systems, it will probably be 5 -- 4 bytes for the pointer, one for the char. I don't believe alignment will come into play here. If you swapped 'c' and 'b', however, the size may grow to 8 bytes.</p>\n\n<p>Ok, I tried it out (g++ 4.2.3, with -g option) and I get 8.</p>\n"
},
{
"answer_id": 143036,
"author": "mdec",
"author_id": 15534,
"author_profile": "https://Stackoverflow.com/users/15534",
"pm_score": 1,
"selected": false,
"text": "<p>This will vary depending on your architecture and how it treats basic data types. It will also depend on whether the system requires natural alignment. </p>\n"
},
{
"answer_id": 143041,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 2,
"selected": false,
"text": "<p>The exact value is <em>sizeof(a)</em>.<br>\nYou might also take a risk and assume that it is in this case no less than 2 and no greater than 16.</p>\n"
},
{
"answer_id": 143043,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>Contrary to what some of the other answers have said, on most systems, in the absence of a pragma or compiler option, the size of the structure will be at least 6 bytes and, on most 32-bit systems, 8 bytes. For 64-bit systems, the size could easily be 16 bytes. Alignment does come into play; always. The sizeof a single struct has to be such that an array of those sizes can be allocated and the individual members of the array are sufficiently aligned for the processor in question. Consequently, if the size of the struct was 5 as others have hypothesized, then an array of two such structures would be 10 bytes long, and the char pointer in the second array member would be aligned on an odd byte, which would (on most processors) cause a major bottleneck in the performance.</p>\n"
},
{
"answer_id": 143048,
"author": "Simon Buchan",
"author_id": 20135,
"author_profile": "https://Stackoverflow.com/users/20135",
"pm_score": 5,
"selected": false,
"text": "<pre><code>#include <stdio.h>\n\ntypedef struct { char* c; char b; } a;\n\nint main()\n{\n printf(\"sizeof(a) == %d\", sizeof(a));\n}\n</code></pre>\n\n<p>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:</p>\n\n<pre><code>#pragma pack(1)\ntypedef struct { char* c; char b; } a;\n</code></pre>\n\n<p>gives sizeof(a) == 5. If you do this, be careful to reset the packing before any library headers!</p>\n"
},
{
"answer_id": 143051,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 0,
"selected": false,
"text": "<p>The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.</p>\n\n<p>If the structure had the pointer declared after the char, it would still be 8 bytes in size \nbut the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary. </p>\n\n<p>The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.</p>\n"
},
{
"answer_id": 143057,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.</p>\n"
}
]
| 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>public Form1()\n{\n InitializeComponent();\n\n tooltip = new ToolTip();\n tooltip.ShowAlways = true;\n}\n\nprivate ToolTip tooltip;\nprivate void toolStripButton_MouseHover(object sender, EventArgs e)\n{\n if (!this.Focused)\n {\n ToolStripItem tsi = (ToolStripItem)sender;\n tooltip.SetToolTip(toolStrip1, tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text);\n /*tooltip.Show(tsi.AutoToolTip ? tsi.ToolTipText : tsi.Text, this, \n new Point(toolStrip1.Left, toolStrip1.Bottom));*/\n }\n}\n\nprivate void toolStripButton_MouseLeave(object sender, EventArgs e)\n{\n tooltip.RemoveAll();\n}\n</code></pre>\n\n<p>The problem with the first is you can't set it to the button directly, it doesn't inherit from Control, and the tooltip won't show up unless you're over the strip but not over a button.</p>\n\n<p>The problem with the second (commented out way) is it doesn't display at all. Not quite sure why, but maybe you can debug it out.</p>\n"
},
{
"answer_id": 170334,
"author": "foson",
"author_id": 22539,
"author_profile": "https://Stackoverflow.com/users/22539",
"pm_score": 3,
"selected": false,
"text": "<p>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</p>\n\n<pre><code>public class ToolStripDropDownEx : ToolStripDropDownButton\n{\n public ToolStripDropDownEx(string text)\n {\n }\n\n protected override void OnMouseHover(EventArgs e)\n {\n if (this.Parent != null)\n Parent.Focus();\n base.OnMouseHover(e);\n } \n}\n</code></pre>\n"
},
{
"answer_id": 307280,
"author": "Maurice Flanagan",
"author_id": 38791,
"author_profile": "https://Stackoverflow.com/users/38791",
"pm_score": 1,
"selected": false,
"text": "<p>I was trying to do the same thing and determined it was going to be pretty challenging and not worth it. The reason is that internally, the .NET code is specifically designed to only show the tooltip if the window is active - they are checking this at a Win32 level so its going to be hard to fake the code out.</p>\n\n<p>Here is the code snippet in ToolTip.cs that checks \"GetActiveWindow()\" and returns false. You can see the comment in the code \"ToolTips should be shown only on active Windows.\" </p>\n\n<p>By the way, you can see all the source code for the .NET BCL with Visual Studio 2008, here are the instructions I used:</p>\n\n<p><a href=\"http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/sburke/archive/2008/01/16/configuring-visual-studio-to-debug-net-framework-source-code.aspx</a></p>\n\n<pre><code>// refer VsWhidbey 498263: ToolTips should be shown only on active Windows.\nprivate bool IsWindowActive(IWin32Window window)\n{ \n Control windowControl = window as Control;\n // We want to enter in the IF block only if ShowParams does not return SW_SHOWNOACTIVATE. \n // for ToolStripDropDown ShowParams returns SW_SHOWNOACTIVATE, in which case we DONT want to check IsWindowActive and hence return true. \n if ((windowControl.ShowParams & 0xF) != NativeMethods.SW_SHOWNOACTIVATE)\n { \n IntPtr hWnd = UnsafeNativeMethods.GetActiveWindow();\n IntPtr rootHwnd =UnsafeNativeMethods.GetAncestor(new HandleRef(window, window.Handle), NativeMethods.GA_ROOT);\n if (hWnd != rootHwnd)\n { \n TipInfo tt = (TipInfo)tools[windowControl];\n if (tt != null && (tt.TipType & TipInfo.Type.SemiAbsolute) != 0) \n { \n tools.Remove(windowControl);\n DestroyRegion(windowControl); \n }\n return false;\n }\n } \n return true;\n} \n</code></pre>\n"
},
{
"answer_id": 8933286,
"author": "KevinKode",
"author_id": 1159456,
"author_profile": "https://Stackoverflow.com/users/1159456",
"pm_score": 2,
"selected": false,
"text": "<p>i tried a few things and found this to be the simplest</p>\n\n<p>when i create the toolstripbutton items i added an event handler to its hover event:</p>\n\n<pre><code>private sub SomeCodeSnippet()\n\n Me.tooltipMain.ShowAlways = True\n\n Dim tsi As New ToolStripButton(String.Empty, myImage)\n tsi.ToolTipText = \"my tool tip text\"\n toolstripMain.Add(tsi)\n\n AddHandler tsi.MouseHover, AddressOf ToolStripItem_MouseHover\n\nend sub\n</code></pre>\n\n<p>then the event handler:</p>\n\n<pre><code>Private Sub ToolStripItem_MouseHover(ByVal sender As Object, ByVal e As System.EventArgs)\n\n If TypeOf sender Is ToolStripButton Then\n Me.tooltipMain.SetToolTip(Me.toolstripMain, CType(sender, ToolStripButton).ToolTipText)\n End If\n\nEnd Sub\n</code></pre>\n\n<p>this works really nicely, although i do notice a tiny initial delay when you hover over the toolstrip for the 1st time</p>\n"
}
]
| 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 pseudocode):</p>\n\n<pre><code>lock(lockobj);\nwhile (!signalled) {\n wait(condvar);\n}\nsignalled = false;\nunlock(lockobj);\n</code></pre>\n\n<p>on the waiting side, and:</p>\n\n<pre><code>lock(lockobj);\nsignalled = true;\nnotify(condvar);\nunlock(lockobj);\n</code></pre>\n\n<p>on the signalling side. (Of course, the lock object and condition variable used have to be the same on both sides.) Hope this helps!</p>\n"
},
{
"answer_id": 143169,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 0,
"selected": false,
"text": "<p>Alternative answer (also in pseudocode) if you want <em>multiple signallings</em> (i.e., if signalled twice, then two threads can wait before the state is unsignalled again).</p>\n\n<p>Waiting side:</p>\n\n<pre><code>lock(lockobj);\nwhile (signalled != 0) {\n wait(condvar);\n}\n--signalled;\nunlock(lockobj);\n</code></pre>\n\n<p>Signalling side:</p>\n\n<pre><code>lock(lockobj);\n++signalled;\nnotify(condvar);\nunlock(lockobj);\n</code></pre>\n"
},
{
"answer_id": 147358,
"author": "Nicholas Mancuso",
"author_id": 8945,
"author_profile": "https://Stackoverflow.com/users/8945",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up just wrapping a condition type in a new structure and created some simple functions to behave much like the EventWaitHandle from C#. I needed two mutexes to acheive proper serialized access.</p>\n\n<p>The the cond_mutex is used for waiting on the conditional variable, while the data_mutex is used when setting the state from signaled to not signaled.</p>\n\n<p>The reset mode is the same from C#. AUTO or MANUAL. This allows for the event_wait_t to reset itself automatically after waiting. Or letting the programmer manually do it with a call to event_wait_reset(event_wait_t *ewh);</p>\n"
}
]
| 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 had an AM/PM appended to dateStr when I do:</p>\n\n<pre><code>NSLog(@\"%@\", dateStr);\n</code></pre>\n\n<p>Are you doing anything else with dateStr that you didn't post here? How are you checking the value?</p>\n\n<p><strong>Follow up</strong> </p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n\n<p>Okay, I see it when I do this also. It's gotta be a bug. I recommend you <a href=\"https://bugreport.apple.com/\" rel=\"noreferrer\">file a bug report</a> and just check for and filter out the unwanted characters in the meantime. </p>\n"
},
{
"answer_id": 1871619,
"author": "huyz",
"author_id": 161972,
"author_profile": "https://Stackoverflow.com/users/161972",
"pm_score": 4,
"selected": false,
"text": "<p>Here's the explanation of the iPhone SDK bug (also still there in 3.1 beta SDK)</p>\n\n<blockquote>\n <p>First, a little background on the iPhone user interface. When iPhone\n users change their region format between, say, “United States” and\n “France”, the users’ “24-Hour Time” setting is automatically switched\n to the mode that is most prevalent in that region. In France, that\n would set 24-Hour Time to “ON”, and in the U.S., that would set it to\n “OFF”. The users can then manually override that setting and that’s\n where trouble starts.</p>\n \n <p>The problem comes from NSDateFormatter somehow “getting stuck” in the\n 12 or 24-hour time mode that the user has manually selected. So if a\n French user manually selects 12-hour mode, and the application\n requested NSDateFormatter to output time with the 24-hour format\n “HHmm”, it would actually receive time in a 12-hour format, e.g.\n “01:00 PM”, as if the application had instead requested “hhmm aa”. \n The reverse would happen if a US user manually selected 24-hour mode:\n outputting time with the 12-hour format “hhmm aa” would actually get\n you time in the 24-hour format instead, e.g. “17:00″.</p>\n</blockquote>\n\n<p>More details and a possible workaround can be found on this <a href=\"http://multinc.com/2009/09/27/iphone-sdk-time-bug-for-international-users/\" rel=\"noreferrer\">blog</a>.</p>\n"
},
{
"answer_id": 3174866,
"author": "jbg",
"author_id": 91420,
"author_profile": "https://Stackoverflow.com/users/91420",
"pm_score": 1,
"selected": false,
"text": "<p>For those finding this question who want to use NSDateFormatter to parse 24-hour time and are hitting this bug, using NSDateComponents to parse dates and times which have a known format sidesteps this issue:</p>\n\n<pre><code>NSString *dateStr = @\"2010-07-05\";\nNSString *timeStr = @\"13:30\";\n\nNSDateComponents *components = [[NSDateComponents alloc] init];\ncomponents.year = [[dateStr substringToIndex:4] intValue];\ncomponents.month = [[dateStr substringWithRange:NSMakeRange(5, 2)] intValue];\ncomponents.day = [[dateStr substringFromIndex:8] intValue];\ncomponents.hour = [[timeStr substringToIndex:2] intValue];\ncomponents.minute = [[timeStr substringFromIndex:3] intValue];\n\nNSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];\n\nNSDate *date = [calendar dateFromComponents:components];\n\n[components release];\n[calendar release];\n</code></pre>\n"
},
{
"answer_id": 3269073,
"author": "Ethel",
"author_id": 335698,
"author_profile": "https://Stackoverflow.com/users/335698",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the solution . </p>\n\n<pre><code>NSDateFormatter *df =[[NSDateFormatter alloc] init];\n [df setDateFormat:@\"yyyy-MM-dd HH:mm:ss\"];\n NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"];\n\n[df setLocale: usLocale];\n\n[usLocale release];\n\n NSDate *documento_en_Linea =[[[NSDate alloc] init]autorelease];\n\ndocumento_en_Linea=[df dateFromString:@\"2010-07-16 21:40:33\"];\n\n[df release];\n\n NSLog(@\"fdocumentoenLineaUTC:%@!\",documento_en_Linea);\n\n\n//ouput \n fdocumentoenLineaUTC:2010-07-16 09:40:33 p.m. -0500!\n</code></pre>\n"
},
{
"answer_id": 3693419,
"author": "valexa",
"author_id": 314546,
"author_profile": "https://Stackoverflow.com/users/314546",
"pm_score": 0,
"selected": false,
"text": "<p>This should also work (I am seeing some bizzare results though).</p>\n\n<pre><code>-(NSString*)lowLevTime:(NSString*)stringFormat {\n char buffer[50];\n const char *format = [stringFormat UTF8String];\n time_t rawtime;\n struct tm * timeinfo;\n time(&rawtime);\n timeinfo = localtime(&rawtime);\n strftime(buffer, sizeof(buffer), format, timeinfo);\n return [NSString stringWithCString:buffer encoding:NSASCIIStringEncoding];\n}\n</code></pre>\n"
},
{
"answer_id": 6066695,
"author": "DenNukem",
"author_id": 118878,
"author_profile": "https://Stackoverflow.com/users/118878",
"pm_score": 3,
"selected": false,
"text": "<p>Setting locale on date formatter to en_US fixes the problem for me:</p>\n\n<pre><code> NSDateFormatter * f = [[NSDateFormatter alloc] init];\n [f setDateFormat:@\"yyyy-MM-dd'T'HH:mm:ss'Z'\"];\n f.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];\n f.calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];\n f.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@\"en_US\"] autorelease];\n</code></pre>\n\n<p>I'm not sure if adding the calendar is also needed, but this works well.</p>\n"
},
{
"answer_id": 11128870,
"author": "Arthulia",
"author_id": 1470567,
"author_profile": "https://Stackoverflow.com/users/1470567",
"pm_score": 0,
"selected": false,
"text": "<p>Short answer: try <code>[dateFormatter setDateFormat:@\"yyyyMMddhhmmss\"];</code> for 12 hour format (note the lowercase <code>hh</code>). </p>\n\n<p>It's been a frustrating topic because so many websites indicate to use <code>HH</code> for hours (including the official Apple documentation), but that sets it to 24 hour format, whereas <code>hh</code> uses 12 hour format. See <a href=\"http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns\" rel=\"nofollow\">http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns</a> for more details.</p>\n\n<p>As a bonus, note that you can also use <code>KK</code> or <code>kk</code> for hour of the day format, which will likely be off by one.</p>\n\n<p>Update:\nI was recently looking at NSLocale (https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSLocale_Class/Reference/Reference.html) and it would seem that you can use autoupdatingCurrentLocale to apply changes made from within the app to the Locale. The upshot of this is that even if the phone is set to use a 24 hour clock (like when you switched to France), you can make a 12/24 toggle for the app that won't impact any other apps on the phone, or require you to leave the app to make the change.</p>\n"
},
{
"answer_id": 19857973,
"author": "Toseef Khilji",
"author_id": 1597744,
"author_profile": "https://Stackoverflow.com/users/1597744",
"pm_score": 5,
"selected": false,
"text": "<p>The reason for this behaviour is Locale, It sets the correct Locale.</p>\n\n<p>Set the local of your <strong>NSDateFormatter</strong> to <strong>en_US_POSIX</strong> will fix this.\nIt works for both 24-hour and 12 hour format.</p>\n\n<p><code>On iPhone OS, the user can override the default AM/PM versus 24-hour time setting (via Settings > General > Date & Time > 24-Hour Time), which causes NSDateFormatter to rewrite the format string you set.</code> From <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1\" rel=\"nofollow noreferrer\">apple doc</a> </p>\n\n<p>Try this,</p>\n\n<pre><code>NSDate *today = [[NSDate alloc] init];\nNSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];\n[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@\"en_US_POSIX\"]];\n[dateFormatter setDateFormat:@\"yyyyMMddHHmmss\"];\nNSString *dateStr = [dateFormatter stringFromDate:today];\n</code></pre>\n"
}
]
| 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>AbstractFoo</code>), which has all the functionality. What difference in behaviour should exist between <code>Foo</code> and <code>Bar</code>? Code that difference as an abstract method in <code>AbstractFoo</code>, not by using a <code>if</code> statement in your code.</p>\n\n<p>Example: Rather than this:</p>\n\n<pre><code>if (foo instanceof Bar) {\n // Do Bar-specific things\n}\n</code></pre>\n\n<p>Do this instead:</p>\n\n<pre><code>class Bar extends AbstractFoo {\n public void specialOp() {\n // Do Bar-specific things\n }\n}\n\n// ...\nfoo.specialOp();\n</code></pre>\n\n<p>The benefit of this approach is that if you need a third class, that's much like <code>Foo</code> but has just a little bit of difference, you don't have to go through all your code and add edit all the <code>if</code> statements. :-)</p>\n"
},
{
"answer_id": 143093,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 0,
"selected": false,
"text": "<p>Definitely use a boolean property. It's the simplest solution, unless you foresee the Bar class needing to change it's interface later (e.g. override it's methods).</p>\n"
},
{
"answer_id": 143109,
"author": "Lev",
"author_id": 7224,
"author_profile": "https://Stackoverflow.com/users/7224",
"pm_score": 0,
"selected": false,
"text": "<p>Inheritance is best.<br>\nWith a boolean property, the class must know about the existence of two different types of objects, and this isn't easily extensible to more than two. Moreover, this approach doesn't let you overload functions.<br>\nComposition makes you write wrappers for all functions.</p>\n"
},
{
"answer_id": 143112,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 2,
"selected": false,
"text": "<p><strong>It all depends on meaning of the Foo and Bar classes. What they represent, and what's their purpose. Please clarify.</strong></p>\n\n<p>I can imagine situations when each of your solutions and proposed solutions is the right one.</p>\n"
},
{
"answer_id": 143135,
"author": "csmba",
"author_id": 350,
"author_profile": "https://Stackoverflow.com/users/350",
"pm_score": 0,
"selected": false,
"text": "<p>your data was not clear enough, but based on what I think you need, I am puzzled why you don't simply go with a 4th option:</p>\n\n<pre><code>Class MainStuff;\nClass TypeA;\nClass TypeB;\n</code></pre>\n\n<p>No either make TypeA and B inherit from MainStuff, or make MainStuff a data member of TypeA and TypeB. This depends on the meaning of what these 3 classes are.</p>\n"
},
{
"answer_id": 143143,
"author": "fenomas",
"author_id": 10651,
"author_profile": "https://Stackoverflow.com/users/10651",
"pm_score": 2,
"selected": false,
"text": "<p>If there is any likelihood that <code>Foo</code> and <code>Bar</code> could someday diverge in implementation, then your question is answered - use inheritance in whatever way seems best.</p>\n\n<p>But if you're absolutely sure that they'll never diverge, then clearly you're looking at something that should be represented by a single class, such as <code>ThingThatIsEitherFooOrBar</code>.</p>\n\n<p>And with that class made, rather than giving it a boolean property like <code>isFoo</code>, it would be much better to take another look at why you need to differentiate Foo from Bar. What is it about Foos that makes you handle them differently than Bars? Figure that out, and make a property that specifies the information that differs. Are Foos bigger? Then make a property for size (even if it's an enum with values \"Foo-sized\" and \"Bar-sized\").</p>\n\n<p>That's about as much as one can say without specific examples of what Foo and Bar might be.</p>\n"
},
{
"answer_id": 143371,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<h2>Foo and Bar inherit from FooBarImplementation</h2>\n\n<p>I'd make a class FooBarImplementation that would implement the common features of Foo and Bar. Foo and Bar would derive from it. But in your code, never <strong>ever</strong> use the type FooBarImplementation. My Java days are somewhat behind me, but I guess there must be some kind of way to hide FooBarImplementation from the user code (making it protected, or package visible only, depending on your project organization. This way, no user code will mix Foo for a Bar (and vice versa)?</p>\n\n<pre><code>class FooBarImplementation\n{\n public void doSomething() { /* etc. */ }\n /* etc. */\n}\n\nclass Foo inherits FooBarImplementation { /* etc. */ }\nclass Bar inherits FooBarImplementation { /* etc. */ }\n</code></pre>\n\n<h2>Foo and Bar composed with FooBarImplementation</h2>\n\n<p>Another possibility would be to make Foo and Bar forward each of their methods to an internal class (again, FooBarImplementation). This way, there's no way the user code could be Foo and Bar.</p>\n\n<pre><code>class FooBarImplementation\n{\n public void doSomething() { /* etc. */ }\n /* etc. */\n}\n\nclass Foo\n{\n private FooBarImplementation fooBarImplementation = new FooBarImplementation() ;\n\n public void doSomething() { this.fooBarImplementation.doSomething() ; }\n /* etc. */\n}\n\n\nclass Bar\n{\n private FooBarImplementation fooBarImplementation = new FooBarImplementation() ;\n\n public void doSomething() { this.fooBarImplementation.doSomething() ; }\n /* etc. */\n}\n</code></pre>\n\n<h2>Do NOT make Foo inherits from Bar (or vice versa)</h2>\n\n<p>Shoudl Foo inherits from Barn, Foo would be a Bar, as far as the language is concerned. Don't do it, you'll lose the difference between the objects, and this is what you don't want.</p>\n\n<h2>Do not use boolean, and whataver type field</h2>\n\n<p>This is the worst idea you could come accross. Bjarne Stroustrup warned against this kind of antipattern for C++, and C++ is not all about OOP. So I guess this pattern is even more \"anti\" for Java... :-)</p>\n"
},
{
"answer_id": 143406,
"author": "Tetha",
"author_id": 17663,
"author_profile": "https://Stackoverflow.com/users/17663",
"pm_score": 0,
"selected": false,
"text": "<p>As others said, it depends, but if you have common functionality between Foo and Bar and the difference in functionality can be expressed as parameters, then I vote for subclasses.\nThis was basically what we were doing in the end of a practical software course. </p>\n\n<p>We should implement a sudoku-game, and in the end, we had an \"AbstractPlayfield\", which was able to apply an arbitrary set of rules to an arbitrary playfield. This AbstractPlayfield was subclassed by the individual variants we were supposed to implement. Those subclasses set parameters (mostly the rules and the shape of the board) for the abstract playfield and everything worked like a charm. We even ended up with more inheritance in those subclasses, because several of the variants contained the rules \"Numbers must be unique in a row\" and \"Numbers must be unique in a column\".<br>\nUsing that, we were able to finish the work that was estimated for about 2 month in about 3 days :) (And they annoyed us with \"Test those tiny attribute-setting classes, because you might have bugs in there! Test them! Test them! We dont care that all important logic is tested!\".)</p>\n\n<p>On the other hand, if the class Bar has no special different functionality from Bar, I do not see the point of adding it - at least from the data you give me. It might make sense if you wanted to do some operations based on types and dispatch on type, but I cannot read that from Foo and Bar. In this case, I'd not create Bar, due to YAGNI. </p>\n"
},
{
"answer_id": 144340,
"author": "Martin OConnor",
"author_id": 18233,
"author_profile": "https://Stackoverflow.com/users/18233",
"pm_score": 1,
"selected": false,
"text": "<p>Basically you need to apply the <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">Strategy Pattern</a>.</p>\n"
},
{
"answer_id": 150094,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If there is no behavioral difference between Foo and Bar, then the class name \"Foo\" is not abstract enough. Identify the common abstraction between Foo and Bar and rename the class accordingly. Then provide a member field in the class to identify instances as \"Foo\", \"Bar\", etc. Use an enum if you wish to limit possible values to \"Foo\" and \"Bar\".</p>\n"
}
]
| 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$newsXML->addAttribute('newsPagePrefix', 'value goes here');\n$newsIntro = $newsXML->addChild('content');\n$newsIntro->addAttribute('type', 'latest');\nHeader('Content-type: text/xml');\necho $newsXML->asXML();\n?>\n</code></pre>\n\n<p>Output</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<news newsPagePrefix=\"value goes here\">\n <content type=\"latest\"/>\n</news>\n</code></pre>\n\n<p>Have fun.</p>\n"
},
{
"answer_id": 143260,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 5,
"selected": false,
"text": "<p>In PHP5, you should use the <a href=\"http://us3.php.net/manual/en/book.dom.php\" rel=\"noreferrer\" title=\"Document Object Model\">Document Object Model</a> class instead.\nExample:</p>\n\n<pre><code>$domDoc = new DOMDocument;\n$rootElt = $domDoc->createElement('root');\n$rootNode = $domDoc->appendChild($rootElt);\n\n$subElt = $domDoc->createElement('foo');\n$attr = $domDoc->createAttribute('ah');\n$attrVal = $domDoc->createTextNode('OK');\n$attr->appendChild($attrVal);\n$subElt->appendChild($attr);\n$subNode = $rootNode->appendChild($subElt);\n\n$textNode = $domDoc->createTextNode('Wow, it works!');\n$subNode->appendChild($textNode);\n\necho htmlentities($domDoc->saveXML());\n</code></pre>\n"
},
{
"answer_id": 143350,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 4,
"selected": false,
"text": "<p>Please see my answer <a href=\"https://stackoverflow.com/questions/139650/when-writing-xml-is-it-better-to-hand-write-it-or-to-use-a-generator-such-as-si#140203\">here</a>. As <a href=\"https://stackoverflow.com/users/15487/dreamwerxmyopenidcom\">dreamwerx.myopenid.com</a> points out, it is possible to do this with <a href=\"http://de.php.net/manual/en/book.simplexml.php\" rel=\"nofollow noreferrer\">SimpleXML</a>, but the <a href=\"http://de3.php.net/manual/en/book.dom.php\" rel=\"nofollow noreferrer\">DOM extension</a> would be the better and more flexible way. Additionally there is a third way: using <a href=\"http://de3.php.net/manual/en/intro.xmlwriter.php\" rel=\"nofollow noreferrer\">XMLWriter</a>. It's much more simple to use than the DOM and therefore it's my preferred way of writing XML documents from scratch.</p>\n\n<pre><code>$w=new XMLWriter();\n$w->openMemory();\n$w->startDocument('1.0','UTF-8');\n$w->startElement(\"root\");\n $w->writeAttribute(\"ah\", \"OK\");\n $w->text('Wow, it works!');\n$w->endElement();\necho htmlentities($w->outputMemory(true));\n</code></pre>\n\n<p>By the way: <a href=\"http://www.w3.org/DOM/\" rel=\"nofollow noreferrer\">DOM</a> stands for <strong>D</strong>ocument <strong>O</strong>bject <strong>M</strong>odel; this is the standardized API into XML documents.</p>\n"
}
]
| 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 an example:</p>\n\n<pre><code>#define MY_BUFFER_SIZE 1024\n\nchar mybuffer[MY_BUFFER_SIZE];\nint nBytes = read(sck, mybuffer, MY_BUFFER_SIZE);\n</code></pre>\n"
},
{
"answer_id": 143197,
"author": "Maciej Hehl",
"author_id": 19939,
"author_profile": "https://Stackoverflow.com/users/19939",
"pm_score": 0,
"selected": false,
"text": "<p>Your sockets implementation doesn't require the buffer, to be big enough, to hold the entire message for sure, but it might be convenient depending on, what You are doing.</p>\n"
},
{
"answer_id": 204321,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 3,
"selected": false,
"text": "<p>As always, use <code>sizeof</code> when you have the chance. Using the built-in operator <code>sizeof</code>, you ask the compiler to compute the size of a variable, rather than specify it yourself. This reduces the risk of introducing bugs when the size of the actual variable is different from what you think.</p>\n\n<p>So, instead of doing</p>\n\n<pre><code>#define BUFSIZE 1500\nchar buffer[BUFSIZE];\nint n = read(sock, buffer, BUFSIZE);\n</code></pre>\n\n<p>you really should use</p>\n\n<pre><code>char buffer[1500];\nint n = read(sock, buffer, sizeof buffer);\n</code></pre>\n\n<p>Notice how you don't need parenthesis around the argument to sizeof, unless the argument is the name of a type.</p>\n"
}
]
| 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> supports <code>--null</code>, nor whether <code>xargs</code> supports <code>-0</code>, on Leopard, but on GNU it's all good.</p>\n"
},
{
"answer_id": 143173,
"author": "Shannon Nelson",
"author_id": 14450,
"author_profile": "https://Stackoverflow.com/users/14450",
"pm_score": 3,
"selected": false,
"text": "<p>Look into using the --null commandline option for xargs with the -print0 option in find.</p>\n"
},
{
"answer_id": 143222,
"author": "godbyk",
"author_id": 4214,
"author_profile": "https://Stackoverflow.com/users/4214",
"pm_score": 9,
"selected": true,
"text": "<p>You can combine all of that into a single <code>find</code> command:</p>\n\n<pre><code>find . -iname \"*foobar*\" -exec cp -- \"{}\" ~/foo/bar \\;\n</code></pre>\n\n<p>This will handle filenames and directories with spaces in them. You can use <code>-name</code> to get case-sensitive results. </p>\n\n<p>Note: The <code>--</code> flag passed to <code>cp</code> prevents it from processing files starting with <code>-</code> as options.</p>\n"
},
{
"answer_id": 149026,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 6,
"selected": false,
"text": "<p>This is more efficient as it does not run \"cp\" multiple times:</p>\n\n<pre><code>find -name '*FooBar*' -print0 | xargs -0 cp -t ~/foo/bar\n</code></pre>\n"
},
{
"answer_id": 161159,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>Be aware that most of the options discussed in other answers are not standard on platforms that do not use the GNU utilities (Solaris, AIX, HP-UX, for instance). See the <a href=\"http://www.opengroup.org/onlinepubs/009695399/toc.htm\" rel=\"nofollow noreferrer\">POSIX</a> specification for 'standard' xargs behaviour.</p>\n\n<p>I also find the behaviour of xargs whereby it runs the command at least once, even with no input, to be a nuisance.</p>\n\n<p>I wrote my own private version of xargs (xargl) to deal with the problems of spaces in names (only newlines separate - though the 'find ... -print0' and 'xargs -0' combination is pretty neat given that file names cannot contain ASCII NUL '\\0' characters. My xargl isn't as complete as it would need to be to be worth publishing - especially since GNU has facilities that are at least as good.</p>\n"
},
{
"answer_id": 474907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I have found that the following syntax works well for me.</p>\n\n<pre><code>find /usr/pcapps/ -mount -type f -size +1000000c | perl -lpe ' s{ }{\\\\ }g ' | xargs ls -l | sort +4nr | head -200\n</code></pre>\n\n<p>In this example, I am looking for the largest 200 files over 1,000,000 bytes in the filesystem mounted at \"/usr/pcapps\".</p>\n\n<p>The Perl line-liner between \"find\" and \"xargs\" escapes/quotes each blank so \"xargs\" passes any filename with embedded blanks to \"ls\" as a single argument.</p>\n"
},
{
"answer_id": 1004726,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/143171/how-can-i-use-xargs-to-copy-files-that-have-spaces-and-quotes-in-their-names#474907\">bill_starr's Perl version</a> won't work well for embedded newlines (only copes with spaces). For those on e.g. Solaris where you don't have the GNU tools, a more complete version might be (using sed)...</p>\n\n<pre><code>find -type f | sed 's/./\\\\&/g' | xargs grep string_to_find\n</code></pre>\n\n<p>adjust the find and grep arguments or other commands as you require, but the sed will fix your embedded newlines/spaces/tabs.</p>\n"
},
{
"answer_id": 4064129,
"author": "Carl Yamamoto-Furst",
"author_id": 492879,
"author_profile": "https://Stackoverflow.com/users/492879",
"pm_score": 1,
"selected": false,
"text": "<p>I used <a href=\"https://stackoverflow.com/questions/143171/how-can-i-use-xargs-to-copy-files-that-have-spaces-and-quotes-in-their-names#474907\">Bill Star's answer</a> slightly modified on Solaris:</p>\n\n<pre><code>find . -mtime +2 | perl -pe 's{^}{\\\"};s{$}{\\\"}' > ~/output.file\n</code></pre>\n\n<p>This will put quotes around each line. I didn't use the '-l' option although it probably would help.</p>\n\n<p>The file list I was going though might have '-', but not newlines. I haven't used the output file with any other commands as I want to review what was found before I just start massively deleting them via xargs.</p>\n"
},
{
"answer_id": 9219776,
"author": "mavit",
"author_id": 487095,
"author_profile": "https://Stackoverflow.com/users/487095",
"pm_score": 3,
"selected": false,
"text": "<pre><code>find | perl -lne 'print quotemeta' | xargs ls -d\n</code></pre>\n\n<p>I believe that this will work reliably for any character except line-feed (and I suspect that if you've got line-feeds in your filenames, then you've got worse problems than this). It doesn't require GNU findutils, just Perl, so it should work pretty-much anywhere.</p>\n"
},
{
"answer_id": 12067078,
"author": "oyouareatubeo",
"author_id": 1067630,
"author_profile": "https://Stackoverflow.com/users/1067630",
"pm_score": 6,
"selected": false,
"text": "<p>I ran into the same problem. Here's how I solved it:</p>\n\n<pre><code>find . -name '*FoooBar*' | sed 's/.*/\"&\"/' | xargs cp ~/foo/bar\n</code></pre>\n\n<p>I used <code>sed</code> to substitute each line of input with the same line, but surrounded by double quotes. From the <code>sed</code> man page, \"<em>...An ampersand (``&'') appearing in the replacement is replaced by the string matching the RE...</em>\" -- in this case, <code>.*</code>, the entire line. </p>\n\n<p>This solves the <code>xargs: unterminated quote</code> error.</p>\n"
},
{
"answer_id": 17325049,
"author": "fred",
"author_id": 1289107,
"author_profile": "https://Stackoverflow.com/users/1289107",
"pm_score": 0,
"selected": false,
"text": "<p>You might need to grep Foobar directory like:</p>\n\n<pre><code>find . -name \"file.ext\"| grep \"FooBar\" | xargs -i cp -p \"{}\" .\n</code></pre>\n"
},
{
"answer_id": 17325825,
"author": "jlliagre",
"author_id": 211665,
"author_profile": "https://Stackoverflow.com/users/211665",
"pm_score": 4,
"selected": false,
"text": "<p>Just don't use <code>xargs</code>. It is a neat program but it doesn't go well with <code>find</code> when faced with non trivial cases.</p>\n\n<p>Here is a portable (POSIX) solution, i.e. one that doesn't require <code>find</code>, <code>xargs</code> or <code>cp</code> GNU specific extensions:</p>\n\n<pre><code>find . -name \"*FooBar*\" -exec sh -c 'cp -- \"$@\" ~/foo/bar' sh {} +\n</code></pre>\n\n<p>Note the ending <code>+</code> instead of the more usual <code>;</code>.</p>\n\n<p>This solution:</p>\n\n<ul>\n<li><p>correctly handles files and directories with embedded spaces, newlines or whatever exotic characters.</p></li>\n<li><p>works on any Unix and Linux system, even those not providing the GNU toolkit.</p></li>\n<li><p>doesn't use <code>xargs</code> which is a nice and useful program, but requires too much tweaking and non standard features to properly handle <code>find</code> output.</p></li>\n<li><p>is also <strong>more efficient</strong> (read <strong>faster</strong>) than the accepted and most if not all of the other answers.</p></li>\n</ul>\n\n<p>Note also that despite what is stated in some other replies or comments quoting <code>{}</code> is useless (unless you are using the exotic <code>fish</code>shell). </p>\n"
},
{
"answer_id": 18496493,
"author": "frediy",
"author_id": 2559037,
"author_profile": "https://Stackoverflow.com/users/2559037",
"pm_score": 6,
"selected": false,
"text": "<p>This method works on <a href=\"http://en.wikipedia.org/wiki/Mac_OS_X_Lion\" rel=\"noreferrer\">Mac OS X v10.7.5</a> (Lion):</p>\n\n<pre><code>find . | grep FooBar | xargs -I{} cp {} ~/foo/bar\n</code></pre>\n\n<p>I also tested the exact syntax you posted. That also worked fine on 10.7.5.</p>\n"
},
{
"answer_id": 20868963,
"author": "StackedCrooked",
"author_id": 75889,
"author_profile": "https://Stackoverflow.com/users/75889",
"pm_score": 2,
"selected": false,
"text": "<p>With Bash (not POSIX) you can use process substitution to get the current line inside a variable. This enables you to use quotes to escape special characters:</p>\n\n<pre><code>while read line ; do cp \"$line\" ~/bar ; done < <(find . | grep foo)\n</code></pre>\n"
},
{
"answer_id": 22535558,
"author": "Aleksandr Guidrevitch",
"author_id": 1199707,
"author_profile": "https://Stackoverflow.com/users/1199707",
"pm_score": 3,
"selected": false,
"text": "<p>For those who relies on commands, other than find, eg <code>ls</code>:</p>\n\n<pre><code>find . | grep \"FooBar\" | tr \\\\n \\\\0 | xargs -0 -I{} cp \"{}\" ~/foo/bar\n</code></pre>\n"
},
{
"answer_id": 23773189,
"author": "Lenik",
"author_id": 217071,
"author_profile": "https://Stackoverflow.com/users/217071",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using Bash, you can convert <em>stdout</em> to an array of lines by <code>mapfile</code>:</p>\n\n<pre><code>find . | grep \"FooBar\" | (mapfile -t; cp \"${MAPFILE[@]}\" ~/foobar)\n</code></pre>\n\n<p>The benefits are:</p>\n\n<ul>\n<li>It's built-in, so it's faster.</li>\n<li>Execute the command with all file names in one time, so it's faster.</li>\n<li><p>You can append other arguments to the file names. For <code>cp</code>, you can also:</p>\n\n<pre><code>find . -name '*FooBar*' -exec cp -t ~/foobar -- {} +\n</code></pre>\n\n<p>however, some commands don't have such feature.</p></li>\n</ul>\n\n<p>The disadvantages:</p>\n\n<ul>\n<li>Maybe not scale well if there are too many file names. (The limit? I don't know, but I had tested with 10 MB list file which includes 10000+ file names with no problem, under Debian)</li>\n</ul>\n\n<p>Well... who knows if Bash is available on OS X?</p>\n"
},
{
"answer_id": 29303513,
"author": "Jan Ptáčník",
"author_id": 4101469,
"author_profile": "https://Stackoverflow.com/users/4101469",
"pm_score": 1,
"selected": false,
"text": "<p>If find and xarg versions on your system doesn't support <code>-print0</code> and <code>-0</code> switches (for example AIX find and xargs) you can use this terribly looking code:</p>\n\n<pre><code> find . -name \"*foo*\" | sed -e \"s/'/\\\\\\'/g\" -e 's/\"/\\\\\"/g' -e 's/ /\\\\ /g' | xargs cp /your/dest\n</code></pre>\n\n<p>Here sed will take care of escaping the spaces and quotes for xargs.</p>\n\n<p>Tested on AIX 5.3</p>\n"
},
{
"answer_id": 31841671,
"author": "John Allsup",
"author_id": 2138913,
"author_profile": "https://Stackoverflow.com/users/2138913",
"pm_score": 1,
"selected": false,
"text": "<p>I played with this a little, started contemplating modifying xargs, and realised that for the kind of use case we're talking about here, a simple reimplementation in Python is a better idea.</p>\n\n<p>For one thing, having ~80 lines of code for the whole thing means it is easy to figure out what is going on, and if different behaviour is required, you can just hack it into a new script in less time than it takes to get a reply on somewhere like Stack Overflow.</p>\n\n<p>See <a href=\"https://github.com/johnallsup/jda-misc-scripts/blob/master/yargs\" rel=\"nofollow noreferrer\">https://github.com/johnallsup/jda-misc-scripts/blob/master/yargs</a> and <a href=\"https://github.com/johnallsup/jda-misc-scripts/blob/master/zargs.py\" rel=\"nofollow noreferrer\">https://github.com/johnallsup/jda-misc-scripts/blob/master/zargs.py</a>.</p>\n\n<p>With yargs as written (and Python 3 installed) you can type:</p>\n\n<pre><code>find .|grep \"FooBar\"|yargs -l 203 cp --after ~/foo/bar\n</code></pre>\n\n<p>to do the copying 203 files at a time. (Here 203 is just a placeholder, of course, and using a strange number like 203 makes it clear that this number has no other significance.)</p>\n\n<p>If you really want something faster and without the need for Python, take zargs and yargs as prototypes and rewrite in C++ or C.</p>\n"
},
{
"answer_id": 33005355,
"author": "Moises",
"author_id": 5420970,
"author_profile": "https://Stackoverflow.com/users/5420970",
"pm_score": 2,
"selected": false,
"text": "<p>For me, I was trying to do something a little different. I wanted to copy my .txt files into my tmp folder. The .txt filenames contain spaces and apostrophe characters. This worked on my Mac.</p>\n\n<pre><code>$ find . -type f -name '*.txt' | sed 's/'\"'\"'/\\'\"'\"'/g' | sed 's/.*/\"&\"/' | xargs -I{} cp -v {} ./tmp/\n</code></pre>\n"
},
{
"answer_id": 33528111,
"author": "user87601",
"author_id": 4364138,
"author_profile": "https://Stackoverflow.com/users/4364138",
"pm_score": 7,
"selected": false,
"text": "<p>The easiest way to do what the original poster wants is to change the delimiter from any whitespace to just the end-of-line character like this:</p>\n\n<pre><code>find whatever ... | xargs -d \"\\n\" cp -t /var/tmp\n</code></pre>\n"
},
{
"answer_id": 49340007,
"author": "Guenther Brunthaler",
"author_id": 4411491,
"author_profile": "https://Stackoverflow.com/users/4411491",
"pm_score": 1,
"selected": false,
"text": "<p>I created a small portable wrapper script called \"xargsL\" around \"xargs\" which addresses most of the problems.</p>\n\n<p>Contrary to xargs, xargsL accepts one pathname per line. The pathnames may contain any character except (obviously) newline or NUL bytes.</p>\n\n<p>No quoting is allowed or supported in the file list - your file names may contain all sorts of whitespace, backslashes, backticks, shell wildcard characters and the like - xargsL will process them as literal characters, no harm done.</p>\n\n<p>As an added bonus feature, xargsL will <em>not</em> run the command once if there is no input!</p>\n\n<p>Note the difference:</p>\n\n<pre><code>$ true | xargs echo no data\nno data\n\n$ true | xargsL echo no data # No output\n</code></pre>\n\n<p>Any arguments given to xargsL will be passed through to xargs.</p>\n\n<p>Here is the \"xargsL\" POSIX shell script:</p>\n\n<blockquote>\n<pre><code>#! /bin/sh\n# Line-based version of \"xargs\" (one pathname per line which may contain any\n# amount of whitespace except for newlines) with the added bonus feature that\n# it will not execute the command if the input file is empty.\n#\n# Version 2018.76.3\n#\n# Copyright (c) 2018 Guenther Brunthaler. All rights reserved.\n#\n# This script is free software.\n# Distribution is permitted under the terms of the GPLv3.\n\nset -e\ntrap 'test $? = 0 || echo \"$0 failed!\" >& 2' 0\n\nif IFS= read -r first\nthen\n {\n printf '%s\\n' \"$first\"\n cat\n } | sed 's/./\\\\&/g' | xargs ${1+\"$@\"}\nfi\n</code></pre>\n</blockquote>\n\n<p>Put the script into some directory in your $PATH and don't forget to</p>\n\n<p><code>$ chmod +x xargsL</code></p>\n\n<p>the script there to make it executable.</p>\n"
},
{
"answer_id": 56803676,
"author": "gerrit",
"author_id": 974555,
"author_profile": "https://Stackoverflow.com/users/974555",
"pm_score": 2,
"selected": false,
"text": "<p>Frame challenge — you're asking how to use xargs. The answer is: you don't use xargs, because you don't need it.</p>\n\n<p>The <a href=\"https://stackoverflow.com/questions/143171/how-can-i-use-xargs-to-copy-files-that-have-spaces-and-quotes-in-their-names#comment20387811_143222\">comment by <code>user80168</code></a> describes a way to do this directly with cp, without calling cp for every file:</p>\n\n<pre><code>find . -name '*FooBar*' -exec cp -t /tmp -- {} +\n</code></pre>\n\n<p>This works because:</p>\n\n<ul>\n<li>the <code>cp -t</code> flag allows to give the target directory near the beginning of <code>cp</code>, rather than near the end. From <code>man cp</code>:</li>\n</ul>\n\n<blockquote>\n<pre><code> -t, --target-directory=DIRECTORY\n copy all SOURCE arguments into DIRECTORY\n</code></pre>\n</blockquote>\n\n<ul>\n<li><p>The <code>--</code> flag tells <code>cp</code> to interpret everything after as a filename, not a flag, so files starting with <code>-</code> or <code>--</code> do not confuse <code>cp</code>; you still need this because the <code>-</code>/<code>--</code> characters are interpreted by <code>cp</code>, whereas any other special characters are interpreted by the shell.</p></li>\n<li><p>The <code>find -exec command {} +</code> variant essentially does the same as xargs. From <code>man find</code>:</p></li>\n</ul>\n\n<blockquote>\n<pre><code> -exec command {} + \n This variant of the -exec action runs the specified command on\n the selected files, but the command line is built by appending\n each selected file name at the end; the total number of invoca‐\n matched files. The command line is built in much the same way\n that xargs builds its command lines. Only one instance of `{}'\n is allowed within the command, and (when find is being invoked\n from a shell) it should be quoted (for example, '{}') to protect\n it from interpretation by shells. The command is executed in\n the starting directory. If any invocation returns a non-zero\n value as exit status, then find returns a non-zero exit status.\n If find encounters an error, this can sometimes cause an immedi‐\n ate exit, so some pending commands may not be run at all. This\n variant of -exec always returns true.\n</code></pre>\n</blockquote>\n\n<p>By using this in find directly, this avoids the need of a pipe or a shell invocation, such that you don't need to worry about any nasty characters in filenames.</p>\n"
}
]
| 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\">GetCurrentDirectory</a> should do the trick.</p>\n"
},
{
"answer_id": 143178,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": false,
"text": "<p>No, there's no standard way. I believe that the C/C++ standards don't even consider the existence of directories (or other file system organizations).</p>\n\n<p>On Windows the <strong>GetModuleFileName()</strong> will return the full path to the executable file of the current process when the <strong>hModule</strong> parameter is set to <strong>NULL</strong>. I can't help with Linux.</p>\n\n<p><strike>Also you should clarify whether you want the current directory or the directory that the program image/executable resides. As it stands your question is a little ambiguous on this point.</strike></p>\n"
},
{
"answer_id": 143180,
"author": "Thorsten79",
"author_id": 19734,
"author_profile": "https://Stackoverflow.com/users/19734",
"pm_score": 5,
"selected": false,
"text": "<p>If you want a standard way without libraries: No. The whole concept of a directory is not included in the standard.</p>\n\n<p>If you agree that some (portable) dependency on a near-standard lib is okay: Use <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/reference.html\" rel=\"noreferrer\">Boost's filesystem library</a> and ask for the <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/filesystem/doc/reference.html#initial_path\" rel=\"noreferrer\">initial_path()</a>. </p>\n\n<p>IMHO that's as close as you can get, with good karma (Boost is a well-established high quality set of libraries)</p>\n"
},
{
"answer_id": 143187,
"author": "Fruny",
"author_id": 16815,
"author_profile": "https://Stackoverflow.com/users/16815",
"pm_score": 0,
"selected": false,
"text": "<p>On POSIX platforms, you can use <a href=\"http://www.opengroup.org/onlinepubs/009695399/functions/getcwd.html\" rel=\"nofollow noreferrer\">getcwd()</a>.</p>\n\n<p>On Windows, you may use <a href=\"http://msdn.microsoft.com/en-us/library/sf98bd4y(VS.80).aspx\" rel=\"nofollow noreferrer\">_getcwd()</a>, as use of <a href=\"http://msdn.microsoft.com/en-us/library/ms235450(VS.80).aspx\" rel=\"nofollow noreferrer\">getcwd()</a> has been deprecated.</p>\n\n<p>For standard libraries, if Boost were standard enough for you, I would have suggested Boost::filesystem, but they seem to have removed path normalization from the proposal. You may have to wait until <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n1975.html\" rel=\"nofollow noreferrer\">TR2 becomes readily available</a> for a fully standard solution.</p>\n"
},
{
"answer_id": 143188,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 3,
"selected": false,
"text": "<p>Maybe concatenate the current working directory with argv[0]? I'm not sure if that would work in Windows but it works in linux.</p>\n\n<p>For example:</p>\n\n<pre><code>#include <stdio.h>\n#include <unistd.h>\n#include <string.h>\n\nint main(int argc, char **argv) {\n char the_path[256];\n\n getcwd(the_path, 255);\n strcat(the_path, \"/\");\n strcat(the_path, argv[0]);\n\n printf(\"%s\\n\", the_path);\n\n return 0;\n}\n</code></pre>\n\n<p>When run, it outputs:</p>\n\n<blockquote>\n <p>jeremy@jeremy-desktop:~/Desktop$ ./test<br>\n /home/jeremy/Desktop/./test</p>\n</blockquote>\n"
},
{
"answer_id": 143219,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 3,
"selected": false,
"text": "<p>You can not use argv[0] for that purpose, usually it does contain full path to the executable, but not nessesarily - process could be created with arbitrary value in the field. </p>\n\n<p>Also mind you, the current directory and the directory with the executable are two different things, so getcwd() won't help you either.</p>\n\n<p>On Windows use GetModuleFileName(), on Linux read /dev/proc/<em>procID</em>/.. files.</p>\n"
},
{
"answer_id": 145216,
"author": "John Zwinck",
"author_id": 4323,
"author_profile": "https://Stackoverflow.com/users/4323",
"pm_score": 0,
"selected": false,
"text": "<p>Boost Filesystem's <code>initial_path()</code> behaves like POSIX's <code>getcwd()</code>, and neither does what you want by itself, but appending <code>argv[0]</code> to either of them should do it.</p>\n\n<p>You may note that the result is not always pretty--you may get things like <code>/foo/bar/../../baz/a.out</code> or <code>/foo/bar//baz/a.out</code>, but I believe that it always results in a valid path which names the executable (note that consecutive slashes in a path are collapsed to one).</p>\n\n<p>I previously wrote a solution using <code>envp</code> (the third argument to <code>main()</code> which worked on Linux but didn't seem workable on Windows, so I'm essentially recommending the same solution as someone else did previously, but with the additional explanation of why it is actually correct even if the results are not pretty.</p>\n"
},
{
"answer_id": 145309,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 7,
"selected": false,
"text": "<p>If you fetch the current directory when your program first starts, then you effectively have the directory your program was started from. Store the value in a variable and refer to it later in your program. This is distinct from <a href=\"https://stackoverflow.com/q/933850/33732\">the directory that holds the current executable program file</a>. It isn't necessarily the same directory; if someone runs the program from a command prompt, then the program is being <em>run from</em> the command prompt's current working directory even though the program file lives elsewhere.</p>\n\n<p>getcwd is a POSIX function and supported out of the box by all POSIX compliant platforms. You would not have to do anything special (apart from incliding the right headers unistd.h on Unix and direct.h on windows).</p>\n\n<p>Since you are creating a C program it will link with the default c run time library which is linked to by ALL processes in the system (specially crafted exceptions avoided) and it will include this function by default. The CRT is never considered an external library because that provides the basic standard compliant interface to the OS.</p>\n\n<p>On windows getcwd function has been deprecated in favour of _getcwd. I think you could use it in this fashion.</p>\n\n<pre><code>#include <stdio.h> /* defines FILENAME_MAX */\n#ifdef WINDOWS\n #include <direct.h>\n #define GetCurrentDir _getcwd\n#else\n #include <unistd.h>\n #define GetCurrentDir getcwd\n #endif\n\n char cCurrentPath[FILENAME_MAX];\n\n if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)))\n {\n return errno;\n }\n\ncCurrentPath[sizeof(cCurrentPath) - 1] = '\\0'; /* not really required */\n\nprintf (\"The current working directory is %s\", cCurrentPath);\n</code></pre>\n"
},
{
"answer_id": 198099,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p>Here's code to get the full path to the executing app:</p>\n<p>Variable declarations:</p>\n<pre><code>char pBuf[256];\nsize_t len = sizeof(pBuf); \n</code></pre>\n<p>Windows:</p>\n<pre><code>int bytes = GetModuleFileName(NULL, pBuf, len);\nreturn bytes ? bytes : -1;\n</code></pre>\n<p>Linux:</p>\n<pre><code>int bytes = MIN(readlink("/proc/self/exe", pBuf, len), len - 1);\nif(bytes >= 0)\n pBuf[bytes] = '\\0';\nreturn bytes;\n</code></pre>\n"
},
{
"answer_id": 2151270,
"author": "Minok",
"author_id": 144719,
"author_profile": "https://Stackoverflow.com/users/144719",
"pm_score": 2,
"selected": false,
"text": "<p>Just to belatedly pile on here,...</p>\n\n<p>there is no standard solution, because the languages are agnostic of underlying file systems, so as others have said, the concept of a directory based file system is outside the scope of the c / c++ languages.</p>\n\n<p>on top of that, you want not the current working directory, but the directory the program is running in, which must take into account how the program got to where it is - ie was it spawned as a new process via a fork, etc. To get the directory a program is running in, as the solutions have demonstrated, requires that you get that information from the process control structures of the operating system in question, which is the only authority on this question. Thus, by definition, its an OS specific solution.</p>\n"
},
{
"answer_id": 2151438,
"author": "mloskot",
"author_id": 151641,
"author_profile": "https://Stackoverflow.com/users/151641",
"pm_score": 0,
"selected": false,
"text": "<p>As <em>Minok</em> mentioned, there is no such functionality specified ini C standard or C++ standard. This is considered to be purely OS-specific feature and it is specified in POSIX standard, for example.</p>\n\n<p><em>Thorsten79</em> has given good suggestion, it is Boost.Filesystem library. However, it may be inconvenient in case you don't want to have any link-time dependencies in binary form for your program.</p>\n\n<p>A good alternative I would recommend is collection of 100% headers-only <a href=\"http://en.wikipedia.org/wiki/STLSoft_C%2B%2B_Libraries\" rel=\"nofollow noreferrer\">STLSoft C++ Libraries</a> <a href=\"http://en.wikipedia.org/wiki/Matthew_Wilson_%28author%29\" rel=\"nofollow noreferrer\">Matthew Wilson</a> (author of must-read books about C++). There is portable facade PlatformSTL gives access to system-specific API: WinSTL for Windows and UnixSTL on Unix, so it is portable solution. All the system-specific elements are specified with use of traits and policies, so it is extensible framework. There is filesystem library provided, of course.</p>\n"
},
{
"answer_id": 16887756,
"author": "Adam Yaxley",
"author_id": 693967,
"author_profile": "https://Stackoverflow.com/users/693967",
"pm_score": 3,
"selected": false,
"text": "<p>On Windows the simplest way is to use the <code>_get_pgmptr</code> function in <code>stdlib.h</code> to get a pointer to a string which represents the absolute path to the executable, including the executables name.</p>\n\n<pre><code>char* path;\n_get_pgmptr(&path);\nprintf(path); // Example output: C:/Projects/Hello/World.exe\n</code></pre>\n"
},
{
"answer_id": 17029008,
"author": "Alexey1993",
"author_id": 2471792,
"author_profile": "https://Stackoverflow.com/users/2471792",
"pm_score": 2,
"selected": false,
"text": "<p>For Windows system at console you can use system(<code>dir</code>) command. And console gives you information about directory and etc. Read about the <code>dir</code> command at <code>cmd</code>. But for Unix-like systems, I don't know... If this command is run, read bash command. <code>ls</code> does not display directory...</p>\n\n<p>Example:</p>\n\n<pre><code>int main()\n{\n system(\"dir\");\n system(\"pause\"); //this wait for Enter-key-press;\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 19535628,
"author": "Octopus",
"author_id": 1475548,
"author_profile": "https://Stackoverflow.com/users/1475548",
"pm_score": 6,
"selected": false,
"text": "<p>This is from the <a href=\"http://www.cplusplus.com/forum/general/11104/\">cplusplus forum</a></p>\n\n<p><strong>On windows:</strong></p>\n\n<pre><code>#include <string>\n#include <windows.h>\n\nstd::string getexepath()\n{\n char result[ MAX_PATH ];\n return std::string( result, GetModuleFileName( NULL, result, MAX_PATH ) );\n}\n</code></pre>\n\n<p><strong>On Linux:</strong></p>\n\n<pre><code>#include <string>\n#include <limits.h>\n#include <unistd.h>\n\nstd::string getexepath()\n{\n char result[ PATH_MAX ];\n ssize_t count = readlink( \"/proc/self/exe\", result, PATH_MAX );\n return std::string( result, (count > 0) ? count : 0 );\n}\n</code></pre>\n\n<p><strong>On HP-UX:</strong></p>\n\n<pre><code>#include <string>\n#include <limits.h>\n#define _PSTAT64\n#include <sys/pstat.h>\n#include <sys/types.h>\n#include <unistd.h>\n\nstd::string getexepath()\n{\n char result[ PATH_MAX ];\n struct pst_status ps;\n\n if (pstat_getproc( &ps, sizeof( ps ), 0, getpid() ) < 0)\n return std::string();\n\n if (pstat_getpathname( result, PATH_MAX, &ps.pst_fid_text ) < 0)\n return std::string();\n\n return std::string( result );\n}\n</code></pre>\n"
},
{
"answer_id": 21887613,
"author": "freezotic",
"author_id": 3329232,
"author_profile": "https://Stackoverflow.com/users/3329232",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#include <windows.h>\nusing namespace std;\n\n// The directory path returned by native GetCurrentDirectory() no end backslash\nstring getCurrentDirectoryOnWindows()\n{\n const unsigned long maxDir = 260;\n char currentDir[maxDir];\n GetCurrentDirectory(maxDir, currentDir);\n return string(currentDir);\n}\n</code></pre>\n"
},
{
"answer_id": 29763572,
"author": "FuzzyQuills",
"author_id": 4156345,
"author_profile": "https://Stackoverflow.com/users/4156345",
"pm_score": 1,
"selected": false,
"text": "<p>For relative paths, here's what I did. I am aware of the age of this question, I simply want to contribute a simpler answer that works in the majority of cases:</p>\n\n<p>Say you have a path like this:</p>\n\n<pre><code>\"path/to/file/folder\"\n</code></pre>\n\n<p>For some reason, Linux-built executables made in eclipse work fine with this. However, windows gets very confused if given a path like this to work with!</p>\n\n<p>As stated above there are several ways to get the current path to the executable, but the easiest way I find works a charm in the majority of cases is appending this to the FRONT of your path:</p>\n\n<pre><code>\"./path/to/file/folder\"\n</code></pre>\n\n<p>Just adding \"./\" should get you sorted! :) Then you can start loading from whatever directory you wish, so long as it is with the executable itself.</p>\n\n<p>EDIT: This won't work if you try to launch the executable from code::blocks if that's the development environment being used, as for some reason, code::blocks doesn't load stuff right... :D</p>\n\n<p>EDIT2: Some new things I have found is that if you specify a static path like this one in your code (Assuming Example.data is something you need to load):</p>\n\n<pre><code>\"resources/Example.data\"\n</code></pre>\n\n<p>If you then launch your app from the actual directory (or in Windows, you make a shortcut, and set the working dir to your app dir) then it will work like that.\nKeep this in mind when debugging issues related to missing resource/file paths. (Especially in IDEs that set the wrong working dir when launching a build exe from the IDE)</p>\n"
},
{
"answer_id": 32024051,
"author": "Sam Redway",
"author_id": 3940749,
"author_profile": "https://Stackoverflow.com/users/3940749",
"pm_score": 5,
"selected": false,
"text": "<p>I know it is very late at the day to throw an answer at this one but I found that none of the answers were as useful to me as my own solution. A very simple way to get the path from your CWD to your bin folder is like this:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n std::string argv_str(argv[0]);\n std::string base = argv_str.substr(0, argv_str.find_last_of(\"/\"));\n}\n</code></pre>\n\n<p>You can now just use this as a base for your relative path. So for example I have this directory structure:</p>\n\n<pre><code>main\n ----> test\n ----> src\n ----> bin\n</code></pre>\n\n<p>and I want to compile my source code to bin and write a log to test I can just add this line to my code.</p>\n\n<pre><code>std::string pathToWrite = base + \"/../test/test.log\";\n</code></pre>\n\n<p>I have tried this approach on Linux using full path, alias etc. and it works just fine.</p>\n\n<p>NOTE:</p>\n\n<p>If you are on windows you should use a '\\' as the file separator not '/'. You will have to escape this too for example:</p>\n\n<pre><code>std::string base = argv[0].substr(0, argv[0].find_last_of(\"\\\\\"));\n</code></pre>\n\n<p>I think this should work but haven't tested, so comment would be appreciated if it works or a fix if not. </p>\n"
},
{
"answer_id": 34832779,
"author": "Marqin",
"author_id": 898435,
"author_profile": "https://Stackoverflow.com/users/898435",
"pm_score": 5,
"selected": false,
"text": "<p>Filesystem TS <a href=\"http://www.iso.org/iso/catalogue_detail.htm?csnumber=63483\" rel=\"noreferrer\">is now a standard</a> ( and supported by gcc 5.3+ and clang 3.9+ ), so you can use <a href=\"http://en.cppreference.com/w/cpp/experimental/fs/current_path\" rel=\"noreferrer\"><code>current_path()</code></a> function from it:</p>\n\n<pre class=\"lang-c++ prettyprint-override\"><code>std::string path = std::experimental::filesystem::current_path();\n</code></pre>\n\n<p>In gcc (5.3+) to include Filesystem you need to use:</p>\n\n<pre><code>#include <experimental/filesystem>\n</code></pre>\n\n<p>and link your code with <code>-lstdc++fs</code> flag.</p>\n\n<p>If you want to use Filesystem with Microsoft Visual Studio, then <a href=\"https://msdn.microsoft.com/en-us/library/hh874694\" rel=\"noreferrer\">read this</a>.</p>\n"
},
{
"answer_id": 39083755,
"author": "Leslie Satenstein",
"author_id": 1445782,
"author_profile": "https://Stackoverflow.com/users/1445782",
"pm_score": 0,
"selected": false,
"text": "<p>The linux bash command \n<strong>which progname</strong> will report a path to program.</p>\n\n<p>Even if one could issue the which command from within your program and direct the output to a tmp file and the program\nsubsequently reads that tmp file, it will not tell you if that program is the one executing. It only tells you where a program having that name is located.</p>\n\n<p>What is required is to obtain your process id number, and to parse out the path to the name </p>\n\n<p>In my program I want to know if the program was\nexecuted from the user's bin directory or from another in the path\nor from /usr/bin. /usr/bin would contain the supported version.\nMy feeling is that in Linux there is the one solution that is portable.</p>\n"
},
{
"answer_id": 46561633,
"author": "Joachim",
"author_id": 1961484,
"author_profile": "https://Stackoverflow.com/users/1961484",
"pm_score": 1,
"selected": false,
"text": "<p>A library solution (although I know this was not asked for).\nIf you happen to use Qt:\n<code>QCoreApplication::applicationDirPath()</code></p>\n"
},
{
"answer_id": 56060288,
"author": "Manabu Nakazawa",
"author_id": 4366470,
"author_profile": "https://Stackoverflow.com/users/4366470",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>realpath()</code> in <code>stdlib.h</code> like this:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>char *working_dir_path = realpath(\".\", NULL);\n</code></pre>\n"
},
{
"answer_id": 56526330,
"author": "TarmoPikaro",
"author_id": 2338477,
"author_profile": "https://Stackoverflow.com/users/2338477",
"pm_score": 2,
"selected": false,
"text": "<p>Works with starting from C++11, using experimental filesystem, and C++14-C++17 as well using official filesystem.</p>\n\n<p>application.h:</p>\n\n<pre><code>#pragma once\n\n//\n// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros\n//\n#ifdef __cpp_lib_filesystem\n#include <filesystem>\n#else\n#include <experimental/filesystem>\n\nnamespace std {\n namespace filesystem = experimental::filesystem;\n}\n#endif\n\nstd::filesystem::path getexepath();\n</code></pre>\n\n<p>application.cpp:</p>\n\n<pre><code>#include \"application.h\"\n#ifdef _WIN32\n#include <windows.h> //GetModuleFileNameW\n#else\n#include <limits.h>\n#include <unistd.h> //readlink\n#endif\n\nstd::filesystem::path getexepath()\n{\n#ifdef _WIN32\n wchar_t path[MAX_PATH] = { 0 };\n GetModuleFileNameW(NULL, path, MAX_PATH);\n return path;\n#else\n char result[PATH_MAX];\n ssize_t count = readlink(\"/proc/self/exe\", result, PATH_MAX);\n return std::string(result, (count > 0) ? count : 0);\n#endif\n}\n</code></pre>\n"
},
{
"answer_id": 60804126,
"author": "nilo",
"author_id": 3246135,
"author_profile": "https://Stackoverflow.com/users/3246135",
"pm_score": 2,
"selected": false,
"text": "<p>Just my two cents, but doesn't the following code portably work in C++17?</p>\n\n<pre><code>#include <iostream>\n#include <filesystem>\nnamespace fs = std::filesystem;\n\nint main(int argc, char* argv[])\n{\n std::cout << \"Path is \" << fs::path(argv[0]).parent_path() << '\\n';\n}\n</code></pre>\n\n<p>Seems to work for me on Linux at least.</p>\n\n<p>Based on the previous idea, I now have:</p>\n\n<pre><code>std::filesystem::path prepend_exe_path(const std::string& filename, const std::string& exe_path = \"\");\n</code></pre>\n\n<p>With implementation:</p>\n\n<pre><code>fs::path prepend_exe_path(const std::string& filename, const std::string& exe_path)\n{\n static auto exe_parent_path = fs::path(exe_path).parent_path();\n return exe_parent_path / filename;\n}\n</code></pre>\n\n<p>And initialization trick in <code>main()</code>:</p>\n\n<pre><code>(void) prepend_exe_path(\"\", argv[0]);\n</code></pre>\n\n<p>Thanks @Sam Redway for the argv[0] idea. And of course, I understand that C++17 was not around for many years when the OP asked the question.</p>\n"
},
{
"answer_id": 65474320,
"author": "The Oathman",
"author_id": 10860215,
"author_profile": "https://Stackoverflow.com/users/10860215",
"pm_score": 1,
"selected": false,
"text": "<p>Path to the current .exe</p>\n<pre><code>\n#include <Windows.h>\n\nstd::wstring getexepathW()\n{\n wchar_t result[MAX_PATH];\n return std::wstring(result, GetModuleFileNameW(NULL, result, MAX_PATH));\n}\n\nstd::wcout << getexepathW() << std::endl;\n\n// -------- OR --------\n\nstd::string getexepathA()\n{\n char result[MAX_PATH];\n return std::string(result, GetModuleFileNameA(NULL, result, MAX_PATH));\n}\n\nstd::cout << getexepathA() << std::endl;\n\n</code></pre>\n"
},
{
"answer_id": 71281252,
"author": "Tareq Saif",
"author_id": 3981013,
"author_profile": "https://Stackoverflow.com/users/3981013",
"pm_score": 0,
"selected": false,
"text": "<p>The following worked well for me on macOS 10.15.7</p>\n<pre><code>brew install boost\n</code></pre>\n<p>main.cpp</p>\n<pre><code>#include <iostream>\n#include <boost/filesystem.hpp>\n\nint main(int argc, char* argv[]){\n boost::filesystem::path p{argv[0]};\n p = absolute(p).parent_path();\n std::cout << p << std::endl;\n return 0;\n}\n</code></pre>\n<p>Compiling</p>\n<pre><code>g++ -Wall -std=c++11 -l boost_filesystem main.cpp\n</code></pre>\n"
}
]
| 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 version of the library it was compiled against in the help section or a banner. </p>\n\n<p>That way you will be able to tell which functionality will the apps have and reduce potential confusion, especially given that somebody could compile a newer app version against an old library for any reason. Also, you decouple them and can add features on the library without depending on release of a new app version and so on. </p>\n\n<p>If you are sure you will always want all the apps and library to go in lockstep then you could use same numbers, but that's adding a constraint for not a strong reason.</p>\n"
},
{
"answer_id": 143186,
"author": "willem",
"author_id": 22702,
"author_profile": "https://Stackoverflow.com/users/22702",
"pm_score": 0,
"selected": false,
"text": "<p>We built an application that uses a framework. We keep separate version numbers for both.</p>\n\n<p>This works well, especially that now the framework and application have grown large enough to be developed by different teams.</p>\n\n<p>So my opinion... keep the version numbers separate.</p>\n"
},
{
"answer_id": 143452,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 2,
"selected": true,
"text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<pre><code>$ xsltproc --version\nUsing libxml 20628, libxslt 10120 and libexslt 813\nxsltproc was compiled against libxml 20628, libxslt 10120 and libexslt 813\nlibxslt 10120 was compiled against libxml 20628\nlibexslt 813 was compiled against libxml 20628\n</code></pre>\n"
}
]
| 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,
"author": "mattlant",
"author_id": 14642,
"author_profile": "https://Stackoverflow.com/users/14642",
"pm_score": 1,
"selected": true,
"text": "<p>You can setup your Gridview with no Datasource. Setup the gridview columns, and in codebehind bind that result to the grid view.</p>\n"
},
{
"answer_id": 143210,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>@leppie - There is no need to call a ToList() on the IQueryable when attaching it as a data source.</p>\n\n<p>Provided your DataContext has not been disposed of prior to the DataBind method being called ToList is a redundant call.</p>\n\n<p>By default a DataContext uses lazy-loading, so that the data is only fetched from the database when the IQueryable is Enumerated. ToList() performs an Enumeration and does the call, so does DataBind().</p>\n\n<p>So you can do something like this:</p>\n\n<pre><code>using(MyDataContext ctx = new MyDataContext(){\n this.MyGridView.DataSource = from something in ctx.Somethings where something.SomeProperty == someValue select something;\n this.MyGridView.DataBind();\n}\n</code></pre>\n\n<p>Depending on how your disposing your DataContext determins what to bind to a data source.</p>\n\n<p>You can then either use auto generated columns on the GridView, so that every property in your returned object is turned into a column, or you can write the columns with the designer and set up the binding rules there.</p>\n"
},
{
"answer_id": 2181604,
"author": "John",
"author_id": 259068,
"author_profile": "https://Stackoverflow.com/users/259068",
"pm_score": 0,
"selected": false,
"text": "<p>You can bind IQueryable<> type to GridView using LinqDataSource control. <a href=\"http://johnsobrepena.blogspot.com/2010/01/data-bind-coolgridview-to-iqueryable.html\" rel=\"nofollow noreferrer\">http://johnsobrepena.blogspot.com/2010/01/data-bind-coolgridview-to-iqueryable.html</a></p>\n"
}
]
| 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 something wrong :)</p>\n\n<p>Anyway, I bet there's no special C# way to do it, because it's very system-specific. You can use the same functions that you would use in a C++ application. Call the functions using P/Invoke. To learn how to write the imports, go to <a href=\"http://www.pinvoke.net\" rel=\"nofollow noreferrer\">pinvoke.net</a>.</p>\n\n<p>Edit: As I understand your question, I assume you already know how to do that in a Win32 application.</p>\n"
},
{
"answer_id": 143308,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 0,
"selected": false,
"text": "<p>The full quote OregonGhost refers to is</p>\n\n<blockquote>\n <p>If you have to ask, you're probably doing something wrong.</p>\n</blockquote>\n\n<p>It's from <a href=\"https://devblogs.microsoft.com/oldnewthing/20070718-00/?p=25963\" rel=\"nofollow noreferrer\">Why is the limit of window handles per process 10,000?</a> You should read this.</p>\n"
},
{
"answer_id": 534991,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 4,
"selected": false,
"text": "<p>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. </p>\n\n<p>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.</p>\n\n<p>As it happens, some users never want to close <em>any</em> 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.</p>\n\n<p>Why am I using controls, and not some other UI technology? Because they <em>work</em>. 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.</p>\n\n<p>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.\"</p>\n\n<p>At any rate, my solution to this is in two parts. </p>\n\n<p>First, a class that can tell you how many window handles your process is using:</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\n\nnamespace StreamWrite.Proceedings.Client\n{\n public class HWndCounter\n {\n [DllImport(\"kernel32.dll\")]\n private static extern IntPtr GetCurrentProcess();\n\n [DllImport(\"user32.dll\")]\n private static extern uint GetGuiResources(IntPtr hProcess, uint uiFlags);\n\n private enum ResourceType\n {\n Gdi = 0,\n User = 1\n }\n\n public static int GetWindowHandlesForCurrentProcess(IntPtr hWnd)\n {\n IntPtr processHandle = GetCurrentProcess();\n uint gdiObjects = GetGuiResources(processHandle, (uint)ResourceType.Gdi);\n uint userObjects = GetGuiResources(processHandle, (uint)ResourceType.User);\n\n return Convert.ToInt32(gdiObjects + userObjects);\n }\n }\n}\n</code></pre>\n\n<p>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 <a href=\"http://csharp-lru-cache.googlecode.com\" rel=\"noreferrer\">here</a> 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.</p>\n"
}
]
| 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[mainTextColor set];\ndrawTextLjust(@\"Sample Text\", 8, 50, 185, 18, 16);\n</code></pre>\n\n<p>And:</p>\n\n<pre><code>static void drawTextLjust(NSString* text, CGFloat y, CGFloat left, CGFloat right,\n int maxFontSize, int minFontSize) {\n CGPoint point = CGPointMake(left, y);\n UIFont *font = [UIFont systemFontOfSize:maxFontSize];\n [text drawAtPoint:point forWidth:right - left withFont:font\n minFontSize:minFontSize actualFontSize:NULL\n lineBreakMode:UILineBreakModeTailTruncation\n baselineAdjustment:UIBaselineAdjustmentAlignBaselines];\n}\n</code></pre>\n"
},
{
"answer_id": 3458620,
"author": "Ash",
"author_id": 414476,
"author_profile": "https://Stackoverflow.com/users/414476",
"pm_score": 3,
"selected": false,
"text": "<p>OK, I got it. First off, change your encoding mode to kCGEncodingMacRoman. Secondly, insert this line underneath it:</p>\n\n<pre><code>CGContextSetTextMatrix(canvas, CGAffineTransformMake(1, 0, 0, -1, 0, 0));\n</code></pre>\n\n<p>This sets the conversion matrix for text so that it is drawn correctly. If you don't put that line in, your text will be upside down and back to front. No idea why this wasn't the default. Finally, make sure you've set the right fill colour. It's an easy mistake to make if you forget to change from the backdrop colour to the text colour and end up with white-on-white text.</p>\n"
}
]
| 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 a <em>much</em> better way to solve this problem.</p>\n\n<p>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:</p>\n\n<pre><code>name | id | parent_id | upchain\nroot1 | 1 | NULL | 1:\nroot2 | 2 | NULL | 2:\nroot1sub1 | 3 | 1 | 1:3:\nroot1sub2 | 4 | 1 | 1:4:\nroot2sub1 | 5 | 2 | 2:5:\nroot2sub2 | 6 | 2 | 2:6:\nroot1sub1sub1 | 7 | 3 | 1:3:7:\n</code></pre>\n\n<p>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.</p>\n\n<p>What you're doing effectively is trading a bit of extra write activity for a <em>big</em> saving when you come to read the data.</p>\n\n<p>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:</p>\n\n<pre><code>SELECT *\nFROM table\nWHERE upchain LIKE '1:%'\n</code></pre>\n\n<p>This is <em>extremely</em> 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.</p>\n\n<p>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.)</p>\n\n<p>Notes (for anyone who's interested):</p>\n\n<ul>\n<li>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.</li>\n<li>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.</li>\n<li>This technique is also a good way to identify circular references which can otherwise be tricky to spot.</li>\n</ul>\n"
},
{
"answer_id": 143375,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 0,
"selected": false,
"text": "<p>This sounds like an exercise from \"SQL For Smarties\" by Joe Celko... </p>\n\n<p>I don't have my copy handy, but I think it's a book that'll help you quite a bit if this is the kind of problems you need to solve.</p>\n"
},
{
"answer_id": 143529,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 2,
"selected": false,
"text": "<p>The Joe Celko's method which is similar to the <a href=\"https://stackoverflow.com/questions/143226/cloning-hierarchical-data#143313\">njreed's answer</a> but is more generic can be found here:</p>\n\n<ul>\n<li><a href=\"http://www.dbmsmag.com/9603d06.html\" rel=\"nofollow noreferrer\">Nested-Set Model of Trees</a> (at the middle of the article)</li>\n<li><a href=\"http://www.dbmsmag.com/9604d06.html\" rel=\"nofollow noreferrer\">Nested-Set Model of Trees, part 2</a></li>\n<li><a href=\"http://www.dbmsmag.com/9605d06.html\" rel=\"nofollow noreferrer\">Trees in SQL -- Part III</a></li>\n</ul>\n"
},
{
"answer_id": 146569,
"author": "Panos",
"author_id": 8049,
"author_profile": "https://Stackoverflow.com/users/8049",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/143226/cloning-hierarchical-data#145298\">@Maximilian</a>: You are right, we forgot your actual requirement. How about a recursive stored procedure? I am not sure if this is possible in PostgreSQL, but here is a working SQL Server version:</p>\n\n<pre><code>CREATE PROCEDURE CloneNode\n @to_clone_id int, @parent_id int\nAS\n SET NOCOUNT ON\n DECLARE @new_node_id int, @child_id int\n\n INSERT INTO test (name, parent_id) \n SELECT name, @parent_id FROM test WHERE id = @to_clone_id\n SET @new_node_id = @@IDENTITY\n\n DECLARE @children_cursor CURSOR\n SET @children_cursor = CURSOR FOR \n SELECT id FROM test WHERE parent_id = @to_clone_id\n\n OPEN @children_cursor\n FETCH NEXT FROM @children_cursor INTO @child_id\n WHILE @@FETCH_STATUS = 0\n BEGIN\n EXECUTE CloneNode @child_id, @new_node_id\n FETCH NEXT FROM @children_cursor INTO @child_id\n END\n CLOSE @children_cursor\n DEALLOCATE @children_cursor\n</code></pre>\n\n<p>Your example is accomplished by <code>EXECUTE CloneNode 2, null</code> (the second parameter is the new parent node).</p>\n"
}
]
| 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 lua into.</p>\n"
},
{
"answer_id": 143257,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 1,
"selected": false,
"text": "<p>I wouldn't call it a feature - the interpreter just returns the result of the statement. It's his job, isn't it?</p>\n"
},
{
"answer_id": 143268,
"author": "Arle Nadja",
"author_id": 17774,
"author_profile": "https://Stackoverflow.com/users/17774",
"pm_score": 0,
"selected": false,
"text": "<p>Assignment isn't an expression that returns something in <code>Lua</code> like it is in <code>C</code>.</p>\n"
},
{
"answer_id": 143282,
"author": "Hugh Allen",
"author_id": 15069,
"author_profile": "https://Stackoverflow.com/users/15069",
"pm_score": 5,
"selected": true,
"text": "<p>Quoting the <a href=\"http://www.lua.org/manual/5.1/lua.html\" rel=\"noreferrer\">man page</a>:</p>\n\n<blockquote>\n <p>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.</p>\n</blockquote>\n"
}
]
| 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,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 7,
"selected": true,
"text": "<p>In Java, an <a href=\"http://download.oracle.com/javase/tutorial/java/javaOO/enum.html\" rel=\"noreferrer\"><code>enum</code> is a full-blown class</a>:</p>\n\n<blockquote>\n <p>Java programming language enum types\n are much more powerful than their\n counterparts in other languages. The\n enum declaration defines a class\n (called an enum type). The enum class\n body can include methods and other\n fields.</p>\n</blockquote>\n\n<p>In order to see the actual size of each <code>enum</code>, let's make an actual <code>enum</code> and examine the contents of the <code>class</code> file it creates.</p>\n\n<p>Let's say we have the following <code>Constants</code> enum class:</p>\n\n<pre><code>public enum Constants {\n ONE,\n TWO,\n THREE;\n}\n</code></pre>\n\n<p>Compiling the above <code>enum</code> and disassembling resulting <code>class</code> file with <code>javap</code> gives the following:</p>\n\n<pre><code>Compiled from \"Constants.java\"\npublic final class Constants extends java.lang.Enum{\n public static final Constants ONE;\n public static final Constants TWO;\n public static final Constants THREE;\n public static Constants[] values();\n public static Constants valueOf(java.lang.String);\n static {};\n}\n</code></pre>\n\n<p>The disassembly shows that that each field of an <code>enum</code> is an instance of the <code>Constants</code> <code>enum</code> class. (Further analysis with <code>javap</code> will reveal that each field is initialized by creating a new object by calling the <code>new Constants(String)</code> constructor in the static initialization block.)</p>\n\n<p>Therefore, we can tell that each <code>enum</code> field that we create will be at least as much as the overhead of creating an object in the JVM.</p>\n"
},
{
"answer_id": 143303,
"author": "Jeff Hubbard",
"author_id": 8844,
"author_profile": "https://Stackoverflow.com/users/8844",
"pm_score": 2,
"selected": false,
"text": "<p>In Java, it would take more memory. In C++, it would take no memory than required for a constant of the same type (it's evaluated at compile-time and has no residual significance at runtime). In C++, this means that the default type for an enum will occupy the same space as an int.</p>\n"
},
{
"answer_id": 143306,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 1,
"selected": false,
"text": "<pre><code>printf(\"%d\", sizeof(enum));\n</code></pre>\n"
},
{
"answer_id": 143312,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>If your enum will ever have only two cases, indeed using a boolean instead might be a better idea (memory size, performance, usage/logic), even more in Java.<br>\nIf you are wondering about memory cost, it might imply you plan to use lot of them. In Java you can use BitSet class, or on a smaller scale, in both languages you can manipulate bits with bitwise operations.</p>\n"
},
{
"answer_id": 143361,
"author": "Mike Dimmick",
"author_id": 6970,
"author_profile": "https://Stackoverflow.com/users/6970",
"pm_score": 3,
"selected": false,
"text": "<p><code>bool</code> might be implemented as a single byte, but typically in a structure it would be surrounded by other elements that have alignment requirements that would mean that the boolean would effectively be occupying at least as much space as an <code>int</code>.</p>\n\n<p>Modern processors load data from main memory as a whole cache line, 64 bytes. The difference between loading one byte from L1 cache and loading four bytes is negligible.</p>\n\n<p>If you're trying to optimise for cache lines in a very high-performance application, then you might worry about how big your enum is, but generally I'd say it's clearer to define an enum than to use a boolean.</p>\n"
},
{
"answer_id": 143366,
"author": "thenickdude",
"author_id": 14431,
"author_profile": "https://Stackoverflow.com/users/14431",
"pm_score": 4,
"selected": false,
"text": "<p>In Java, there should only be one instance of each of the values of your enum in memory. A reference to the enum then requires only the storage for that reference. Checking the value of an enum is as efficient as any other reference comparison.</p>\n"
},
{
"answer_id": 143408,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 3,
"selected": false,
"text": "<p>You would only worry about this when storing large quantities of enums. For Java, you may be able to use an EnumSet in some cases. It uses a bit vector internally which is very space efficient and fast.</p>\n\n<p><a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html\" rel=\"noreferrer\">http://java.sun.com/j2se/1.5.0/docs/api/java/util/EnumSet.html</a></p>\n"
},
{
"answer_id": 144179,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 0,
"selected": false,
"text": "<p>sizeof(enum) depends upon what you have in the enum. I was recently trying to find the size of an ArrayList() with default constructor params and no objects stored inside (which means the capacity to store is 10). It turned out that ArrayList is not too big < 100 bytes.</p>\n\n<p>So, sizeof(enum) for a very simple enum should be less than 10 bytes. you can write a small program, give it a certain amount of memory and then try allocating enums. you should be able to figure it out(that's how i found out the memory of ArrayList)</p>\n\n<p>BR,<BR>\n~A</p>\n"
},
{
"answer_id": 144732,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 1,
"selected": false,
"text": "<p>In C++ an enum is typically the same size as an <code>int</code>. That said it is not uncommon for compilers to provide a command line switch to allow the size of the enum to be set to the smallest size that fits the range of values defined.</p>\n"
},
{
"answer_id": 145114,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 0,
"selected": false,
"text": "<p>In C/C++ an enum will be the same size as an int.</p>\n\n<p>With gcc you can add <strong>attribute</strong>((packed)) to the enum definition to make it take the minimum footprint. If the largest value in the enum is < 256 this will be one byte, two bytes if the largest value is < 65536, etc.</p>\n\n<pre><code>typedef enum {\n MY_ENUM0,\n MY_ENUM1,\n MY_ENUM2,\n MY_ENUM3,\n MY_ENUM4,\n MY_ENUM5\n} __attribute__((packed)) myEnum_e;\n</code></pre>\n"
},
{
"answer_id": 148531,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>In ISO C++ there is no obligation for an enum to be larger than its largest enumerator requires. In particular, enum {TRUE, FALSE} may have sizeof(1) even when sizeof(bool)==sizeof(int). There is simply no requirement. Some compilers make the enums the same size as an int. That is a compiler feature, which is allowed because the standard only imposes a minimum. Other compilers use extensions to control the size of an enum.</p>\n"
}
]
| 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 * {\n color: #fff;\n }\n .wrapper {\n\n }\n\n .trigger {\n background: #223;\n }\n\n .appear {\n background: #334;\n display: none;\n }\n\n .trigger:hover .appear {\n display: block;\n }\n </style>\n</head>\n\n<body>\n\n <div class=\"wrapper\">\n <div class=\"trigger\">\n <p>This is the trigger for the hover element.</p>\n <div class=\"appear\">\n <p>I'm <strong>alive!</strong></p>\n </div>\n </div>\n </div>\n\n</body>\n</code></pre>\n\n<p><a href=\"http://paste2.org/p/79237\" rel=\"nofollow noreferrer\">pastebin</a>.</p>\n"
},
{
"answer_id": 144625,
"author": "Justin Poliey",
"author_id": 6967,
"author_profile": "https://Stackoverflow.com/users/6967",
"pm_score": 6,
"selected": true,
"text": "<p>IE7 won't allow you to apply <code>:hover</code> 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.</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n</code></pre>\n\n<p>More on IE7/quirks mode can be found on <a href=\"http://www.bernzilla.com/item.php?id=762\" rel=\"noreferrer\">this blog post</a>.</p>\n"
},
{
"answer_id": 4152844,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Could it be the double margin problem?\nI did an display: inline-block when it happened for a li\n<a href=\"http://www.positioniseverything.net/explorer/doubled-margin.html\" rel=\"nofollow\">http://www.positioniseverything.net/explorer/doubled-margin.html</a></p>\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, then you can catch them like any other key event:</p>\n\n<pre><code>var myListener = new Object();\nmyListener.onKeyDown = function() {\n var code = Key.getCode();\n if (code==ExtendedKey.SOFT1) {\n trace(\"I got a soft key event\");\n }\n}\nKey.addListener(myListener);\n</code></pre>\n\n<p>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.</p>\n\n<p>Note that you can check at runtime whether or not softkeys are available:</p>\n\n<pre><code>trace(System.capabilities.hasMappableSoftKeys);\ntrace(System.capabilities.softKeyCount); \n</code></pre>\n"
},
{
"answer_id": 457172,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you use a switch statement, you can have more than one keycode associated with an action, you make a desktop version for testing too. I have done it myself.</p>\n"
}
]
| 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\" rel=\"noreferrer\">http://www.skepticfiles.org/cowtext/apple/memorytx.htm</a></p>\n\n<p><strong>Update:</strong></p>\n\n<p>That link appears to be dead, here's a Wayback Machine alternative:</p>\n\n<blockquote>\n <p><a href=\"http://web.archive.org/web/20090315100335/http://www.skepticfiles.org/cowtext/apple/memorytx.htm\" rel=\"noreferrer\">http://web.archive.org/web/20090315100335/http://www.skepticfiles.org/cowtext/apple/memorytx.htm</a></p>\n</blockquote>\n\n<p>Here's the full article just in case Wayback goes away:</p>\n\n<pre>\nAPPLE CALL, PEEK, POKE LIST CALL 144 SCAN THE INPUT BUFFER CALL 151 ENTER THE MONITOR NORM\n\n APPLE CALL, PEEK, POKE LIST\n\n------------------------------------------------------------------------------\nCALL -144 SCAN THE INPUT BUFFER\nCALL -151 ENTER THE MONITOR NORMALLY\nCALL -155 ENTER THE MONITOR & SOUND BELL\nCALL -167 ENTER MONITOR AND RESET\nCALL -198 RING BELL (SIMULATE CONTROL G)\nCALL -211 PRINT \"ERR\" AND RING BELL\nCALL -259 READ FROM TAPE\nCALL -310 WRITE TO TAPE\nCALL -321 DISPLAYS A, S, Y, P, & S REGISTERS\nCALL -380 SET NORMAL VIDEO MODE\nCALL -384 SET INVERSE VIDEO MODE\nCALL -415 DISASSEMBLE 20 INSTRUCTIONS\nCALL -458 VERIFY (COMPARE & LIST DIFFERENCES)\n\nCALL -468 MEMORY MOVE AFTER POKING 60,61 OLD START - 62,63 OLD END\n 64,65 NEW END - 66,67 NEW STAR\n\nCALL -484 MOVE\nCALL -517 DISPLAY CHARACTER & UPDATE SCREEN LOCATION\nCALL -531 DISPLAY CHARACTER, MASK CONTROL CHAR., & SAVE 7 REG. & ACCU\nCALL -550 DISPLAY HEX VALUE OF A-REGISTER (ACCUMULATOR)\nCALL -656 RING BELL AND WAIT FOR A CARRIAGE RETURN\n\nCALL -657 GET LINE OF INPUT, NO PROMPT, NO L/F, & WAIT(COMMA,COLON OK\nCALL -662 GET LINE OF INPUT, WITH PROMPT, NO L/F, & WAIT\nCALL -665 GET LINE OF INPUT, WITH PROMPT, LINE FEED, & WAIT\nTHE ABOVE 3 CALLS (-657, -662, -665) REFER TO THE INPUT BUFFER FROM 512-767\n\nCALL -715 GET CHARACTER\nCALL -756 WAIT FOR KEY PRESS\nCALL -856 TIME DELAY (POKE 69,XX TO SET TIME OF DELAY)\nCALL -868 CLEARS CURSOR LINE FROM CURSOR TO END OF LINE\nCALL -912 SCROLLS TEXT UP 1 LINE\nCALL -922 LINE FEED\nCALL -936 CLEAR SCREEN (HOME)\nCALL -958 CLEAR SCREEN FROM CURSOR TO BOTTOM OF SCREEN\nCALL -998 MOVES CURSOR UP 1 LINE\nCALL -1008 MOVES CURSOR BACKWARD 1 SPACE\nCALL -1024 DISPLAY CHARACTER ONLY\nCALL -1036 MOVES CURSOR FORWARD 1 SPACE\nCALL -1063 SEND BELL TO CURRENT OUTPUT DEVICE\nCALL -1216 TEXT & GRAPHICS MODE\nCALL -1233 MOVE CURSOR TO BOTTOM OF SCREEN\nCALL -1321 CONTROL E\nCALL -1717 MOVES CURSOR DOWN 5 LINES\nCALL -1840 DISASSEMBLE 1 INSTRUCTION\nCALL -1953 CHANGE COLOR BY +3\nCALL -1994 CLEAR LO-RES SCREEN (TOP 40 LINES)\nCALL -1998 CLEAR GRAPHIC SCREEN (LO-RES)\nCALL -2007 VERTICAL LINE\nCALL -2023 HORIZONTAL LINE\nCALL -2458 ENTER MINI ASSEMBLER\nCALL -3100 TURNS ON HIRES PAGE 1, WITHOUT CLEARING IT\nCALL -3776 SAVE INTEGER\nCALL -3973 LOAD INTEGER\nCALL -6090 RUN INTEGER\nCALL -8117 LIST INTEGER\nCALL -8189 ENTER BASIC & CONTINUE\nCALL -8192 ENTER BASIC AND RESET (INTEGER BASIC KILL)\nCALL -16303 TEXT MODE\nCALL -16304 GRAPHICS MODE\nCALL -16336 TOGGLE SPEAKER\nCALL 42350 CATALOGS DISK\nCALL 54915 CLEANS STACK, CLEARS THE \"OUT OF MEMORY\" ERROR\nCALL 64166 INITIATES A COLD START (BOOT OF THE DISK)\nCALL 64246 BRAND NEW-YOU FIGURE IT OUT\n\nCALL 64367 SCANS MEMORY LOC 1010 & 1011 & POKES VALUE INTO LOCATIONS\n 1012 THAT IS EQUAL TO (PEEK(1011)-165)\n\n------------------------------------------------------------------------------\nPEEK 33 WIDTH OF TEXT WINDOW (1-40)\nPEEK 34 TOP EDGE OF TEXT WINDOW (0-22)\nPEEK 35 BOTTOM OF TEXT WINDOW (1-24)\nPEEK 36 HORIZONTAL CURSOR POSITION (0-39)\nPEEK 37 VERTICAL CURSOR POSITION (0-23)\nPEEK 43 BOOT SLOT X 16 (AFTER BOOT)\nPEEK 44 END POINT OF LAST HLIN, VLIN, OR PLOT\nPEEK 48 LO-RES COLOR VALUE X 17\n\nPEEK 50 TEXT OUTPUT FORMAT: 63=INVERSE 255=NORMAL\n 127=FLASH ( WITH PEEK 243 SET TO 64)\n\nPEEK 51 PROMPT CHARACTER\nPEEK 74,75 LOMEM ADDRESS (INT)\nPEEK 76,77 HIMEM ADDRESS (INT)\nPEEK 103,104 FP PROGRAM STARTING ADDRESS\nPEEK 104 IF 8 IS RETURNED, THEN FP IS IN ROM\nPEEK 105,106 FP VARIABLE SPACE STARTING ADDRESS\nPEEK 107,108 FP ARRAY STARTING ADDRESS\nPEEK 109,110 FP END OF NUMERIC STORAGE ADDRESS\nPEEK 111,112 FP STRING STORAGE STARTING ADDRESS\nPEEK 115,116 FP HIMEM ADDRESS\nPEEK 117,118 FP LINE NUMBER BEING EXECUTED\nPEEK 119,120 FP LINE WHERE PROGRAM STOPPED\nPEEK 121,122 FP LINE BEING EXECUTED ADDRESS\nPEEK 123,124 LINE WHERE DATA BEING READ\nPEEK 125,126 DATA LOCATION ADDRESS\nPEEK 127,128 INPUT OR DATA ADDRESS\nPEEK 129,130 FP LAST USED VARIABLE NAME\nPEEK 131,132 FP LAST USED VARIABLE ADDRESS\nPEEK 175,176 FP END OF PROGRAM ADDRESS\nPEEK 202,203 INT PROGRAM STARTING ADDRESS\nPEEK 204,205 INT END OF VARIABLE STORAGE\nPEEK 214 FP RUN FLAG (AUTO-RUN IF >127)\nPEEK 216 ONERR FLAG (>127 IF ONERR IS ACTIVE)\nPEEK 218,219 LINE WHERE ONERR OCCURED\nPEEK 222 ONERR ERROR CODE\nPEEK 224,225 X-COORDINATE OF LAST HPLOT\nPEEK 226 Y-COORDINATE OF LAST HPLOT\nPEEK 228 HCOLOR VALUE 0=0 85=2 128=4 213=6\n 42=1 127=3 170=5 255=7\nPEEK 230 HI-RES PLOTING PAGE (32=PAGE 1 64=PAGE 2 96=PAGE 3)\nPEEK 231 SCALE VALUE\nPEEK 232,233 SHAPE TABLE STARTING ADDRESS\nPEEK 234 HI-RES COLLISION COUNTER\nPEEK 241 256 MINUS SPEED VALUE\nPEEK 243 FLASH MASK (64=FLASH WHEN PEEK 50 SET TO 127)\nPEEK 249 ROT VLAUE\nPEEK 976-978 DOS RE-ENTRY VECTOR\nPEEK 1010-1012 RESET VECTOR\nPEEK 1013-1015 AMPERSAND (&) VECTOR\nPEEK 1016-1018 CONTROL-Y VECTOR\nPEEK 43140-43271 DOS COMMAND TABLE\nPEEK 43378-43582 DOS ERROR MESSAGE TABLE\nPEEK 43607 MAXFILES VALUE\nPEEK 43616,46617 LENGTH OF LAST BLOAD\nPEEK 43624 DRIVE NUMBER\nPEEK 43626 SLOT NUMBER\nPEEK 43634,43635 STARTING ADDRESS OF LAST BLOAD\nPEEK 43697 MAXFILES DEFAULT VALUE\nPEEK 43698 DOS COMMAND CHARACTER\nPEEK 43702 BASIC FLAG (0=INT 64=FP ROM 128=FP RAM)\nPEEK 44033 CATALOG TRACK NUMBER (17 IS STANDARD)\nPEEK 44567 NUMBER OF CHARACTERS MINUS 1 IN CATALOG FILE NAMES\nPEEK 44611 NUMBER OF DIGITS MINUS 1 IN SECTOR AND VOLUME NUMBERS\nPEEK 45991-45998 FILE-TYPE CODE TABLE\nPEEK 45999-46010 DISK VOLUME HEADING\nPEEK 46017 DISK VOLUME NUMBER\nPEEK 46064 NUMBER OF SECTORS (13=DOS 3.2 16=DOS 3.3)\nPEEK 49152 READ KEYBOARD (IF >127 THEN KEY HAS BEEN PRESSED\nPEEK 49200 TOGGLE SPEAKER (CLICK)\nPEEK 49248 CASSETTE INPUT (>127=BINARY 1, 127 IF BUTTON PRESSED)\nPEEK 49250 PADDLE 1 BUTTON (>127 IF BUTTON PRESSGD)\nPEEK 49251 PADDLE 2 BUTTON (>127 IF BUTTON PRESSED)\nPEEK 49252 READ GAME PADDLE 0 (0-255)\nPEEK 49253 READ GAME PADDLE 1 (0-255)\nPEEK 49254 READ GAME PADDLE 2 (0-255)\nPEEK 49255 READ GAME PADDLE 3 (0-255)\nPEEK 49408 READ SLOT 1\nPEEK 49664 READ SLOT 2\nPEEK 49920 READ SLOT 3\nPEEK 50176 READ SLOT 4\nPEEK 50432 READ SLOT 5\nPEEK 50688 READ SLOT 6 (162=DISK CONROLLOR CARD)\nPEEK 50944 READ SLOT 7\n\nPEEK 64899 INDICATES WHICH COMPUTER YOU'RE USING\n 223=APPLE II OR II+, 234=FRANKLIN ACE OR ?, 255=APPLE IIE\n\nPOKE 33,33 SCRUNCH LISTING AND REMOVE SPACES IN QUOTE STATEMENTS\nPOKE 36,X USE AS PRINTER TAB (X=TAB - 1)\nPOKE 50,128 MAKES ALL OUTPUT TO THE SCREEN INVISIBLE\nPOKE 50,RANDOM SCRAMBLES OUTPUT TO SCREEN\nPOKE 51,0 DEFEATS \"NOT DIRECT COMMAND\", SOMETIMES DOESN'T WORK\nPOKE 82,128 MAKE CASETTE PROGRAM AUTO-RUN WHEN LOADED\nPOKE 214,255 SETS RUN FLAG IN FP & ANY KEY STROKES WILL RUN DISK PROGRA\nPOKE 216,0 CANCEL ONERR FLAG\n\nPOKE 1010,3 SETS THE RESET VECTOR TO INITIATE\nPOKE 1011,150 A COLD START (BOOT)\n\nPOKE 1010,102 MAKE\nPOKE 1011,213 RESET\nPOKE 1012,112 RUN\n\nPOKE 1014,165 SETS THE AMPERSAND (&) VECTOR\nPOKE 1015,214 TO LIST YOUR PROGRAM\n\nPOKE 1014,110 SETS THE AMPERSAND (&) VECTOR\nPOKE 1015,165 TO CATALOG A DISK\n\nPOKE 1912+SLOT,1 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'S\nPOKE 1912+SLOT,0 ON APPLE PARALLEL CARD (WITH P1-02 PROM) WILL ENABLE L/F'S\n\nPOKE 2049,1 THIS WILL CAUSE THE FIRST LINE OF PROGRAM TO LIST REPEATEDLY\nPOKE 40514,20 ALLOWS TEXT FILE GREETING PROGRAM\nPOKE 40514,52 ALLOWS BINARY FILE GREETING PROGRAM\n\nPOKE 40993,24 THIS ALLOWS\nPOKE 40994,234 DISK COMMANDS IN\nPOKE 40995,234 THE DIRECT MODE\n\nPOKE 42319,96 DISABLES THE INIT COMMAND\n\nPOKE 42768,234 CANCEL ALL\nPOKE 42769,234 DOS ERROR\nPOKE 42770,234 MESSAGES\nPOKE 43624,X SELECTS DISK DRIVE WITHOUT EXECUTING A COMMAND (48K SYSTEM)\n\nPOKE 43699,0 TURNS AN EXEC FILE OFF BUT LEAVES IT OPEN UNTIL A FP, CLOSE\nPOKE 43699,1 TURNS AN EXEC FILE BACK ON. INIT, OR MAXFILES IS ISSUE\n\nPOKE 44452,24 ALLOWS 20 FILE NAMES (2 EXTRA)\nPOKE 44605,23 BEFORE CATALOG PAUSE\n\nPOKE 44505,234 REVEALS DELETED FILE\nPOKE 44506,234 NAMES IN CATALG\n\nPOKE 44513,67 CATALOG WILL RETURN ONLY LOCKED FILES\nPOKE 44513,2 RETURN CATALOG TO NORMAL\nPOKE 44578,234 CANCEL CARRIAGE\nPOKE 44579,234 RETURNS AFTER CATALOG\nPOKE 44580,234 FILE NAMES\n\nPOKE 44596,234 CANCEL\nPOKE 44597,234 CATALOG-STOP\nPOKE 44598,234 WHEN SCREEN IS FULL\n\nPOKE 44599,234 STOP CATALOG AT EACH FILE\nPOKE 44600,234 NAME AND WAIT FOR A KEYPRESS\n\nPOKE 46922,96 THIS ALLOWS DISK\nPOKE 46923,234 INITIALATION\nPOKE 46924,234 WITHOUT PUTTING\nPOKE 44723,4 DOS ON THE DISK\n\nPOKE 49107,234 PREVENT LANGUAGE\nPOKE 49108,234 CARD FROM LOADING\nPOKE 49109,234 DURING RE-BOOT\n\nPOKE 49168,0 CLEAR KEYBOARD\nPOKE 49232,0 DISPLAY GRAPHICS\nPOKE 49233,0 DISPLAY TEXT\nPOKE 49234,0 DISPLAY FULL GRAPHICS\nPOKE 49235,0 DISPLAY TEXT/GRAPHICS\nPOKE 49236,0 DISPLAY GRAPHICS PAGE 1\nPOKE 49237,0 DISPLAY GRAPHICS PAGE 2\nPOKE 49238,0 DISPLAY LORES\nPOKE 49239,0 DISPLAY HIRES\n------------------------------------------------------------------------------\n\n 48K MEMORY MAP\n\n DECIMAL HEX USAGE\n------------------------------------------------------------------------------\n 0-255 $0-$FF ZERO-PAGE SYSTEM STORAGE\n 256-511 $100-$1FF SYSTEM STACK\n 512-767 $200-$2FF KEYBOARD CHARACTER BUFFER\n 768-975 $300-$3CF OFTEN AVAILABLE AS FREE SPACE FOR USER PROGRAMS\n 976-1023 $3D0-3FF SYSTEM VECTORS\n 1024-2047 $400-$7FF TEXT AND LO-RES GRAPHICS PAGE 1\n 2048-LOMEM $800-LOMEM PROGRAM STORAGE\n 2048-3071 $800-$BFF TEXT AND LO-RES GRAPHICS PAGE 2 OR FREE SPACE\n 3072-8191 $C00-$1FFF FREE SPACE UNLESS RAM APPLESOFT IS IN USE\n 8192-16383 $2000-$3FFF HI-RES PAGE 1 OR FREE SPACE\n16384-24575 $4000-$5FFF HI-RES PAGE 2 OR FREE SPACE\n24576-38999 $6000-$95FF FREE SPACE AND STRING STORAGE\n38400-49151 $9600-$BFFF DOS\n49152-53247 $C000-$CFFF I/O HARDWARE (RESERVED)\n53248-57343 $D000-$DFFF APPLESOFT IN LANGUAGE CARD OR ROM\n57344-63487 $E000-$F7FF APPLESOFT OR INTEGER BASIC IN LANGUAGE CARD OR ROM\n63488-65535 $F800-$FFFF SYSTEM MONITOR\n\n\nPEEK: TO EXAMINE ANY MEMORY LOCATION L, PRINT PEEK (L), WHERE L IS A DECIMAL\nNUMBER 0-65535. TO PEEK AT A TWO-BYTE NUMBER AT CONSEQUTIVE LOCATIONS L AND\nL+1, PRINT PEEK (L) + PEEK (L+1) * 256\n\nPOKE: TO ASSIGN A VALUE X (0-255) TO LOCATION L; POKE L,X. TO POKE A TWO-BYT\nNUMBER (NECESSARY IF X>255), POKE L,X-INT(X/256)*256, AND POKE L+1,INT(X/256).\n\nCALL: TO EXECUTE A MACHINE LANGUAGE SUB ROUTINE AT LOCATION L, CALL L.\n\n\nJUST FOR FUN TRY THIS: POKE 33,90. THEN TRY LISTING YOUR PROGRAM. OR TRY:\n0,99 OR POKE 50,250 OR POKE 50,127. USE RESET TO RETURN TO NORMAL.\n\nFOR TRUE RANDOM NUMBER GENERATION TRY THIS:X= RND(PEEK(78)+PEEK(79)*256)\n\nTO LOCATE THE STARTING ADDRESS OF THE LAST BLOADED FILE USE: PEEK(-21902)+PEEK\n(-21901)*256 (RESULT IS IN HEX)\n\nTO DETERMINE THE LENGTH OF THE LAST BLOADED FILE USE: PEEK(-21920)+PEEK(-21919\n*256 (RESULT IS IN HEX)\n\nTO DETERMINE THE LINE NUMBER THAT CAUSED AN ERROR TO OCCUR, SET X TO: PEEK(218\n+PEEK(219)*256\n\n------------------------------------------------------------------------------\n\nE-Mail Fredric L. Rice / The Skeptic Tank\n\n</pre>\n"
},
{
"answer_id": 143385,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 1,
"selected": false,
"text": "<p>Crikey, that's a blast from the past. I think it entered the monitor ROM (I was torn between this and Integer BASIC but I'm pretty certain it was the monitor).</p>\n\n<p>You could download an Apple II emulator and find out.</p>\n"
},
{
"answer_id": 2535404,
"author": "Mike Lowery",
"author_id": 298511,
"author_profile": "https://Stackoverflow.com/users/298511",
"pm_score": 4,
"selected": false,
"text": "<p>Call -151 enters the monitor, 3D0G brings you back to BASIC, and typing a slot # in the monitor followed by Ctrl-P will boot that device. Amazing what one remembers after 20 years!</p>\n"
},
{
"answer_id": 33522668,
"author": "JavaMan",
"author_id": 237575,
"author_profile": "https://Stackoverflow.com/users/237575",
"pm_score": 2,
"selected": false,
"text": "<p>May I also add that -151 is apple ]['s way of expressing hex number which should mean $FF69 (hex syntax used in Apple II i.e. 0xFF68). \nThe CALL is an Apple Basic command that invokes an assembly subroutine given by the argument (-151 here). IIRC, this command can accept an address as negative decimal value for addresses between $8000-$FFFF using 2's complement interpretation.</p>\n\n<p>For those who are interested in history, here is the Apple ]['s monitor rom listing (in 6502 assembly) and address $FF69 is having the label MONZ which is the start of the command prompt that process machine code processing commands from user. One that uses a '*' as the prompt. A very primitive command prompt.</p>\n\n<p><a href=\"http://www.easy68k.com/paulrsm/6502/MON.TXT\" rel=\"nofollow\">Apple II System Monitor</a></p>\n"
},
{
"answer_id": 62615874,
"author": "Dale Mahalko",
"author_id": 2996876,
"author_profile": "https://Stackoverflow.com/users/2996876",
"pm_score": 1,
"selected": false,
"text": "<p>As a side note, the reason why this is a negative number and not the proper <strong>CALL 65385</strong> is because the very first form of BASIC for the Apple II was known as Integer BASIC. It only understood signed 16-bit Integer values from -32768 to 32767, and so it is impossible to directly address memory beyond 32767 in the normal positive value manner.</p>\n<p>If you tried actually typing POKE 49200,0 or CALL 65385 in Integer BASIC you will get a message like ">32767 ERR"</p>\n<p>When the replacement Microsoft Applesoft BASIC (yes, from them) with floating point numbers was introduced, they included support for the negative POKE values for some degree of backwards compatibility for the older Integer BASIC programs. Though this compatibility is limited, as Applesoft lacks other programming features of Integer like the MOD division remainder.</p>\n<p>Due to the strong influence of early Integer BASIC programming methods, there are many PEEK POKE and CALL commands that are generally only known by their hexadecimal and negative decimal values, but not by their positive decimal values.</p>\n"
}
]
| 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 when you define methods within your class on the interface. I know that sounds confusing but here is what I mean: <code>IList.CopyTo</code> would be implicitly implemented as:</p>\n\n<pre><code>public void CopyTo(Array array, int index)\n{\n throw new NotImplementedException();\n}\n</code></pre>\n\n<p>and explicitly as:</p>\n\n<pre><code>void ICollection.CopyTo(Array array, int index)\n{\n throw new NotImplementedException();\n}\n</code></pre>\n\n<p>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.</p>\n\n<pre><code>MyClass myClass = new MyClass(); // Declared as concrete class\nmyclass.CopyTo //invalid with explicit\n((IList)myClass).CopyTo //valid with explicit.\n</code></pre>\n\n<p>I use explicit primarily to keep the implementation clean, or when I need two implementations. Regardless, I rarely use it.</p>\n\n<p>I am sure there are more reasons to use/not use explicit that others will post.</p>\n\n<p>See the <a href=\"https://stackoverflow.com/questions/143405/c-interfaces-implicit-and-explicit-implementation#143425\"><strong>next post</strong></a> in this thread for excellent reasoning behind each. </p>\n"
},
{
"answer_id": 143425,
"author": "Phil Bennett",
"author_id": 2995,
"author_profile": "https://Stackoverflow.com/users/2995",
"pm_score": 8,
"selected": false,
"text": "<p>Implicit definition would be to just add the methods / properties, etc. demanded by the interface directly to the class as public methods.</p>\n\n<p>Explicit definition forces the members to be exposed only when you are working with the interface directly, and not the underlying implementation. This is preferred in most cases.</p>\n\n<ol>\n<li>By working directly with the interface, you are not acknowledging,\nand coupling your code to the underlying implementation.</li>\n<li>In the event that you already have, say, a public property Name in\nyour code and you want to implement an interface that also has a\nName property, doing it explicitly will keep the two separate. Even\nif they were doing the same thing I'd still delegate the explicit\ncall to the Name property. You never know, you may want to change\nhow Name works for the normal class and how Name, the interface\nproperty works later on.</li>\n<li>If you implement an interface implicitly then your class now exposes\nnew behaviours that might only be relevant to a client of the\ninterface and it means you aren't keeping your classes succinct\nenough (my opinion).</li>\n</ol>\n"
},
{
"answer_id": 143433,
"author": "Bill",
"author_id": 17595,
"author_profile": "https://Stackoverflow.com/users/17595",
"pm_score": 3,
"selected": false,
"text": "<p>If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.</p>\n\n<p>If your implementing class is not public, except for the method used to create the class (which could be a factory or <a href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"noreferrer\">IoC</a> container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.</p>\n\n<p>Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. \"Makes sure\", I suppose, is the \"advantage\". A well-factored implementation can accomplish this without explicit implementation.</p>\n\n<p>The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.</p>\n\n<p>Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed. </p>\n"
},
{
"answer_id": 143483,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 6,
"selected": false,
"text": "<p>In addition to excellent answers already provided, there are some cases where explicit implementation is REQUIRED for the compiler to be able to figure out what is required. Take a look at <code>IEnumerable<T></code> as a prime example that will likely come up fairly often.</p>\n\n<p>Here's an example:</p>\n\n<pre><code>public abstract class StringList : IEnumerable<string>\n{\n private string[] _list = new string[] {\"foo\", \"bar\", \"baz\"};\n\n // ...\n\n #region IEnumerable<string> Members\n public IEnumerator<string> GetEnumerator()\n {\n foreach (string s in _list)\n { yield return s; }\n }\n #endregion\n\n #region IEnumerable Members\n IEnumerator IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n #endregion\n}\n</code></pre>\n\n<p>Here, <code>IEnumerable<string></code> implements <code>IEnumerable</code>, hence we need to too. But hang on, both the generic and the normal version <strong>both implement functions with the same method signature</strong> (C# ignores return type for this). This is completely legal and fine. How does the compiler resolve which to use? It forces you to only have, at most, one implicit definition, then it can resolve whatever it needs to.</p>\n\n<p>ie.</p>\n\n<pre><code>StringList sl = new StringList();\n\n// uses the implicit definition.\nIEnumerator<string> enumerableString = sl.GetEnumerator();\n// same as above, only a little more explicit.\nIEnumerator<string> enumerableString2 = ((IEnumerable<string>)sl).GetEnumerator();\n// returns the same as above, but via the explicit definition\nIEnumerator enumerableStuff = ((IEnumerable)sl).GetEnumerator();\n</code></pre>\n\n<p>PS: The little piece of indirection in the explicit definition for IEnumerable works because inside the function the compiler knows that the actual type of the variable is a StringList, and that's how it resolves the function call. Nifty little fact for implementing some of the layers of abstraction some of the .NET core interfaces seem to have accumulated.</p>\n"
},
{
"answer_id": 157490,
"author": "Lee Oades",
"author_id": 20508,
"author_profile": "https://Stackoverflow.com/users/20508",
"pm_score": 4,
"selected": false,
"text": "<p>In addition to the other reasons already stated, this is the situation in which a class is implementing two different interfaces that have a property/method with the same name and signature.</p>\n\n<pre><code>/// <summary>\n/// This is a Book\n/// </summary>\ninterface IBook\n{\n string Title { get; }\n string ISBN { get; }\n}\n\n/// <summary>\n/// This is a Person\n/// </summary>\ninterface IPerson\n{\n string Title { get; }\n string Forename { get; }\n string Surname { get; }\n}\n\n/// <summary>\n/// This is some freaky book-person.\n/// </summary>\nclass Class1 : IBook, IPerson\n{\n /// <summary>\n /// This method is shared by both Book and Person\n /// </summary>\n public string Title\n {\n get\n {\n string personTitle = \"Mr\";\n string bookTitle = \"The Hitchhikers Guide to the Galaxy\";\n\n // What do we do here?\n return null;\n }\n }\n\n #region IPerson Members\n\n public string Forename\n {\n get { return \"Lee\"; }\n }\n\n public string Surname\n {\n get { return \"Oades\"; }\n }\n\n #endregion\n\n #region IBook Members\n\n public string ISBN\n {\n get { return \"1-904048-46-3\"; }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>This code compiles and runs OK, but the Title property is shared.</p>\n\n<p>Clearly, we'd want the value of Title returned to depend on whether we were treating Class1 as a Book or a Person. This is when we can use the explicit interface.</p>\n\n<pre><code>string IBook.Title\n{\n get\n {\n return \"The Hitchhikers Guide to the Galaxy\";\n }\n}\n\nstring IPerson.Title\n{\n get\n {\n return \"Mr\";\n }\n}\n\npublic string Title\n{\n get { return \"Still shared\"; }\n}\n</code></pre>\n\n<p>Notice that the explicit interface definitions are inferred to be Public - and hence you can't declare them to be public (or otherwise) explicitly.</p>\n\n<p>Note also that you can still have a \"shared\" version (as shown above), but whilst this is possible, the existence of such a property is questionable. Perhaps it could be used as a default implementation of Title - so that existing code would not have to be modified to cast Class1 to IBook or IPerson.</p>\n\n<p>If you do not define the \"shared\" (implicit) Title, consumers of Class1 <strong>must</strong> explicitly cast instances of Class1 to IBook or IPerson first - otherwise the code will not compile.</p>\n"
},
{
"answer_id": 3034603,
"author": "Jon Nadal",
"author_id": 319002,
"author_profile": "https://Stackoverflow.com/users/319002",
"pm_score": 5,
"selected": false,
"text": "<h2>Reason #1</h2>\n<p>I tend to use explicit interface implementation when I want to discourage "programming to an implementation" (<em><a href=\"http://www.artima.com/lejava/articles/designprinciples.html\" rel=\"noreferrer\">Design Principles from Design Patterns</a></em>).</p>\n<p>For example, in an <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter\" rel=\"noreferrer\">MVP</a>-based web application:</p>\n<pre><code>public interface INavigator {\n void Redirect(string url);\n}\n\npublic sealed class StandardNavigator : INavigator {\n void INavigator.Redirect(string url) {\n Response.Redirect(url);\n }\n}\n</code></pre>\n<p>Now another class (such as a <a href=\"https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93presenter#Pattern_description\" rel=\"noreferrer\">presenter</a>) is less likely to depend on the StandardNavigator implementation and more likely to depend on the INavigator interface (since the implementation would need to be cast to an interface to make use of the Redirect method).</p>\n<h2>Reason #2</h2>\n<p>Another reason I might go with an explicit interface implementation would be to keep a class's "default" interface cleaner. For example, if I were developing an <a href=\"http://en.wikipedia.org/wiki/ASP.NET\" rel=\"noreferrer\">ASP.NET</a> server control, I might want two interfaces:</p>\n<ol>\n<li>The class's primary interface, which is used by web page developers; and</li>\n<li>A "hidden" interface used by the presenter that I develop to handle the control's logic</li>\n</ol>\n<p>A simple example follows. It's a combo box control that lists customers. In this example, the web page developer isn't interested in populating the list; instead, they just want to be able to select a customer by GUID or to obtain the selected customer's GUID. A presenter would populate the box on the first page load, and this presenter is encapsulated by the control.</p>\n<pre><code>public sealed class CustomerComboBox : ComboBox, ICustomerComboBox {\n private readonly CustomerComboBoxPresenter presenter;\n\n public CustomerComboBox() {\n presenter = new CustomerComboBoxPresenter(this);\n }\n\n protected override void OnLoad() {\n if (!Page.IsPostBack) presenter.HandleFirstLoad();\n }\n\n // Primary interface used by web page developers\n public Guid ClientId {\n get { return new Guid(SelectedItem.Value); }\n set { SelectedItem.Value = value.ToString(); }\n }\n\n // "Hidden" interface used by presenter\n IEnumerable<CustomerDto> ICustomerComboBox.DataSource { set; }\n}\n</code></pre>\n<p>The presenter populates the data source, and the web page developer never needs to be aware of its existence.</p>\n<h3>But's It's Not a Silver Cannonball</h3>\n<p>I wouldn't recommend always employing explicit interface implementations. Those are just two examples where they might be helpful.</p>\n"
},
{
"answer_id": 4949060,
"author": "Valentin Kuzub",
"author_id": 514382,
"author_profile": "https://Stackoverflow.com/users/514382",
"pm_score": 5,
"selected": false,
"text": "<p>To quote Jeffrey Richter from CLR via C#\n<br>(<strong>EIMI</strong> means <strong>E</strong>xplicit <strong>I</strong>nterface <strong>M</strong>ethod <strong>I</strong>mplementation)</p>\n\n<blockquote>\n <p>It is critically important for you to\n understand some ramifications that\n exist when using EIMIs. And because of\n these ramifications, you should try to\n avoid EIMIs as much as possible.\n Fortunately, generic interfaces help\n you avoid EIMIs quite a bit. But there\n may still be times when you will need\n to use them (such as implementing two\n interface methods with the same name\n and signature). Here are the big\n problems with EIMIs:</p>\n \n <ul>\n <li>There is no documentation explaining how a type specifically\n implements an EIMI method, and there\n is no Microsoft Visual Studio\n <a href=\"https://en.wikipedia.org/wiki/Intelli-sense\" rel=\"noreferrer\">IntelliSense</a> support.</li>\n <li>Value type instances are boxed when cast to an interface.</li>\n <li>An EIMI cannot be called by a derived type.</li>\n </ul>\n</blockquote>\n\n<p>If you use an interface reference ANY virtual chain can be explicitly replaced with EIMI on any derived class and when an object of such type is cast to the interface, your virtual chain is ignored and the explicit implementation is called. That's anything but polymorphism.</p>\n\n<p>EIMIs can also be used to hide non-strongly typed interface members from basic Framework Interfaces' implementations such as IEnumerable<T> so your class doesn't expose a non strongly typed method directly, but is syntactical correct.</p>\n"
},
{
"answer_id": 6140004,
"author": "Yochai Timmer",
"author_id": 536086,
"author_profile": "https://Stackoverflow.com/users/536086",
"pm_score": 3,
"selected": false,
"text": "<p>An implicit interface implementation is where you have a method with the same signature of the interface.</p>\n\n<p>An explicit interface implementation is where you explicitly declare which interface the method belongs to.</p>\n\n<pre><code>interface I1\n{\n void implicitExample();\n}\n\ninterface I2\n{\n void explicitExample();\n}\n\n\nclass C : I1, I2\n{\n void implicitExample()\n {\n Console.WriteLine(\"I1.implicitExample()\");\n }\n\n\n void I2.explicitExample()\n {\n Console.WriteLine(\"I2.explicitExample()\");\n }\n}\n</code></pre>\n\n<p>MSDN: <a href=\"http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx\" rel=\"noreferrer\"><strong>implicit and explicit interface implementations</strong></a></p>\n"
},
{
"answer_id": 13214331,
"author": "nrodic",
"author_id": 551322,
"author_profile": "https://Stackoverflow.com/users/551322",
"pm_score": 2,
"selected": false,
"text": "<p>One important use of explicit interface implementation is when in need to implement interfaces with <strong>mixed visibility</strong>.</p>\n\n<p>The problem and solution are well explained in the article <em><a href=\"http://www.csharp411.com/c-internal-interface/\" rel=\"nofollow\">C# Internal Interface</a></em>.</p>\n\n<p>For example, if you want to protect leakage of objects between application layers, this technique allows you to specify different visibility of members that could cause the leakage.</p>\n"
},
{
"answer_id": 23615330,
"author": "supercat",
"author_id": 363751,
"author_profile": "https://Stackoverflow.com/users/363751",
"pm_score": 3,
"selected": false,
"text": "<p>Every class member that implements an interface exports a declaration which is semantically similar to the way VB.NET interface declarations are written, e.g.</p>\n\n<pre><code>Public Overridable Function Foo() As Integer Implements IFoo.Foo\n</code></pre>\n\n<p>Although the name of the class member will often match that of the interface member, and the class member will often be public, neither of those things is required. One may also declare:</p>\n\n<pre><code>Protected Overridable Function IFoo_Foo() As Integer Implements IFoo.Foo\n</code></pre>\n\n<p>In which case the class and its derivatives would be allowed to access a class member using the name <code>IFoo_Foo</code>, but the outside world would only be able to access that particular member by casting to <code>IFoo</code>. Such an approach is often good in cases where an interface method will have <em>specified</em> behavior on all implementations, but <em>useful</em> behavior on only some [e.g. the specified behavior for a read-only collection's <code>IList<T>.Add</code> method is to throw <code>NotSupportedException</code>]. Unfortunately, the only proper way to implement the interface in C# is:</p>\n\n<pre><code>int IFoo.Foo() { return IFoo_Foo(); }\nprotected virtual int IFoo_Foo() { ... real code goes here ... }\n</code></pre>\n\n<p>Not as nice.</p>\n"
},
{
"answer_id": 25323397,
"author": "scobi",
"author_id": 14582,
"author_profile": "https://Stackoverflow.com/users/14582",
"pm_score": 4,
"selected": false,
"text": "<p>I use explicit interface implementation most of the time. Here are the main reasons.</p>\n\n<p><strong>Refactoring is safer</strong></p>\n\n<p>When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.</p>\n\n<p>Two common cases come to mind:</p>\n\n<ul>\n<li><p><em>Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one</em>. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to \"see\" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).</p></li>\n<li><p><em>Removing a function from an interface</em>. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.</p></li>\n</ul>\n\n<p>It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.</p>\n\n<p>Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.</p>\n\n<p><strong>It's self-documenting</strong></p>\n\n<p>If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying \"implementation of ITask\". Of course, that only works if the group header isn't offscreen..</p>\n\n<p>Whereas: 'bool ITask.Execute()' is clear and unambiguous.</p>\n\n<p><strong>Clear separation of interface implementation</strong></p>\n\n<p>I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.</p>\n\n<p>As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into \"code contract\" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).</p>\n\n<p>(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)</p>\n\n<p>Related: <a href=\"https://stackoverflow.com/a/3034603/14582\">Reason 2 above by Jon</a>.</p>\n\n<p><strong>And so on</strong></p>\n\n<p>Plus the advantages already mentioned in other answers here:</p>\n\n<ul>\n<li>When required, as per <a href=\"https://stackoverflow.com/a/157490/14582\">disambiguation</a> or needing an <a href=\"http://www.csharp411.com/c-internal-interface/\" rel=\"noreferrer\">internal interface</a></li>\n<li>Discourages \"programming to an implementation\" (<a href=\"https://stackoverflow.com/a/3034603/14582\">Reason 1 by Jon</a>)</li>\n</ul>\n\n<h2>Problems</h2>\n\n<p>It's not all fun and happiness. There are some cases where I stick with implicits:</p>\n\n<ul>\n<li>Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.</li>\n<li>Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).</li>\n</ul>\n\n<p>Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:</p>\n\n<ol>\n<li>Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.</li>\n<li>(My preferred method) Add a <code>public IMyInterface I { get { return this; } }</code> (which should get inlined) and call <code>foo.I.InterfaceMethod()</code>. If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).</li>\n</ol>\n"
},
{
"answer_id": 58412221,
"author": "Marc Sigrist",
"author_id": 270212,
"author_profile": "https://Stackoverflow.com/users/270212",
"pm_score": 2,
"selected": false,
"text": "<p>The previous answers explain why implementing an interface explicitly in C# may be <em>preferrable</em> (for mostly formal reasons). However, there is one situation where explicit implementation is <em>mandatory</em>: In order to avoid leaking the encapsulation when the interface is non-<code>public</code>, but the implementing class is <code>public</code>.</p>\n\n<pre><code>// Given:\ninternal interface I { void M(); }\n\n// Then explicit implementation correctly observes encapsulation of I:\n// Both ((I)CExplicit).M and CExplicit.M are accessible only internally.\npublic class CExplicit: I { void I.M() { } }\n\n// However, implicit implementation breaks encapsulation of I, because\n// ((I)CImplicit).M is only accessible internally, while CImplicit.M is accessible publicly.\npublic class CImplicit: I { public void M() { } }\n</code></pre>\n\n<p>The above leakage is unavoidable because, according to the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/interfaces#interface-members\" rel=\"nofollow noreferrer\">C# specification</a>, \"All interface members implicitly have public access.\" As a consequence, implicit implementations must also give <code>public</code> access, even if the interface itself is e.g. <code>internal</code>.</p>\n\n<p>Implicit interface implementation in C# is a great convenience. In practice, many programmers use it <em>all the time/everywhere</em> without further consideration. This leads to messy type surfaces at best and leaked encapsulation at worst. Other languages, such as F#, <a href=\"https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/interfaces#implementing-interfaces-by-using-class-types\" rel=\"nofollow noreferrer\">don't even allow it</a>.</p>\n"
},
{
"answer_id": 72986342,
"author": "marsze",
"author_id": 2060966,
"author_profile": "https://Stackoverflow.com/users/2060966",
"pm_score": 0,
"selected": false,
"text": "<p>I've found myself using <strong>explicit</strong> implementations more often recently, for the following <strong>practical</strong> reasons:</p>\n<ul>\n<li><p>Always using explicit from the starts prevents having any naming collisions, in which explicit implementation would be required anyways</p>\n</li>\n<li><p>Consumers are "forced" to use the interface (which they should/must do anyways when you're using DI)</p>\n</li>\n<li><p>No "zombie" members in the implementations - removing any member from the interface declaration will result in compiler errors if not removed from the implementation too</p>\n</li>\n<li><p>Default values for optional parameters, as well constraints on generic arguments are automatically adopted - no need to write them twice and keep them in sync</p>\n</li>\n</ul>\n"
}
]
| 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 add 1 to i!\n\nif ($i==$j) { // I made sure to use == rather than = here to avoid a bug\n</code></pre>\n\n<p>That sort of thing.</p>\n"
},
{
"answer_id": 143445,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 6,
"selected": false,
"text": "<p>I've found myself writing this little gem before:</p>\n\n<pre><code>//@TODO: Rewrite this, it sucks. Seriously.\n</code></pre>\n\n<p>Usually it's a good sign that I've reached the end of my coding session for the night.</p>\n"
},
{
"answer_id": 143453,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 5,
"selected": false,
"text": "<p>I once worked on a project with a strange C compiler. It gave an error on a valid piece of code unless a comment was inserted between two statements. So I changed the comment to:</p>\n\n<pre><code>// Do not remove this comment else compilation will fail.\n</code></pre>\n\n<p>And it worked great.</p>\n"
},
{
"answer_id": 143464,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 5,
"selected": false,
"text": "<p>Every comment that just repeats what the code says is useless. Comments should not tell me what the code does. If I don't know the programming language well enough, to understand what's going on by just reading the code, I should not be reading that code at all. Comments like</p>\n\n<pre><code>// Increase i by one\ni++;\n</code></pre>\n\n<p>are completely useless. I see that i is increased by one, that is what the code says, I don't need a comment for that! Comments should be used to explain <strong>why</strong> something is done (in case it is far from being obvious) or <strong>why</strong> something is done that way and not any other way (so I can understand certain design decisions another programmer made that are by far not obvious at once). Further comments are useful to explain tricky code, where it is absolutely not possible to determine what's going on by having a quick look at the code (e.g. there are tricky algorithms to count the number of bits set in a number; if you don't know what this code does, you have no chance of guessing what goes on there).</p>\n"
},
{
"answer_id": 143466,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 4,
"selected": false,
"text": "<pre><code>// Don't know why we have to do this\n</code></pre>\n"
},
{
"answer_id": 143479,
"author": "MidnightGun",
"author_id": 13220,
"author_profile": "https://Stackoverflow.com/users/13220",
"pm_score": -1,
"selected": false,
"text": "<p>I thought this was about the worst comment on a SO post, and was disappointed to find otherwise.</p>\n"
},
{
"answer_id": 143481,
"author": "Quentin",
"author_id": 19068,
"author_profile": "https://Stackoverflow.com/users/19068",
"pm_score": 2,
"selected": false,
"text": "<p>Not quite a comment, but from the JavaDoc that described the API of a system I once had to work with.</p>\n\n<pre>\n<strong>setAttribute(attributeName, attributeValue)</strong>\n<em>Sets an attribute</em>\n</pre>\n\n<p>Nowhere was it documented what an attribute was (they were not HTML/XML/etc attributes), what attributes existed or what values they could have.</p>\n"
},
{
"answer_id": 143489,
"author": "Gautam Jain",
"author_id": 15065,
"author_profile": "https://Stackoverflow.com/users/15065",
"pm_score": -1,
"selected": false,
"text": "<p>Commented code is the least useful comment :)</p>\n"
},
{
"answer_id": 143516,
"author": "BlackWasp",
"author_id": 21862,
"author_profile": "https://Stackoverflow.com/users/21862",
"pm_score": 1,
"selected": false,
"text": "<p>I have removed the name to avoid embarassment but this is a comment found in some production code. Unfortunately, as this was ASP code, referring to a VB6 module, and the customer was quite inquisitive, it was she who pointed out the comment to me whilst I was on-site during a consultancy visit. Luckily she had a sense of humour about it.</p>\n\n<blockquote>\n <p>'I don't know how the help this @\"%& works. It is a load of &£$! created by that\n contractor ---------.<br/>\n I will just leave it in place and hope nobody ever needs it changing.</p>\n</blockquote>\n\n<p>Unfortunately for me the code did need changing about a year later, at which point we found we had no source code and had to junk it and rewrite for free.</p>\n"
},
{
"answer_id": 143556,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 5,
"selected": false,
"text": "<pre><code>Thread.Sleep(1000); // this will fix .NET's crappy threading implementation\n</code></pre>\n"
},
{
"answer_id": 143590,
"author": "Axeman",
"author_id": 22108,
"author_profile": "https://Stackoverflow.com/users/22108",
"pm_score": 3,
"selected": false,
"text": "<p>In a huge VB5 application </p>\n\n<pre><code>dim J\nJ = 0 'magic\nJ = J 'more magic\nfor J=1 to 100\n...do stuff...\n</code></pre>\n\n<p>The reference is obviously <a href=\"http://catb.org/esr/jargon/html/magic-story.html\" rel=\"nofollow noreferrer\">THIS</a> ... and yes, the application without those two lines fails at runtime with an unknown error code. We still don't know why. </p>\n"
},
{
"answer_id": 143600,
"author": "Diomidis Spinellis",
"author_id": 20520,
"author_profile": "https://Stackoverflow.com/users/20520",
"pm_score": 6,
"selected": false,
"text": "<p>Unfilled javadoc boilerplate comments are particularly useless. They consume a lot of screen real estate without contributing anything useful. And the worst part is that where one such comment appears, hundreds of others are surely lurking behind.</p>\n\n<pre><code>/**\n * Method declaration\n *\n *\n * @param table\n * @param row\n *\n * @throws SQLException\n */\nvoid addTransactionDelete(Table table, Object row[]) throws SQLException {\n</code></pre>\n"
},
{
"answer_id": 143607,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>Just the typical Comp Sci 101 type comments:</p>\n</blockquote>\n\n<p>I have threatened my students with random acts of extreme violence if they ever did this in assignments. And they <em>still</em> did. The sense in proper indentation, however, seemed to be totally lost to them. Goes to show why Python would be the ideal language for beginners, I guess.</p>\n"
},
{
"answer_id": 143640,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 4,
"selected": false,
"text": "<p>Default comments inserted by IDEs.</p>\n\n<p>The last project I worked on which used WebSphere Application Developer had plenty of maintenance developers and contractors who didn't seem to be bothered by the hundreds, if not thousands of Java classes which contained the likes of this:</p>\n\n<pre><code>/**\n * @author SomeUserWhoShouldKnowBetter\n *\n * To change this generated comment edit the template variable \"typecomment\":\n * Window>Preferences>Java>Templates.\n * To enable and disable the creation of type comments go to\n * Window>Preferences>Java>Code Generation.\n */\n</code></pre>\n\n<p>There was always that split-second between thinking you'd actually found a well-commented source file and realising that, yup, it's another default comment, which forced you to use <code>SWEAR_WORD_OF_CHOICE</code>.</p>\n"
},
{
"answer_id": 143663,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 2,
"selected": false,
"text": "<p>Comments generated by an auto-javadoc tool (e.g. <a href=\"http://jautodoc.sourceforge.net/\" rel=\"nofollow noreferrer\">JAutoDoc</a>). I had a team member submit a large amount of code that was commented like:</p>\n\n<pre><code>/**\n * Gets the something\n *\n * @param num The num\n * @param offset The offset\n */\npublic void getSomething(int num, bool offset)\n</code></pre>\n\n<p>Maybe it's helpful as a starting point, but by definition if the program is parsing the variable and method names to make its comments it can't be doing much useful.</p>\n"
},
{
"answer_id": 144249,
"author": "SecretDeveloper",
"author_id": 2720,
"author_profile": "https://Stackoverflow.com/users/2720",
"pm_score": 3,
"selected": false,
"text": "<p>100k LOC application that was ported from vb6 to vb.net. It looks as though a previous developer had put a comment header on one method and then copied and pasted the exact comment onto every method he wrote from then on. Hundreds of methods and each one incorrectly commented...</p>\n\n<p>When i first saw it i laughed... 6 months later the joke is wearing thin.</p>\n"
},
{
"answer_id": 144269,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": 5,
"selected": false,
"text": "<p>GhostDoc comes up with some pretty interesting ones on its own.</p>\n\n<pre><code>/// <summary>\n/// Toes the foo.\n/// </summary>\n/// <returns></returns>\npublic Foo ToFoo()\n</code></pre>\n"
},
{
"answer_id": 144289,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>My favorite all-time comment. </p>\n\n<pre><code>/* our second do loop */\ndo {\n</code></pre>\n\n<p>Whoever wrote it - you know who you are.</p>\n"
},
{
"answer_id": 144371,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/* FIXME: documentation for the bellow functionality - and why are we doing it this way */\n</code></pre>\n\n<p>It was a huge statistical program for an accounting application. We had never figured out why she had done it that - wrong - way. But we had to rewrite it, and paid penalty for the customer. </p>\n"
},
{
"answer_id": 144725,
"author": "Andrew Edgecombe",
"author_id": 11694,
"author_profile": "https://Stackoverflow.com/users/11694",
"pm_score": 4,
"selected": false,
"text": "<p>Came across a file once. Thousands of lines of code, most of it quite horrendous. Badly named variables, tricky conditionals on loops and one comment buried in the middle of the file.</p>\n\n<pre><code>\n /* Hmmm. A bit tricky. */\n</code></pre>\n"
},
{
"answer_id": 144729,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 2,
"selected": false,
"text": "<p>Whenever I teach OOP in C++ or Java, I typically get the following:</p>\n\n<pre><code>// My class!\nClass myclass \n{\n //Default constructor\n public myClass()\n {\n ...\n }\n}\n</code></pre>\n\n<p>My policy is to announce to students that they would lose points for both insufficient and superfluous documentation</p>\n"
},
{
"answer_id": 144742,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 2,
"selected": false,
"text": "<p>My research deals with API usability and I've encountered a lot of comments which are bad simply because they are misleading, misplaced, incorrect, or incomplete.</p>\n\n<p>For example, in Java Messaging Service (JMS or within J2EE), the QueueReceiver.receive class contains the following gem:\n\"This call blocks until a message arrives, the timeout expires, or this message consumer is closed. A timeout of zero never expires and the call blocks indefinitely.\"</p>\n\n<p>Sounds great? right? </p>\n\n<p>Problem is, as my lab studies show, that users believe that comments cover everything. Faced with a situation where messages are not received, they refuse to look elsewhere for the explanation. </p>\n\n<p>In this case, when you create a QueueConnection from the QueueConnectionFactory, it tells you that the messages would not be delivered until start is called. But that does not appear in the receive method.</p>\n\n<p>I believe that if that line wasn't there, more people would have searched for it elsewhere.</p>\n\n<p>By the way, my study deals with JavaDoc usability in general, and in whether people actually find the important directives in JavaDocs. If anybody wants to take a look, a related is <a href=\"http://www.cs.cmu.edu/~udekel/papers/udekel_pushing_unpublished.pdf\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 144779,
"author": "David M. Karr",
"author_id": 10508,
"author_profile": "https://Stackoverflow.com/users/10508",
"pm_score": 5,
"selected": false,
"text": "<p>I don't believe it. I came into this question after it had 22 answers, and no one pointed out the least possibly useful type of comment:</p>\n\n<p>comments that are wrong.</p>\n\n<p>It's bad enough that people write superfluous comments that get in the way of understanding code, but when someone writes a detailed comment explaining how something works, and it's either wrong in the first place, or wrong after the code was changed without changing the comment (much more likely scenario), that is definitely the worst kind of comment.</p>\n"
},
{
"answer_id": 145458,
"author": "Firas Assaad",
"author_id": 23153,
"author_profile": "https://Stackoverflow.com/users/23153",
"pm_score": 2,
"selected": false,
"text": "<p>I have a lot of these:</p>\n\n<pre><code># For each pose in the document\ndoc.elements.each('//pose') do |pose| ...\n\n# For each sprite in sprites\[email protected] do |sprite| ...\n\n# For each X in Y\nfor X in Y do ...\n</code></pre>\n\n<p>I'm trying to cut back on that, though. :(</p>\n"
},
{
"answer_id": 145482,
"author": "Tom De Leu",
"author_id": 22263,
"author_profile": "https://Stackoverflow.com/users/22263",
"pm_score": 3,
"selected": false,
"text": "<p>The worst comment is one that gives a wrong explanation of what the code does.\nThat is worse than no comment at all.</p>\n\n<p>I've seen this kind of thing in code with way too many comments (that shouldn't be there because the code is clear enough on its own), and it happens mostly when the code is updated (refactored, modified, etc.) but the comments aren't updated along with it.</p>\n\n<p>A good rule of thumb is: only write comments to explain <strong>why</strong> code is doing something, not <strong>what</strong> it does.</p>\n"
},
{
"answer_id": 148615,
"author": "user23405",
"author_id": 23405,
"author_profile": "https://Stackoverflow.com/users/23405",
"pm_score": 1,
"selected": false,
"text": "<p>I would have to say that the least useful type of commenting I have encountered is second-language commenting.</p>\n\n<p>I would rather see the comments written clearly in someone's native language than scrawled in a very poor approximation of English. At least then a native speaker of that language could translate it. ESL comments are often unreadable to everyone on the planet except the person who wrote them, and sometimes not even by them.</p>\n"
},
{
"answer_id": 148622,
"author": "Decio Lira",
"author_id": 12423,
"author_profile": "https://Stackoverflow.com/users/12423",
"pm_score": 6,
"selected": false,
"text": "<pre><code>// remember to comment code\n</code></pre>\n\n<p>wtf? :D</p>\n"
},
{
"answer_id": 168803,
"author": "Justin",
"author_id": 401774,
"author_profile": "https://Stackoverflow.com/users/401774",
"pm_score": 5,
"selected": false,
"text": "<pre><code>// secret sauce\n</code></pre>\n"
},
{
"answer_id": 168840,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": false,
"text": "<p>Taken from one of my <a href=\"http://geekswithblogs.net/sdorman/archive/2007/09/28/Priceless.aspx\" rel=\"nofollow noreferrer\">blog posts</a>:</p>\n\n<blockquote>\n <p>In the process of cleaning up some of the source code for one of the projects I manage, I came across the following comments: </p>\n</blockquote>\n\n<pre><code>/*\n MAB 08-05-2004: Who wrote this routine? When did they do it? Who should \n I call if I have questions about it? It's worth it to have a good header\n here. It should helps to set context, it should identify the author \n (hero or culprit!), including contact information, so that anyone who has\n questions can call or email. It's useful to have the date noted, and a \n brief statement of intention. On the other hand, this isn't meant to be \n busy work; it's meant to make maintenance easier--so don't go overboard.\n\n One other good reason to put your name on it: take credit! This is your\n craft\n*/\n</code></pre>\n\n<p>and then a little further down:</p>\n\n<pre><code>#include \"xxxMsg.h\" // xxx messages\n/*\n MAB 08-05-2004: With respect to the comment above, I gathered that\n from the filename. I think I need either more or less here. For one\n thing, xxxMsg.h is automatically generated from the .mc file. That might\n be interesting information. Another thing is that xxxMsg.h should NOT be\n added to source control, because it's auto-generated. Alternatively, \n don't bother with a comment at all.\n*/\n</code></pre>\n\n<p>and then yet again:</p>\n\n<pre><code>/*\n MAB 08-05-2004: Defining a keyword?? This seems problemmatic [sic],\n in principle if not in practice. Is this a common idiom? \n*/\n</code></pre>\n"
},
{
"answer_id": 168873,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 4,
"selected": false,
"text": "<p>a very large database engine project in C many many years ago - thousands of lines of code with short and misspelled variable names, and no comments... until way deep in nested if-conditions several thousands of lines into the module the following comment appeared:</p>\n\n<pre><code>//if you get here then you really f**ked\n</code></pre>\n\n<p>by that time, i think we knew that already!</p>\n"
},
{
"answer_id": 168881,
"author": "Robert S.",
"author_id": 7565,
"author_profile": "https://Stackoverflow.com/users/7565",
"pm_score": 5,
"selected": false,
"text": "<p>Something like this:</p>\n\n<pre><code>// This method takes two integer values and adds them together via the built-in\n// .NET functionality. It would be possible to code the arithmetic function\n// by hand, but since .NET provides it, that would be a waste of time\nprivate int Add(int i, int j) // i is the first value, j is the second value\n{\n // add the numbers together using the .NET \"+\" operator\n int z = i + j;\n\n // return the value to the calling function\n // return z;\n\n // this code was updated to simplify the return statement, eliminating the need\n // for a separate variable.\n // this statement performs the add functionality using the + operator on the two\n // parameter values, and then returns the result to the calling function\n return i + j;\n}\n</code></pre>\n\n<p>And so on.</p>\n"
},
{
"answer_id": 168941,
"author": "bouvard",
"author_id": 24608,
"author_profile": "https://Stackoverflow.com/users/24608",
"pm_score": 2,
"selected": false,
"text": "<p>I have a very bad habit of doing this, especially when I'm on a roll:</p>\n\n<pre><code>// TODO: Documentation.\n</code></pre>\n"
},
{
"answer_id": 168950,
"author": "CJP",
"author_id": 13152,
"author_profile": "https://Stackoverflow.com/users/13152",
"pm_score": 2,
"selected": false,
"text": "<p>A very large source file, implementing multi-threading in a single process. In the midst of all the call-stack switching and semaphore grabbing and thread suspension and resumption was a simple comment regarding a particularly obscure bit of pointer manipulation:</p>\n\n<pre><code>/* Trickiness */\n</code></pre>\n\n<p>Gee, thanks for sharing.</p>\n"
},
{
"answer_id": 168962,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 3,
"selected": false,
"text": "<p>Would definitely have to be comments that stand in place of error handling.</p>\n\n<pre><code>if(some_condition){\n do_stuff();\n}\nelse{\n //An error occurred!\n}\n</code></pre>\n"
},
{
"answer_id": 169030,
"author": "Levi Rosol",
"author_id": 23458,
"author_profile": "https://Stackoverflow.com/users/23458",
"pm_score": 4,
"selected": false,
"text": "<pre><code>//' OOOO oooo that smell!! Can't you smell that smell!??!??!!!!11!??/!!!!!1!!!!!!1\n\nIf Not Me.CurrentMenuItem.Parent Is Nothing Then\n For Each childMenuItem As MenuItem In aMenuItem.Children\n do something\n Next\n\n If Not Me.CurrentMenuItem.Parent.Parent Is Nothing Then\n //'item is at least a grand child\n For Each childMenuItem As MenuItem In aMenuItem.Children\n For Each grandchildMenuItem As MenuItem In childMenuItem.Children\n do something\n Next\n Next\n\n If Not Me.CurrentMenuItem.Parent.Parent.Parent Is Nothing Then\n //'item is at least a grand grand child\n For Each childMenuItem As MenuItem In aMenuItem.Children\n For Each grandchildMenuItem As MenuItem In childMenuItem.Children\n For Each grandgrandchildMenuItem As MenuItem In grandchildMenuItem.Children\n do something\n Next\n Next\n Next\n\n End If\n End If\nEnd If\n</code></pre>\n"
},
{
"answer_id": 169092,
"author": "BoltBait",
"author_id": 20848,
"author_profile": "https://Stackoverflow.com/users/20848",
"pm_score": 4,
"selected": false,
"text": "<pre><code>try\n{\n...some code...\n}\ncatch\n{\n// Just don't crash, it wasn't that important anyway.\n}\n</code></pre>\n\n<p>*sigh</p>\n"
},
{
"answer_id": 175343,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 1,
"selected": false,
"text": "<p>Taken from legacy code, this was the only description of the following <code>if</code> condition's purpose (the condition spanned 4 rows at 120 cols):</p>\n\n<pre><code>#-- Whoa, now that's a big if condition.\n</code></pre>\n"
},
{
"answer_id": 176001,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 3,
"selected": false,
"text": "<p>This is an absolutely real example from a database trigger:</p>\n\n<pre><code>/******************************************************************************\n NAME: (repeat the trigger name)\n PURPOSE: To perform work as each row is inserted or updated.\n REVISIONS:\n Ver Date Author Description\n --------- ---------- --------------- ------------------------------------\n 1.0 27.6.2000 1. Created this trigger.\n PARAMETERS:\n INPUT:\n OUTPUT:\n RETURNED VALUE:\n CALLED BY:\n CALLS:\n EXAMPLE USE:\n ASSUMPTIONS:\n LIMITATIONS:\n ALGORITHM:\n NOTES:\n******************************************************************************/\n</code></pre>\n"
},
{
"answer_id": 176009,
"author": "Paul Lefebvre",
"author_id": 25615,
"author_profile": "https://Stackoverflow.com/users/25615",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Magic\nmenu.Visible = False\nmenu.Visible = True\n</code></pre>\n\n<p>This is from the UI framework in some PowerBuilder code I used to work on. The framework created menu items dynamically (from database data). However, when PowerBuilder was upgraded from 16-bit to 32-bit, the menu code stopped working. The lead developer somehow determined that hiding the menu and then showing it caused it to display properly.</p>\n"
},
{
"answer_id": 176032,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<pre><code>/** function header comments required to pass checkstyle */\n</code></pre>\n"
},
{
"answer_id": 176048,
"author": "Steropes",
"author_id": 21872,
"author_profile": "https://Stackoverflow.com/users/21872",
"pm_score": 2,
"selected": false,
"text": "<p>Extraneous comment breaks. Normally, if there's a logical separation of flow, a line of comments like:</p>\n\n<pre><code>/***************************************************************************/\n</code></pre>\n\n<p>above and below that section of code can be helpful. Its also nice for when you need to come back later and split apart a large function (that started out small) into several smaller functions to keep the code easy to read.</p>\n\n<p>A former programmer, who shall remain nameless, decided to add the following two lines:</p>\n\n<pre><code>//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\n</code></pre>\n\n<p>After <em>every single line of code</em>.</p>\n"
},
{
"answer_id": 176050,
"author": "Doron Yaacoby",
"author_id": 3389,
"author_profile": "https://Stackoverflow.com/users/3389",
"pm_score": 2,
"selected": false,
"text": "<p>Once I saw the following comment in some code:</p>\n\n<pre><code>//I know that this is very ugly, but I am tired and in a hurry. \n//You would do the same if you were me...\n//...\n//[A piece of nasty code here]\n</code></pre>\n"
},
{
"answer_id": 223242,
"author": "dotnetcoder",
"author_id": 29443,
"author_profile": "https://Stackoverflow.com/users/29443",
"pm_score": 0,
"selected": false,
"text": "<pre><code>/* this is a hack.\n ToDo: change this code */\n</code></pre>\n"
},
{
"answer_id": 223465,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 1,
"selected": false,
"text": "<p>Quoting this from memory so it might not be exact. </p>\n\n<blockquote>\n <p>I don't know what the f*ck this does, but it seems to work so I am not touching it.</p>\n</blockquote>\n\n<p>The funny thing is the way I found out about it. This comment was embedded in an access application some developer in our company had written for a client and distributed in an MDB. Unfortunately the code that \"seems to work\" bombed and Access dutifully opened the code window with the debugger highlighting the line right below the comment. It didn't exactly inspire confidence with that customer.</p>\n"
},
{
"answer_id": 223503,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 2,
"selected": false,
"text": "<p>Here are my two favorites:</p>\n\n<pre><code> // do nothing\n</code></pre>\n\n<p>This doesn't really help as it just takes up space.</p>\n\n<p>Then somewhere further along:</p>\n\n<pre><code> // TODO: DAN to fix this. Not Wes. No sir. Not Wes.\n</code></pre>\n\n<p>I guess if I'm not Dan or Wes, I should just ignore this, right? </p>\n"
},
{
"answer_id": 223512,
"author": "StubbornMule",
"author_id": 13341,
"author_profile": "https://Stackoverflow.com/users/13341",
"pm_score": 0,
"selected": false,
"text": "<pre><code>//I am not sure why this works but it fixes the problem.\n</code></pre>\n\n<p>This one tops the list for my useless comments.</p>\n"
},
{
"answer_id": 223589,
"author": "madlep",
"author_id": 14160,
"author_profile": "https://Stackoverflow.com/users/14160",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// this is messed up, and no one actually knows how it works anymore...\n</code></pre>\n"
},
{
"answer_id": 247084,
"author": "rshimoda",
"author_id": 23297,
"author_profile": "https://Stackoverflow.com/users/23297",
"pm_score": 2,
"selected": false,
"text": "<p>Once upon a time, I saw:</p>\n\n<pre><code>#region This is ugly but a mas has to do what a man has to do\nInitialization of a gigantic array (...)\n#endregion \n// Aren't you glad this has ended?\n</code></pre>\n\n<p>I was glad I was not that developer.</p>\n"
},
{
"answer_id": 247198,
"author": "GalacticCowboy",
"author_id": 29638,
"author_profile": "https://Stackoverflow.com/users/29638",
"pm_score": 3,
"selected": false,
"text": "<p>The two most unhelpful comments I've ever seen...</p>\n\n<pre><code>try\n{\n ...\n}\ncatch\n{\n // TODO: something catchy\n}\n</code></pre>\n\n<p>I posted this one at the Daily WTF also, so I'll trim it to just the comment...</p>\n\n<pre><code> // TODO: The following if block should be reduced to one return statememt:\n // return Regex.IsMatch(strTest, NAME_CHARS);\n if (!Regex.IsMatch(strTest, NAME_CHARS))\n return false;\n else\n return true;\n</code></pre>\n"
},
{
"answer_id": 247232,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 0,
"selected": false,
"text": "<p>someone send me a c file which described a binary file his program created.</p>\n\n<p>it contained no comments except somewhere in the writing of the real data</p>\n\n<pre><code>SwapArray(..); // Big endian ???\nwrite();\n</code></pre>\n\n<p>I asked about the implementation of the SwapArray and he told me I didn't need it, it's just to make sure it works on linux machines.</p>\n\n<p>After experimenting I found out that he used little endian every where (which is like normal) but only the real data was written in big endian. Normally you could see it in a hex editor, but the data was stored in floating point, so it's not that easy to notice the mixed endian.</p>\n"
},
{
"answer_id": 247451,
"author": "Ace",
"author_id": 18673,
"author_profile": "https://Stackoverflow.com/users/18673",
"pm_score": 2,
"selected": false,
"text": "<pre><code>cntrVal = \"\"+ toInteger(cntrVal) //<---MAYBE THIS IS THE WAY I'M GOING THROUGH CHANGES (comin' up comin' up) THIS IS THE WAY I WANNA LIVE\n</code></pre>\n\n<p>That's lyrics from an E-type song btw...</p>\n"
},
{
"answer_id": 247491,
"author": "Aardvark",
"author_id": 3655,
"author_profile": "https://Stackoverflow.com/users/3655",
"pm_score": 1,
"selected": false,
"text": "<p>Someone's name or initials, and that's it. Sometimes these signatures define a block of code...</p>\n\n<pre><code>//SFD Start\n...code...\n//SFD End\n</code></pre>\n\n<p>Like the code is such a work of art they have to sign it! Plus, what if someone else needs to change code marked this way?</p>\n\n<p>This should not be confused with the \"blame\" or \"annotate\" feature in source control systems - they rock!</p>\n"
},
{
"answer_id": 247500,
"author": "endian",
"author_id": 25462,
"author_profile": "https://Stackoverflow.com/users/25462",
"pm_score": 0,
"selected": false,
"text": "<p>Top of the Pops surely has to be </p>\n\n<pre><code>// This code should never be called\n</code></pre>\n"
},
{
"answer_id": 247625,
"author": "Thomas DeGan",
"author_id": 12470,
"author_profile": "https://Stackoverflow.com/users/12470",
"pm_score": 0,
"selected": false,
"text": "<p>My favorite from when I worked on a legacy communications application.</p>\n\n<pre><code>// Magic happens here...\n</code></pre>\n"
},
{
"answer_id": 247750,
"author": "rlb.usa",
"author_id": 449902,
"author_profile": "https://Stackoverflow.com/users/449902",
"pm_score": 2,
"selected": false,
"text": "<pre><code>#include <stdio.h>\n//why isn't this working!\n</code></pre>\n\n<p>With a c-compiler that only supports <code>/*-style */</code> global comments.</p>\n"
},
{
"answer_id": 315540,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 3,
"selected": false,
"text": "<p>One I've never found very helpful:</p>\n\n<pre><code><!--- Lasciate ogne speranza, voi ch'intrate --->\n</code></pre>\n"
},
{
"answer_id": 521961,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 1,
"selected": false,
"text": "<p>Ran across a doozy today. I should have expected it given that it was part of a VBA macro in an excel workbook. </p>\n\n<pre><code>a.writeline s 'write line\n</code></pre>\n\n<p>I found it particularly charming that whomever wrote this took the time to write a comment that used a space to clear up the incredibly confusing jumbled together \"writeline\" command, but didn't find it necessary to use meaningful variable names. Best I can tell a is short for \"a file\", and s is short for \"a String\" (because \"a\" was already taken).</p>\n"
},
{
"answer_id": 521978,
"author": "Greg",
"author_id": 12601,
"author_profile": "https://Stackoverflow.com/users/12601",
"pm_score": 1,
"selected": false,
"text": "<p>Randomly, in the middle of code:</p>\n\n<pre><code>//???\n</code></pre>\n"
},
{
"answer_id": 668071,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 0,
"selected": false,
"text": "<p>Came across this one today:</p>\n\n<pre><code>/// <summary>\n/// The Page_Load runs when the page loads\n/// </summary>\nprivate void Page_Load(Object sender, EventArgs e) {}\n</code></pre>\n"
},
{
"answer_id": 668117,
"author": "Antony Scott",
"author_id": 62951,
"author_profile": "https://Stackoverflow.com/users/62951",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (someFlag)\n{\n // YES\n DoSomething();\n}\nelse\n{\n // NO\n DoSomethingElse();\n}\n</code></pre>\n\n<p>There was one guy who did that constantly, the rest of the team eventually convinced him to stop doing it!</p>\n"
},
{
"answer_id": 777151,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 2,
"selected": false,
"text": "<p>I'm suprised nobody posted one like this before.</p>\n\n<pre><code> #contentWrapper{\n position:absolute;\n top: 150px; /*80 = 30 + 50 where 50 is margin and 30 is the height of the header*/\n }\n</code></pre>\n\n<p>Plain wrong comments are the worst kind of comments.</p>\n"
},
{
"answer_id": 777215,
"author": "Mike Cole",
"author_id": 86191,
"author_profile": "https://Stackoverflow.com/users/86191",
"pm_score": 4,
"selected": false,
"text": "<p>I saw this comment yesterday in a C# app:</p>\n\n<pre><code>//TODO: Remove this comment.\n</code></pre>\n"
},
{
"answer_id": 777220,
"author": "Alex",
"author_id": 94272,
"author_profile": "https://Stackoverflow.com/users/94272",
"pm_score": 2,
"selected": false,
"text": "<p>// Good luck</p>\n"
},
{
"answer_id": 777236,
"author": "Mike Cole",
"author_id": 86191,
"author_profile": "https://Stackoverflow.com/users/86191",
"pm_score": 0,
"selected": false,
"text": "<p>Another one I remember:</p>\n\n<pre><code>//TODO: This needs to be reworked. THIS CRAP NEEDS TO STOP!!!\n</code></pre>\n"
},
{
"answer_id": 777289,
"author": "jonny",
"author_id": 72530,
"author_profile": "https://Stackoverflow.com/users/72530",
"pm_score": 2,
"selected": false,
"text": "<p>Excessive redundancy doesn't clarify what's going on.\nThis one is from mobile phone firmware</p>\n\n<pre><code>/*========================================================================\n\nFUNCTION \n DtFld_SetMin\n\nDESCRIPTION\n This local function sets a nMin member of the Dtfld struct.\n\nDEPENDENCIES\n None\n\nARGUMENTS\n [in]me\n Pointer to the Dtfld struct.\n [in]val\n Value to set\n\nRETURN VALUE\n None.\n\nSIDE EFFECTS\n None\n\nNOTE\n None\n========================================================================*/\n/**\n @brief This local function sets a nMin member of the Dtfld struct..\n @param [in] me Pointer to the Dtfld struct.\n @param [in]val Value to set\n @retval None \n @note None\n @see None\n*/\n\nstatic __inline void DtFld_SetMin(DtFld *me, int val)\n{\n me->nMin = val;\n}\n</code></pre>\n"
},
{
"answer_id": 777328,
"author": "Josef Sábl",
"author_id": 53864,
"author_profile": "https://Stackoverflow.com/users/53864",
"pm_score": 2,
"selected": false,
"text": "<p>We are maintaining terrible mess of PHP application and the original developer had a habit of leaving 'debugging code' commented out in the place. As he always said, it was because \"in case he ever needs them again, he just uncomments them and voila, so it saves him a lot of work\".</p>\n\n<p>So all the scripts are literally riddled with lines like:</p>\n\n<pre><code>//echo \"asdfada\";\n//echo $query.\"afadfadf\";\n</code></pre>\n\n<p>None of them is actually functional in any way. They are mostly there to confirm that code execution reaches that point.</p>\n\n<p>On a related note, he never deleted any obsolete script or database table. So we have directories filled with files like dosomething.php, dosomething1.php, dosomething1.bak, dosomething1.bak.php etc... Everybody scared to delete anything because nobody knows, what is really used.</p>\n"
},
{
"answer_id": 777332,
"author": "Stefan Kendall",
"author_id": 78182,
"author_profile": "https://Stackoverflow.com/users/78182",
"pm_score": 1,
"selected": false,
"text": "<p>This:</p>\n\n<p>Yup, a blank space, left as a subversion change log.</p>\n"
},
{
"answer_id": 777358,
"author": "kjv",
"author_id": 1360,
"author_profile": "https://Stackoverflow.com/users/1360",
"pm_score": 2,
"selected": false,
"text": "<pre><code>/// <summary>\n/// Disables the web part. (Virtual method)\n/// </summary>\npublic virtual void EnableWebPart() { /* nothing - you have to override it */ }\n</code></pre>\n"
},
{
"answer_id": 777484,
"author": "Pierre-Luc Simard",
"author_id": 68554,
"author_profile": "https://Stackoverflow.com/users/68554",
"pm_score": 2,
"selected": false,
"text": "<p>I work in two languages, (English and French) but my favorite comment was in french:</p>\n\n<pre><code>/* La passe du coyote qui tousse */\n</code></pre>\n\n<p>Translated it would gives something like this:</p>\n\n<pre><code>/* The coughing coyote trick */\n</code></pre>\n\n<p>It usually represented a segment of code that either seemed like a clever idea to the author and was completly obscure or it was a weird bugfix that even the author did not understand why it worked (think fixing a race condition by moving if statements around). In all cases it was poorly written code that scared anybody who had to refactor it because it was very hard to predict the effect of changing it.</p>\n"
},
{
"answer_id": 777512,
"author": "Kapsh",
"author_id": 45730,
"author_profile": "https://Stackoverflow.com/users/45730",
"pm_score": 0,
"selected": false,
"text": "<pre><code>{\n Long complicated code logic //Added this\n}\n</code></pre>\n"
},
{
"answer_id": 876238,
"author": "Nathan W",
"author_id": 6335,
"author_profile": "https://Stackoverflow.com/users/6335",
"pm_score": 1,
"selected": false,
"text": "<p>I found this in a sample application for a mapping product:</p>\n\n<pre><code>// Return value does not matter\nreturn 0;\n</code></pre>\n"
},
{
"answer_id": 913327,
"author": "vikingosegundo",
"author_id": 106435,
"author_profile": "https://Stackoverflow.com/users/106435",
"pm_score": 1,
"selected": false,
"text": "<p>I found this in a twisted program</p>\n\n<pre><code># Let them send messages to the world\n#del self.irc_PRIVMSG # By deleting the method? Hello?\n</code></pre>\n"
},
{
"answer_id": 1288277,
"author": "andersonbd1",
"author_id": 125864,
"author_profile": "https://Stackoverflow.com/users/125864",
"pm_score": 1,
"selected": false,
"text": "<pre><code>/**\n * Implements the PaymentType interface.\n */\npublic class PaymentTypePo implements PaymentType\n</code></pre>\n"
},
{
"answer_id": 1544091,
"author": "Peter Turner",
"author_id": 1765,
"author_profile": "https://Stackoverflow.com/users/1765",
"pm_score": 3,
"selected": false,
"text": "<p>AHHHRRRGGHHH Just found this in some ancient code, bet the guy thought he was pretty funny</p>\n\n<pre><code>private\n //PRIVATE means PRIVATE so no comments for you\n function LoadIt(IntID: Integer): Integer;\n</code></pre>\n"
},
{
"answer_id": 1545805,
"author": "snicker",
"author_id": 160359,
"author_profile": "https://Stackoverflow.com/users/160359",
"pm_score": 3,
"selected": false,
"text": "<p>I just found this one, written on the line before a commented-out line of code:</p>\n\n<pre><code>//This causes a crash for some reason. I know the real reason but it doesn't fit on this line.\n</code></pre>\n"
},
{
"answer_id": 1545906,
"author": "Jason Williams",
"author_id": 97385,
"author_profile": "https://Stackoverflow.com/users/97385",
"pm_score": 1,
"selected": false,
"text": "<p>I once worked with a very talented assembly language programmer who had augmented the basic ARM instruction set with a number of macros. His code was made up of <em>tens of thousands</em> of instructions and looked something like the following - with macro instructions that I (a competent ARM programmer) couldn't read represented by ??? and an occasional regular ARM instruction like ADD:</p>\n\n<pre>\n...\n??? R0,R0,#1\n??? R0,R1\nADD R0,R0,#6 ; Add 6\n??? R1,R0\n??? R0,R0,R1\n...\n</pre>\n\n<p>I can only presume that when you have a brain the size of a planet, it is too high brow to cope with those pesky instructions that are just too damn simple.</p>\n"
},
{
"answer_id": 1556746,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 1,
"selected": false,
"text": "<p>Found this one today in the middle of a block of declarations:</p>\n\n<pre><code>// other variables\n</code></pre>\n\n<p>Gee, really? Thanks.</p>\n"
},
{
"answer_id": 1556786,
"author": "Earlz",
"author_id": 69742,
"author_profile": "https://Stackoverflow.com/users/69742",
"pm_score": 2,
"selected": false,
"text": "<pre><code>add ax,1 ;add 1 to the accumulator\n</code></pre>\n\n<p>seriously? that comment wasted 5 seconds of my life.</p>\n\n<p>also outdated comments FTL</p>\n\n<pre><code>//the system can only handle 5 people right now. make sure where not over\nif(num_people>20){ \n</code></pre>\n"
},
{
"answer_id": 1556888,
"author": "Hector Minaya",
"author_id": 177394,
"author_profile": "https://Stackoverflow.com/users/177394",
"pm_score": 0,
"selected": false,
"text": "<p>{Some Code;} // I don't Remember why I do this, but it works...</p>\n"
},
{
"answer_id": 1557214,
"author": "Makach",
"author_id": 57731,
"author_profile": "https://Stackoverflow.com/users/57731",
"pm_score": 0,
"selected": false,
"text": "<p>Actually I have a few of these,</p>\n\n<pre><code>// 18042009: (Name here) made me do this\n</code></pre>\n\n<p>Not very proud of those comments but I keep them to remind me why I did WTF code that particular section, so useful in that aspect. </p>\n"
},
{
"answer_id": 1557241,
"author": "John Lechowicz",
"author_id": 186384,
"author_profile": "https://Stackoverflow.com/users/186384",
"pm_score": 1,
"selected": false,
"text": "<p>I one time came across this little beauty in a VB.NET app</p>\n\n<pre><code>Dim huh as String 'Best name for a variable ever.\n</code></pre>\n"
},
{
"answer_id": 1662589,
"author": "DisgruntledGoat",
"author_id": 37947,
"author_profile": "https://Stackoverflow.com/users/37947",
"pm_score": 0,
"selected": false,
"text": "<p>I recently found this in some code I wrote aeons ago:</p>\n\n<pre><code>// it's a kind of magic (number)\n$descr_id = 2;\n$url_id = 34;\n</code></pre>\n"
},
{
"answer_id": 1718172,
"author": "Eli",
"author_id": 27580,
"author_profile": "https://Stackoverflow.com/users/27580",
"pm_score": 1,
"selected": false,
"text": "<p><strong>// return</strong></p>\n\n<p><strong>return;</strong></p>\n"
},
{
"answer_id": 1760755,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 1,
"selected": false,
"text": "<p>Just found this one today...</p>\n\n<pre><code>// TODO: this is basically a copy of the code at line 743!!!\n</code></pre>\n"
},
{
"answer_id": 1767759,
"author": "Martha",
"author_id": 121333,
"author_profile": "https://Stackoverflow.com/users/121333",
"pm_score": 0,
"selected": false,
"text": "<p>This comment was actually written in a different language, but I'll try to get the effect across in a translation:</p>\n\n<pre><code>//we trick it, if forbidden, as if it had already existed\n</code></pre>\n\n<p>What the comment was trying to describe was the way it was dealing with list items that were turned off - the code marked the item as a duplicate which should therefore be skipped. Yes, a very bass-ackwards way of doing things, but it paled in comparison to the nonsensical comment.</p>\n"
},
{
"answer_id": 1767798,
"author": "whybird",
"author_id": 156118,
"author_profile": "https://Stackoverflow.com/users/156118",
"pm_score": 0,
"selected": false,
"text": "<pre><code>[some code]\n// [a commented out code line]\n// this line added 2004-10-24 by JD.\n// removed again 2004-11-05 by JD.\n// [another commented out code line]\n[some more code]\n</code></pre>\n\n<p>a) WHY?\nb) Which line?</p>\n"
},
{
"answer_id": 1767834,
"author": "Secko",
"author_id": 127269,
"author_profile": "https://Stackoverflow.com/users/127269",
"pm_score": 2,
"selected": false,
"text": "<p>One of the funniest I have ever come across.</p>\n\n<pre><code>// HACK HACK HACK. REMOVE THIS ONCE MARLETT IS AROUND\n</code></pre>\n\n<p>One that made me wonder.</p>\n\n<pre><code>// this is a comment - don't delete\n</code></pre>\n"
},
{
"answer_id": 1767900,
"author": "Elle H",
"author_id": 23666,
"author_profile": "https://Stackoverflow.com/users/23666",
"pm_score": 1,
"selected": false,
"text": "<p>This is a comment I wrote in a file in my group's final project in college</p>\n\n<pre><code>/* http://youtube.com/watch?v=oHg5SJYRHA0 */\n</code></pre>\n"
},
{
"answer_id": 1767906,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 1,
"selected": false,
"text": "<p>A classic that we always joke about at my job (complete with typos):</p>\n\n<pre><code>// Its stupid but it work\n</code></pre>\n\n<p>This was found multiple times in an old code base.</p>\n"
},
{
"answer_id": 1767945,
"author": "Daniel Rodriguez",
"author_id": 131319,
"author_profile": "https://Stackoverflow.com/users/131319",
"pm_score": 0,
"selected": false,
"text": "<p>I saw an awesome code inside the AI part of a game:</p>\n\n<pre><code>...\"AI code\"...\nif(something)\n goto MyAwesomeLabel; //Who's gonna be the first to dump crap on me for this?\n...\"More Ai code\"...\n\nMyAwesomeLabel:\n //It wasn't that hard to get here, right?\n ...\"Even more AI code\"...\n</code></pre>\n"
},
{
"answer_id": 1889256,
"author": "Dan J",
"author_id": 112705,
"author_profile": "https://Stackoverflow.com/users/112705",
"pm_score": 1,
"selected": false,
"text": "<p>I had to fix a bug in 2000 lines of code that transcoded audio from GSM into mu-law (mostly using bit shifting and arrays of conversion values). The only comment in the file was at the top of the only method defined in it. It was:</p>\n\n<pre><code>/* Do the business */\n</code></pre>\n"
},
{
"answer_id": 2004112,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 1,
"selected": false,
"text": "<p><code>// Undocumented</code></p>\n"
},
{
"answer_id": 2004121,
"author": "jfawcett",
"author_id": 186680,
"author_profile": "https://Stackoverflow.com/users/186680",
"pm_score": 1,
"selected": false,
"text": "<p>I was once maintaining the operating system code we customized for a Harris minicomputer (yes, this was a long time ago). Going through the scheduler code (assembler) one day, I came across a code block that had the comment \"Begin Magic\" at the top and about 25 lines later the comment \"End Magic.\" The code in-between was some of the tightest, most complicated, elegant code I've ever seen. It took 4 of us to figure out what that little section of code was actually doing (VM switching).</p>\n"
},
{
"answer_id": 2203103,
"author": "Michael Todd",
"author_id": 16623,
"author_profile": "https://Stackoverflow.com/users/16623",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// yes, this is going to break in 2089, but, one, I'll be dead, and two, we really ought to be using\n// a different system by then\nif (yearPart >= 89)\n{\n // naughty bits removed....\n}\n</code></pre>\n\n<p>(Not useful as comments go, but both are truthful statements.)</p>\n"
},
{
"answer_id": 2390250,
"author": "Dr.Optix",
"author_id": 238944,
"author_profile": "https://Stackoverflow.com/users/238944",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>//URGENT TODO: Reimplement this shit,\n the old code is as broken as hell...\n and we tought we solved all the\n problems</p>\n</blockquote>\n\n<p>Just found that in one of my old projects. At first I laughed but in the end I was bitching because I still couldn't find the bug. </p>\n"
},
{
"answer_id": 2390289,
"author": "pestilence669",
"author_id": 226917,
"author_profile": "https://Stackoverflow.com/users/226917",
"pm_score": 0,
"selected": false,
"text": "<p><code># Below is stub documentation for your module. You'd better edit it</code></p>\n"
},
{
"answer_id": 3732919,
"author": "EMP",
"author_id": 20336,
"author_profile": "https://Stackoverflow.com/users/20336",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// initialise the static variable to 0\ncount = 1;\n</code></pre>\n"
},
{
"answer_id": 3760435,
"author": "dagofly",
"author_id": 453875,
"author_profile": "https://Stackoverflow.com/users/453875",
"pm_score": 1,
"selected": false,
"text": "<p>I'm making some changes in a java class that has more than 1000 lines but without any comments. I'm newbie in their coding style so i can't help myself about adding a comment like </p>\n\n<pre><code>/*Added because someone asked me to add it*/\n</code></pre>\n"
},
{
"answer_id": 3811919,
"author": "greuze",
"author_id": 460306,
"author_profile": "https://Stackoverflow.com/users/460306",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if (returnValue ==0)\n doStuff();\nelse\n System.out.println(\"Beware of you, the Dragons are coming!\");\n</code></pre>\n"
},
{
"answer_id": 3843271,
"author": "MPelletier",
"author_id": 210916,
"author_profile": "https://Stackoverflow.com/users/210916",
"pm_score": 2,
"selected": false,
"text": "<p>I just saw this in an INI file for a software (one of several dumped on me not long ago) I'm maintaining:</p>\n\n<pre><code>;--- if LOGERR=1, errors are logged but debugging is difficult\n;--- if LOGERR=0, errors are not logged but debugging is easy\nLOGERR=1\n</code></pre>\n\n<p>Well, debugging was indeed difficult, but I did not dare change the setting.</p>\n"
},
{
"answer_id": 3843352,
"author": "Snekse",
"author_id": 378151,
"author_profile": "https://Stackoverflow.com/users/378151",
"pm_score": 0,
"selected": false,
"text": "<p>Not quite fitting to the question, but I hate when I see:</p>\n\n<pre><code>try\n{\n someSeeminglyTrivialMethod();\n}\ncatch (Exception e)\n{\n //Ignore. Should never happen.\n}\n</code></pre>\n\n<p>Whenever I see that during a code review, I tell them to replace the catch with:</p>\n\n<pre><code>catch (Exception e)\n{\n System.exit(0);\n}\n</code></pre>\n"
}
]
| 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,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 2,
"selected": false,
"text": "<p>Try setting <a href=\"http://developer.mozilla.org/en/DOM/document.title\" rel=\"nofollow noreferrer\">document.title</a> to the new value</p>\n"
}
]
| 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 example.</p>\n\n<p>I'll post one period of time here, and all the different variations of other periods that overlap in some way.</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |-------------------| compare to this one\n |---------| contained within\n |----------| contained within, equal start\n |-----------| contained within, equal end\n |-------------------| contained within, equal start+end\n |------------| not fully contained, overlaps start\n |---------------| not fully contained, overlaps end\n |-------------------------| overlaps start, bigger\n |-----------------------| overlaps end, bigger\n |------------------------------| overlaps entire period\n</code></pre>\n\n<p>on the other hand, let me post all those that doesn't overlap:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |-------------------| compare to this one\n |---| ends before\n |---| starts after\n</code></pre>\n\n<p>So if you simple reduce the comparison to:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>starts after end\nends before start\n</code></pre>\n\n<p>then you'll find all those that doesn't overlap, and then you'll find all the non-matching periods.</p>\n\n<p>For your final NOT IN LIST example, you can see that it matches those two rules.</p>\n\n<p>You will need to decide wether the following periods are IN or OUTSIDE your ranges:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code> |-------------|\n |-------| equal end with start of comparison period\n |-----| equal start with end of comparison period\n</code></pre>\n\n<p>If your table has columns called range_end and range_start, here's some simple SQL to retrieve all the matching rows:</p>\n\n\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM periods\nWHERE NOT (range_start > @check_period_end\n OR range_end < @check_period_start)\n</code></pre>\n\n<p>Note the <em>NOT</em> in there. Since the two simple rules finds all the <em>non-matching</em> rows, a simple NOT will reverse it to say: <em>if it's not one of the non-matching rows, it has to be one of the matching ones</em>.</p>\n\n<p>Applying simple reversal logic here to get rid of the NOT and you'll end up with:</p>\n\n\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM periods\nWHERE range_start <= @check_period_end\n AND range_end >= @check_period_start\n</code></pre>\n"
},
{
"answer_id": 143575,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": false,
"text": "<p>Taking your example range of 06/06/1983 to 18/06/1983 and assuming you have columns called <strong>start</strong> and <strong>end</strong> for your ranges, you could use a clause like this</p>\n\n<pre><code>where ('1983-06-06' <= end) and ('1983-06-18' >= start)\n</code></pre>\n\n<p>i.e. check the start of your test range is before the end of the database range, and that the end of your test range is after or on the start of the database range.</p>\n"
},
{
"answer_id": 146595,
"author": "David Aldridge",
"author_id": 6742,
"author_profile": "https://Stackoverflow.com/users/6742",
"pm_score": 3,
"selected": false,
"text": "<p>If your RDBMS supports the OVERLAP() function then this becomes trivial -- no need for homegrown solutions. (In Oracle it apparantly works but is undocumented).</p>\n"
},
{
"answer_id": 148709,
"author": "onedaywhen",
"author_id": 15354,
"author_profile": "https://Stackoverflow.com/users/15354",
"pm_score": 0,
"selected": false,
"text": "<p>In your expected results you say </p>\n\n<p>06/06/1983 to 18/06/1983 = IN LIST</p>\n\n<p>However, this period does not contain nor is contained by any of the periods in your table (not list!) of periods. It does, however, overlap the period 10/06/1983 to 14/06/1983.</p>\n\n<p>You may find the Snodgrass book (<a href=\"http://www.cs.arizona.edu/people/rts/tdbbook.pdf\" rel=\"nofollow noreferrer\">http://www.cs.arizona.edu/people/rts/tdbbook.pdf</a>) useful: it pre-dates mysql but the concept of time hasn't changed ;-)</p>\n"
},
{
"answer_id": 5864708,
"author": "jonavon",
"author_id": 167540,
"author_profile": "https://Stackoverflow.com/users/167540",
"pm_score": 0,
"selected": false,
"text": "<p>I created function to deal with this problem in MySQL. Just convert the dates to seconds before use.</p>\n\n<pre><code>DELIMITER ;;\n\nCREATE FUNCTION overlap_interval(x INT,y INT,a INT,b INT)\nRETURNS INTEGER DETERMINISTIC\nBEGIN\nDECLARE\n overlap_amount INTEGER;\n IF (((x <= a) AND (a < y)) OR ((x < b) AND (b <= y)) OR (a < x AND y < b)) THEN\n IF (x < a) THEN\n IF (y < b) THEN\n SET overlap_amount = y - a;\n ELSE\n SET overlap_amount = b - a;\n END IF;\n ELSE\n IF (y < b) THEN\n SET overlap_amount = y - x;\n ELSE\n SET overlap_amount = b - x;\n END IF;\n END IF;\n ELSE\n SET overlap_amount = 0;\n END IF;\n RETURN overlap_amount;\nEND ;;\n\nDELIMITER ;\n</code></pre>\n"
},
{
"answer_id": 8557604,
"author": "Rama Subba Reddy M",
"author_id": 868917,
"author_profile": "https://Stackoverflow.com/users/868917",
"pm_score": 0,
"selected": false,
"text": "<p>Look into the following example. It will helpful for you.</p>\n\n<pre><code> SELECT DISTINCT RelatedTo,CAST(NotificationContent as nvarchar(max)) as NotificationContent,\n ID,\n Url,\n NotificationPrefix,\n NotificationDate\n FROM NotificationMaster as nfm\n inner join NotificationSettingsSubscriptionLog as nfl on nfm.NotificationDate between nfl.LastSubscribedDate and isnull(nfl.LastUnSubscribedDate,GETDATE())\n where ID not in(SELECT NotificationID from removednotificationsmaster where Userid=@userid) and nfl.UserId = @userid and nfl.RelatedSettingColumn = RelatedTo\n</code></pre>\n"
},
{
"answer_id": 14312925,
"author": "Paul Williamson",
"author_id": 1976318,
"author_profile": "https://Stackoverflow.com/users/1976318",
"pm_score": 0,
"selected": false,
"text": "<pre><code>CREATE FUNCTION overlap_date(s DATE, e DATE, a DATE, b DATE)\nRETURNS BOOLEAN DETERMINISTIC\nRETURN s BETWEEN a AND b or e BETWEEN a and b or a BETWEEN s and e;\n</code></pre>\n"
},
{
"answer_id": 27815104,
"author": "RickyS",
"author_id": 4427966,
"author_profile": "https://Stackoverflow.com/users/4427966",
"pm_score": 0,
"selected": false,
"text": "<p>Try This on MS SQL</p>\n\n<hr>\n\n<pre><code>WITH date_range (calc_date) AS (\nSELECT DATEADD(DAY, DATEDIFF(DAY, 0, [ending date]) - DATEDIFF(DAY, [start date], [ending date]), 0)\nUNION ALL SELECT DATEADD(DAY, 1, calc_date)\nFROM date_range \nWHERE DATEADD(DAY, 1, calc_date) <= [ending date])\nSELECT P.[fieldstartdate], P.[fieldenddate]\nFROM date_range R JOIN [yourBaseTable] P on Convert(date, R.calc_date) BETWEEN convert(date, P.[fieldstartdate]) and convert(date, P.[fieldenddate]) \nGROUP BY P.[fieldstartdate], P.[fieldenddate];\n</code></pre>\n"
},
{
"answer_id": 33148731,
"author": "Florian HENRY - Scopen",
"author_id": 2418749,
"author_profile": "https://Stackoverflow.com/users/2418749",
"pm_score": 0,
"selected": false,
"text": "<p>Another method by using BETWEEN sql statement</p>\n\n<p>Periods included : </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM periods\nWHERE @check_period_start BETWEEN range_start AND range_end\n AND @check_period_end BETWEEN range_start AND range_end\n</code></pre>\n\n<p>Periods excluded : </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>SELECT *\nFROM periods\nWHERE (@check_period_start NOT BETWEEN range_start AND range_end\n OR @check_period_end NOT BETWEEN range_start AND range_end)\n</code></pre>\n"
},
{
"answer_id": 44704468,
"author": "Gio",
"author_id": 8200935,
"author_profile": "https://Stackoverflow.com/users/8200935",
"pm_score": -1,
"selected": false,
"text": "<pre><code>SELECT * \nFROM tabla a \nWHERE ( @Fini <= a.dFechaFin AND @Ffin >= a.dFechaIni )\n AND ( (@Fini >= a.dFechaIni AND @Ffin <= a.dFechaFin) OR (@Fini >= a.dFechaIni AND @Ffin >= a.dFechaFin) OR (a.dFechaIni>=@Fini AND a.dFechaFin <=@Ffin) OR\n(a.dFechaIni>=@Fini AND a.dFechaFin >=@Ffin) )\n</code></pre>\n"
}
]
| 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\n55 17 * * * ur_user_is_missing ruby /home/raguanu/Dropbox/nettie.rb >> /tmp/cron_test\n</code></pre>\n"
},
{
"answer_id": 143601,
"author": "Douglas Leeder",
"author_id": 3978,
"author_profile": "https://Stackoverflow.com/users/3978",
"pm_score": 1,
"selected": false,
"text": "<p>Programs run from cron don't have your interactive environment. Therefore they don't have and DISPLAY variable, and so you can't run any X (graphical) programs, e.g. Firefox.</p>\n\n<p>I would suggest doing the HTTP connections yourself, in ruby, rather than trying to automate Firefox.</p>\n"
},
{
"answer_id": 143605,
"author": "Roshan",
"author_id": 15806,
"author_profile": "https://Stackoverflow.com/users/15806",
"pm_score": 3,
"selected": true,
"text": "<p>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. </p>\n\n<p>There's a few things to keep in mind though:\nYou 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:</p>\n\n<pre><code>Xvfb :1 -screen 0 1600x1200x32\n</code></pre>\n\n<p>Then you'll be able to use this by setting the DISPLAY variable to :1</p>\n\n<p>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. </p>\n\n<p>There's even a ruby binding for curl: \n<a href=\"http://curl.haxx.se/libcurl/ruby/\" rel=\"nofollow noreferrer\">libcurl for Ruby</a>. The resulting script should be much smaller than your current script.</p>\n"
}
]
| 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 should work.</p>\n\n<p>For more info, check here:\n<a href=\"http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html\" rel=\"nofollow noreferrer\">http://bradwilson.typepad.com/blog/2008/08/partial-renderi.html</a></p>\n"
},
{
"answer_id": 143594,
"author": "Ricky",
"author_id": 653,
"author_profile": "https://Stackoverflow.com/users/653",
"pm_score": 4,
"selected": false,
"text": "<p>Do what @BenScheirman said, and add a semi-colon at the end of your statement :)</p>\n\n<pre><code><% Html.RenderPartial(\"~/Views/Shared/Footer.ascx\"); %>\n</code></pre>\n\n<p>Update: I guess VB doesn't require the semi-colon. So you would only need that if you are programming in C#.</p>\n"
}
]
| 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": 143631,
"author": "Ian P",
"author_id": 10853,
"author_profile": "https://Stackoverflow.com/users/10853",
"pm_score": 2,
"selected": false,
"text": "<p>No -- As Chris Jester-Young said, it will be thrown up to the next try-catch in the hierarchy.</p>\n"
},
{
"answer_id": 143660,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>As said above...<br>\nI would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).</p>\n"
},
{
"answer_id": 143671,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 6,
"selected": false,
"text": "<p>No. It's very easy to check.</p>\n\n<pre><code>public class Catch {\n public static void main(String[] args) {\n try {\n throw new java.io.IOException();\n } catch (java.io.IOException exc) {\n System.err.println(\"In catch IOException: \"+exc.getClass());\n throw new RuntimeException();\n } catch (Exception exc) {\n System.err.println(\"In catch Exception: \"+exc.getClass());\n } finally {\n System.err.println(\"In finally\");\n }\n }\n}\n</code></pre>\n\n<p>Should print:</p>\n\n<pre>\nIn catch IOException: class java.io.IOException\nIn finally\nException in thread \"main\" java.lang.RuntimeException\n at Catch.main(Catch.java:8)</pre>\n\n<p>Technically that could have been a compiler bug, implementation dependent, unspecified behaviour, or something. However, the JLS is pretty well nailed down and the compilers are good enough for this sort of simple thing (generics corner case may be a different matter).</p>\n\n<p>Also note, if you swap around the two catch blocks, it wont compile. The second catch would be completely unreachable.</p>\n\n<p>Note the finally block always runs even if a catch block is executed (other than silly cases, such as infinite loops, attaching through the tools interface and killing the thread, rewriting bytecode, etc.).</p>\n"
},
{
"answer_id": 143674,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>It won't be caught by the second catch block. Each Exception is caught only when inside a try block. You can nest tries though (not that it's a good idea generally):</p>\n\n<pre><code>try {\n doSomething();\n} catch (IOException) {\n try {\n doSomething();\n } catch (IOException e) {\n throw new ApplicationException(\"Failed twice at doSomething\" +\n e.toString());\n } \n} catch (Exception e) {\n}\n</code></pre>\n"
},
{
"answer_id": 144588,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 1,
"selected": false,
"text": "<p>No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one) </p>\n"
},
{
"answer_id": 144944,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 5,
"selected": false,
"text": "<p>The Java Language Specification says in section 14.19.1:</p>\n<blockquote>\n<p>If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:</p>\n<ul>\n<li>If the run-time type of V is assignable to the Parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. If that block completes normally, then the try statement completes normally; <strong>if that block completes abruptly for any reason, then the try statement completes abruptly for the same reason.</strong></li>\n</ul>\n</blockquote>\n<p>Reference:\n<a href=\"http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134\" rel=\"noreferrer\">http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#24134</a></p>\n<p>In other words, the first enclosing catch that can handle the exception does, and if an exception is thrown out of that catch, that's not in the scope of any other catch for the original try, so they will not try to handle it.</p>\n<p>One related and confusing thing to know is that in a try-[catch]-finally structure, a finally block may throw an exception and if so, any exception thrown by the try or catch block is lost. That can be confusing the first time you see it.</p>\n"
},
{
"answer_id": 17111311,
"author": "Mastergeek",
"author_id": 965571,
"author_profile": "https://Stackoverflow.com/users/965571",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to throw an exception from the catch block you must inform your method/class/etc. that it needs to throw said exception. Like so:</p>\n\n<pre><code>public void doStuff() throws MyException {\n try {\n //Stuff\n } catch(StuffException e) {\n throw new MyException();\n }\n}\n</code></pre>\n\n<p>And now your compiler will not yell at you :)</p>\n"
},
{
"answer_id": 20308711,
"author": "Ted K",
"author_id": 2324774,
"author_profile": "https://Stackoverflow.com/users/2324774",
"pm_score": -1,
"selected": false,
"text": "<p>Old post but \"e\" variable must be unique:</p>\n\n<pre><code>try {\n // Do something\n} catch(IOException ioE) {\n throw new ApplicationException(\"Problem connecting to server\");\n} catch(Exception e) {\n // Will the ApplicationException be caught here?\n}\n</code></pre>\n"
}
]
| 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 consider RPM and cygwin to do the installation. You could even set up a yum or apt repository to deliver the packages to remote systems.</p>\n\n<p>If you're looking for a general installer for customers running any number of OSes and distros, then the problem becomes much harder.</p>\n"
},
{
"answer_id": 143990,
"author": "Dave Rolsky",
"author_id": 9832,
"author_profile": "https://Stackoverflow.com/users/9832",
"pm_score": 3,
"selected": false,
"text": "<p>The answer suggesting RPM is definitely a good one. Using your system's package manager can definitely make your life easier. However, it might mean you also need to package up a bunch of other Perl modules.</p>\n\n<p>You might also take a look at <a href=\"http://search.cpan.org/dist/Shipwright/\" rel=\"noreferrer\">Shipwright</a>. This is a Perl-based tool for packaging up an app and all its Perl module dependencies. It's early days yet, but it looks promising.</p>\n\n<p>As far as installing dependencies, it wouldn't be hard to simply package up a bunch of tarballs and then have you Module::Build-based solution install them. You should take a look at <a href=\"http://search.cpan.org/dist/pip/\" rel=\"noreferrer\">pip</a>, which makes installing a module from a tarball quite trivial. You could package this with your code base and simply call it from your own installer to handle the deps.</p>\n\n<p>I question whether relying on CPAN is a good idea. The CPAN shell always fetches the latest version of a distro, rather than a specific version. If you're interested in ensuring repeatable installs, it's not the right tool.</p>\n"
},
{
"answer_id": 144216,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": true,
"text": "<p>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?</p>\n<p>For most of my stuff, which involves sysadmins familiar with Perl installing in control environments, I just use <a href=\"http://search.cpan.org/dist/ExtUtils-Makemaker\" rel=\"nofollow noreferrer\">MakeMaker</a>. It's easy to get it to do all the things you listed if you know a little about <code>MakeMaker</code>. If you want to know more about that, ask a another question. ;) <a href=\"http://search.cpan.org/dist/Module-Build\" rel=\"nofollow noreferrer\">Module::Build</a> is just as easy, though, and the way to go if you don't already like using <code>MakeMaker</code>.</p>\n<p><code>Module::Build</code> 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 <code>Module::Build</code>, but also a bit more work. And, the <code>cpan</code> tool (which comes with Perl), can install from the current directory and handle dependencies for you. Just tell it to install the current directory:</p>\n<pre><code> $ cpan .\n</code></pre>\n<p>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 <code>Module::Build</code> make that package for you so the developers have the flexibility of <code>Module::Build</code>, but the installers have the ease of the native process. Sticking with <code>Module::Build</code> also means that you could create different packages for different platforms from a single build tool.</p>\n<p>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.</p>\n<p>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.</p>\n<p>Good luck, :)</p>\n"
},
{
"answer_id": 148616,
"author": "draegtun",
"author_id": 12195,
"author_profile": "https://Stackoverflow.com/users/12195",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at <a href=\"http://search.cpan.org/dist/PAR/\" rel=\"nofollow noreferrer\">PAR</a>.</p>\n\n<p>Jonathan Rockway as a small section on using this with Catalyst in his book.</p>\n"
}
]
| 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 noreferrer\">bitwise AND operator</a> \"&\" and compare the result to zero. Even better, instead of coding the roles as bits of an integer column, use boolean columns, one for each role. Then your query would simply be designer AND programmer friendly. If you expect the roles to change a lot over the lifetime of your application, then use a many-to-many table to map the association between users and their roles. both alternatives are more portable than relying on the existence of the bitwise-AND operator.</p>\n"
},
{
"answer_id": 143919,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 0,
"selected": false,
"text": "<p>To find all programmers use:</p>\n\n<pre><code>SELECT * FROM UserTable WHERE Roles & 2 = 2\n</code></pre>\n"
},
{
"answer_id": 3561525,
"author": "vsevik",
"author_id": 428563,
"author_profile": "https://Stackoverflow.com/users/428563",
"pm_score": 2,
"selected": false,
"text": "<p>SELECT * FROM table WHERE mask1 & mask2 > 0</p>\n"
},
{
"answer_id": 3561763,
"author": "ScottE",
"author_id": 112194,
"author_profile": "https://Stackoverflow.com/users/112194",
"pm_score": 2,
"selected": false,
"text": "<p>example:</p>\n\n<pre><code>DECLARE @Mask int\nSET @Mask = 6\n\nDECLARE @Users TABLE\n(\nID int,\nUsername varchar(50),\nRoles int\n)\n\nINSERT INTO @Users (ID, Username, Roles) \nSELECT 1, 'Dave', 6\nUNION\nSELECT 2, 'Charlie', 2\nUNION\nSELECT 3, 'Susan', 4\nUNION\nSELECT 4, 'Nick', 1\n\nSELECT * FROM @Users WHERE Roles & @Mask > 0\n</code></pre>\n"
},
{
"answer_id": 9262624,
"author": "Ben",
"author_id": 1139212,
"author_profile": "https://Stackoverflow.com/users/1139212",
"pm_score": 3,
"selected": false,
"text": "<pre><code>SELECT * FROM UserTable WHERE Roles & 6 > 0\n</code></pre>\n"
},
{
"answer_id": 9263250,
"author": "Jamiec",
"author_id": 219661,
"author_profile": "https://Stackoverflow.com/users/219661",
"pm_score": 8,
"selected": true,
"text": "<p>The answer to your question is to use the Bitwise <code>&</code> like this:</p>\n\n<pre><code>SELECT * FROM UserTable WHERE Roles & 6 != 0\n</code></pre>\n\n<p>The <code>6</code> 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:</p>\n\n<pre><code> 1 2 4\n------------------\nDave 0 1 1\nCharlie 0 1 0\nSusan 0 0 1 \nNick 1 0 0\n</code></pre>\n\n<p>Your test (6) is this</p>\n\n<pre><code> 1 2 4\n------------------\nTest 0 1 1\n</code></pre>\n\n<p>If we go through each person doing the bitwaise And against the test we get these:</p>\n\n<pre><code> 1 2 4\n------------------\nDave 0 1 1 \nTest 0 1 1\nResult 0 1 1 (6)\n\nCharlie 0 1 0\nTest 0 1 1\nResult 0 1 0 (2)\n\nSusan 0 0 1\nTest 0 1 1\nResult 0 0 1 (4)\n\nNick 1 0 0\nTest 0 1 1\nResult 0 0 0 (0) \n</code></pre>\n\n<p>The above should demonstrate that any records where the result is not zero has one or more of the requested flags.</p>\n\n<p>Edit: Here's the test case should you want to check this</p>\n\n<pre><code>with test (id, username, roles)\nAS\n(\n SELECT 1,'Dave',6\n UNION SELECT 2,'Charlie',2\n UNION SELECT 3,'Susan',4\n UNION SELECT 4,'Nick',1\n)\nselect * from test where (roles & 6) != 0 // returns dave, charlie & susan\n</code></pre>\n\n<p>or </p>\n\n<pre><code>select * from test where (roles & 2) != 0 // returns Dave & Charlie\n</code></pre>\n\n<p>or</p>\n\n<pre><code>select * from test where (roles & 7) != 0 // returns dave, charlie, susan & nick\n</code></pre>\n"
}
]
| 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.Launch(@\"c:\\ApplicationPath.exe\");\n var window = app.GetWindow(\"Window1\");\n var helloButton = window.Get<Button>(\"Hello\");\n Assert.IsNotNull(helloButton);\n helloButton.Click();\n var messageBox = window.MessageBox(\"Howdy\");\n Assert.IsNotNull(messageBox);\n</code></pre>\n"
},
{
"answer_id": 11826654,
"author": "Jeroen de Bekker",
"author_id": 581255,
"author_profile": "https://Stackoverflow.com/users/581255",
"pm_score": 1,
"selected": false,
"text": "<p>Contained in the White source code are some UI tests projects (to test White itself).</p>\n\n<p>One of the test includes MessageBox tests, which includes a way to obtain the displayed message.</p>\n\n<pre><code>[TestFixture, WinFormCategory, WPFCategory]\npublic class MessageBoxTest : ControlsActionTest\n{\n [Test]\n public void CloseMessageBoxTest()\n {\n window.Get<Button>(\"buttonLaunchesMessageBox\").Click();\n Window messageBox = window.MessageBox(\"Close Me\");\n var label = window.Get<Label>(\"65535\");\n Assert.AreEqual(\"Close Me\", label.Text);\n messageBox.Close();\n }\n\n [Test]\n public void ClickButtonOnMessageBox()\n {\n window.Get<Button>(\"buttonLaunchesMessageBox\").Click();\n Window messageBox = window.MessageBox(\"Close Me\");\n messageBox.Get<Button>(SearchCriteria.ByText(\"OK\")).Click();\n }\n}\n</code></pre>\n\n<p>Evidently, the label used to display the text message is owned by the window displaying the messagebox, and its primary identification is the max word value (65535).</p>\n"
},
{
"answer_id": 13670760,
"author": "embarus",
"author_id": 147572,
"author_profile": "https://Stackoverflow.com/users/147572",
"pm_score": 2,
"selected": false,
"text": "<p>Please try this </p>\n\n<pre><code> Window messageBox = window.MessageBox(\"\");\n var label = messageBox.Get<Label>(SearchCriteria.Indexed(0));\n Assert.AreEqual(\"Hello\",label.Text);\n</code></pre>\n"
},
{
"answer_id": 35219222,
"author": "陸普世",
"author_id": 2902212,
"author_profile": "https://Stackoverflow.com/users/2902212",
"pm_score": 1,
"selected": false,
"text": "<p>window.MessageBox() is a good solution!!</p>\n\n<p>But this method would <strong>stuck for a long time</strong> if the messagebox <strong>doesn't appear</strong>. Sometimes I want to check \"<strong>Not Appearance</strong>\" of a messagebox (<em>Warning, Error, etc.</em>). So I write a method to set the timeOut by threading.</p>\n\n<pre><code>[TestMethod]\npublic void TestMethod()\n{\n // arrange\n var app = Application.Launch(@\"c:\\ApplicationPath.exe\");\n var targetWindow = app.GetWindow(\"Window1\");\n Button button = targetWindow.Get<Button>(\"Button\");\n\n // act\n button.Click(); \n\n var actual = GetMessageBox(targetWindow, \"Application Error\", 1000L);\n\n // assert\n Assert.IsNotNull(actual); // I want to see the messagebox appears.\n // Assert.IsNull(actual); // I don't want to see the messagebox apears.\n}\n\nprivate void GetMessageBox(Window targetWindow, string title, long timeOutInMillisecond)\n{\n Window window = null ;\n\n Thread t = new Thread(delegate()\n {\n window = targetWindow.MessageBox(title);\n });\n t.Start();\n\n long l = CurrentTimeMillis();\n while (CurrentTimeMillis() - l <= timeOutInMillsecond) { }\n\n if (window == null)\n t.Abort();\n\n return window;\n}\n\npublic static class DateTimeUtil\n{\n private static DateTime Jan1st1970 = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);\n public static long currentTimeMillis()\n {\n return (long)((DateTime.UtcNow - Jan1st1970).TotalMilliseconds);\n }\n}\n</code></pre>\n"
}
]
| 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 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.</p>\n\n<p>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.</p>\n\n<p>A simpler approach, that can be used for small b/w fonts, is to define the characters directly in code:</p>\n\n<pre><code>LetterA db 01111100b\n db 11000110b\n db 11000110b\n db 11111110b\n db 11000110b\n db 11000110b\n</code></pre>\n\n<p>The XPM file format is actually a file format with C syntax that can be used as a hybrid solution for storing the characters.</p>\n"
},
{
"answer_id": 143846,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>Pre-rendered bitmap fonts are probably the way to go. Render your font using whatever, arrange the characters in a grid, and save the image in a simple uncompressed format like PPM, BMP or TGA. If you want antialiasing, make sure to use a format that supports transparency (BMP and TGA do; PPM does not).</p>\n\n<p>In order to support proportional widths, you'll need to extract the widths of each character from the grid. There's no simple way to do this, it depends on how you generate the grid. You could probably write some short little program to analyze each character and find the minimal bounding box. Once you have the width data, you put it in an auxiliary file which contains the coordinates and sizes of each character.</p>\n\n<p>Finally, to render a string, you look up each character and bitblit its rectangle from the font bitmap onto your frame buffer, advancing the raster position by the width of the character.</p>\n"
},
{
"answer_id": 149113,
"author": "Jeff",
"author_id": 15797,
"author_profile": "https://Stackoverflow.com/users/15797",
"pm_score": 1,
"selected": false,
"text": "<p>We have successfully used the SRGP package for fonts. We did use fixed-pitch fonts, so I'm not sure if it can proportional fonts.</p>\n"
},
{
"answer_id": 528099,
"author": "Richard Fabian",
"author_id": 64122,
"author_profile": "https://Stackoverflow.com/users/64122",
"pm_score": 1,
"selected": false,
"text": "<p>We're using bitmap fonts generated by anglecode#s bitmap font generator :</p>\n\n<p><a href=\"http://www.angelcode.com/products/bmfont/\" rel=\"nofollow noreferrer\">http://www.angelcode.com/products/bmfont/</a></p>\n\n<p>This is very usable as it has XML output which will be easy to convert to any data format you need.</p>\n\n<p>Angel Code's bmfont also adds kerning and better packing to the old alternative that was MudFont.</p>\n"
}
]
| 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 more flexible and can be null. I can't remember if it's legal C++ to force a null reference:</p>\n\n<pre><code>MyType *pObj = nullptr;\nreturn *pObj\n</code></pre>\n\n<p>But I consider this dangerous. Again in Java I'd throw an exception as this is common there, but I rarely see exceptions used so freely in C++.\nIf I was making a puclic API for a reusable C++ component and had to return a reference, I guess I'd go the exception route.\nMy real preference is to have the API return a pointer; I consider pointers an integral part of C++.</p>\n"
},
{
"answer_id": 143762,
"author": "Torbjörn Gyllebring",
"author_id": 21182,
"author_profile": "https://Stackoverflow.com/users/21182",
"pm_score": 0,
"selected": false,
"text": "<p>what I prefer doing in situations like this is having a throwing \"get\" and for those circumstances where performance matter or failiure is common have a \"tryGet\" function along the lines of \"bool tryGet(type key, value **pp)\" whoose contract is that if true is returned then *pp == a valid pointer to some object else *pp is null.</p>\n"
},
{
"answer_id": 143782,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 4,
"selected": false,
"text": "<p>The STL deals with this situation by using iterators. For example, the std::map class has a similar function:</p>\n\n<pre><code>iterator find( const key_type& key );\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 143795,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 1,
"selected": false,
"text": "<p>How about returning a shared_ptr as the result. This can be null if the item wasn't found. It works like a pointer, but it will take care of releasing the object for you.</p>\n"
},
{
"answer_id": 143799,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Don't</strong> use an exception in such a case. C++ has a nontrivial performance overhead for such exceptions, <em>even if no exception is thrown</em>, and it additially makes reasoning about the code much harder (cf. exception safety).</p>\n<p>Best-practice in C++ is one of the two following ways. Both get used in the STL:</p>\n<ul>\n<li>As Martin pointed out, return an iterator. Actually, your iterator can well be a <code>typedef</code> for a simple pointer, there's nothing speaking against it; in fact, since this is consistent with the STL, you could even argue that this way is superior to returning a reference.</li>\n<li>Return a <code>std::pair<bool, yourvalue></code>. This makes it impossible to modify the value, though, since a copycon of the <code>pair</code> is called which doesn't work with referende members.</li>\n</ul>\n<h3>/EDIT:</h3>\n<p>This answer has spawned quite some controversy, visible from the comments and not so visible from the many downvotes it got. I've found this rather surprising.</p>\n<p>This answer was never meant as the ultimate point of reference. The “correct” answer had already been given by Martin: execeptions reflect the behaviour in this case rather poorly. It's semantically more meaningful to use some other signalling mechanism than exceptions.</p>\n<p>Fine. I completely endorse this view. No need to mention it once again. Instead, I wanted to give an additional facet to the answers. While minor speed boosts should never be the first rationale for any decision-making, they can provide further arguments and in some (few) cases, they may even be crucial.</p>\n<p>Actually, I've mentioned two facets: performance and exception safety. I believe the latter to be rather uncontroversial. While it's extremely hard to give strong exceptions guarantees (the strongest, of course, being “nothrow”), I believe it's essential: any code that is guaranteed to not throw exceptions makes the whole program easier to reason about. Many C++ experts emphasize this (e.g. Scott Meyers in item 29 of “Effective C++”).</p>\n<p>About speed. Martin York has pointed out that this no longer applies in modern compilers. I respectfully disagree. The C++ language makes it necessary for the environment to keep track, at runtime, of code paths that may be unwound in the case of an exception. Now, this overhead isn't really all that big (and it's quite easy to verify this). “nontrivial” in my above text may have been too strong.</p>\n<p>However, I find it important to draw the distinction between languages like C++ and many modern, “managed” languages like C#. The latter has <em>no</em> additional overhead as long as no exception is thrown because the information necessary to unwind the stack is kept anyway. By and large, stand by my choice of words.</p>\n"
},
{
"answer_id": 143857,
"author": "Sam Stokes",
"author_id": 20131,
"author_profile": "https://Stackoverflow.com/users/20131",
"pm_score": 3,
"selected": false,
"text": "<p>The problem with exists() is that you'll end up searching twice for things that do exist (first check if it's in there, then find it again). This is inefficient, particularly if (as its name of \"list\" suggests) your container is one where searching is O(n).</p>\n\n<p>Sure, you could do some internal caching to avoid the double search, but then your implementation gets messier, your class becomes less general (since you've optimised for a particular case), and it probably won't be exception-safe or thread-safe.</p>\n"
},
{
"answer_id": 144239,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 2,
"selected": false,
"text": "<h2>STL Iterators?</h2>\n<p>The "iterator" idea proposed before me is interesting, but the real point of iterators is navigation through a container. Not as an simple accessor.</p>\n<p>If you're accessor is one among many, then iterators are the way to go, because you will be able to use them to move in the container. But if your accessor is a simple getter, able to return either <b>the value</b> or the fact there is <b>no value</b>, then your iterator is perhaps only a glorified pointer...</p>\n<p>Which leads us to...</p>\n<h2>Smart pointers?</h2>\n<p>The point of smart pointers is to simplify pointer ownership. With a shared pointer, you'll get a ressource (memory) which will be shared, at the cost of an overhead (shared pointers needs to allocate an integer as a reference counter...).</p>\n<p>You have to choose: Either your Value is already inside a shared pointer, and then, you can return this shared pointer (or a weak pointer). Or Your value is inside a raw pointer. Then you can return the row pointer. <strong>You don't want to return a shared pointer if your ressource is not already inside a shared pointer:</strong> A World of funny things will happen when your shared pointer will get out of scope an delete your Value without telling you...</p>\n<p>:-p</p>\n<h2>Pointers?</h2>\n<p>If your interface is clear about its ownership of its ressources, and by the fact the returned value can be NULL, then you could return a simple, raw pointer. If the user of your code is dumb enough ignore the interface contract of your object, or to play arithmetics or whatever with your pointer, then he/she will be dumb enough to break any other way you'll choose to return the value, so don't bother with the mentally challenged...</p>\n<h2>Undefined Value</h2>\n<p>Unless your Value type really has already some kind of "undefined" value, and the user knows that, and will accept to handle that, it is a possible solution, similar to the pointer or iterator solution.</p>\n<p>But do not add a "undefined" value to your Value class <strong>because</strong> of the problem you asked: You'll end up raising the "references vs. pointer" war to another level of insanity. Code users want the objects you give them to either be Ok, or to not exist. Having to test every other line of code this object is still valid is a pain, and will complexify uselessly the user code, by your fault.</p>\n<h2>Exceptions</h2>\n<p>Exceptions are usually not as costly as some people would like them to be. But for a simple accessor, the cost could be not trivial, if your accessor is used often.</p>\n<p>For example, the STL std::vector has two accessors to its value through an index:</p>\n<pre><code>T & std::vector::operator[]( /* index */ )\n</code></pre>\n<p>and:</p>\n<pre><code>T & std::vector::at( /* index */ )\n</code></pre>\n<p>The difference being that the <b><code>[]</code></b> is <i>non-throwing</i> . So, if you access outside the range of the vector, you're on your own, probably risking memory corruption, and a crash sooner or later. So, you should really be sure you verified the code using it.</p>\n<p>On the other hand, <b><code>at</code></b> is <i>throwing</i>. This means that if you access outside the range of the vector, then you'll get a clean exception. This method is better if you want to delegate to another code the processing of an error.</p>\n<p>I use personnaly the <b><code>[]</code></b> when I'm accessing the values inside a loop, or something similar. I use <b><code>at</code></b> when I feel an exception is the good way to return the current code (or the calling code) the fact something went wrong.</p>\n<h2>So what?</h2>\n<p>In your case, you must choose:</p>\n<p>If you really need a lightning-fast access, then the throwing accessor could be a problem. But this means you already used a profiler on your code to determinate this is a bottleneck, doesn't it?</p>\n<p>;-)</p>\n<p>If you know that not having a value can happen often, and/or you want your client to propagate a possible null/invalid/whatever semantic pointer to the value accessed, then return a pointer (if your value is inside a simple pointer) or a weak/shared pointer (if your value is owned by a shared pointer).</p>\n<p>But if you believe the client won't propagate this "null" value, or that they should not propagate a NULL pointer (or smart pointer) in their code, then use the reference protected by the exception. Add a "hasValue" method returning a boolean, and add a throw should the user try the get the value even if there is none.</p>\n<p>Last but not least, consider the code that will be used by the user of your object:</p>\n<pre><code>// If you want your user to have this kind of code, then choose either\n// pointer or smart pointer solution\nvoid doSomething(MyClass & p_oMyClass)\n{\n MyValue * pValue = p_oMyClass.getValue() ;\n \n if(pValue != NULL)\n {\n // Etc.\n }\n}\n\nMyValue * doSomethingElseAndReturnValue(MyClass & p_oMyClass)\n{\n MyValue * pValue = p_oMyClass.getValue() ;\n \n if(pValue != NULL)\n {\n // Etc.\n }\n\n return pValue ;\n}\n\n// ==========================================================\n\n// If you want your user to have this kind of code, then choose the\n// throwing reference solution\nvoid doSomething(MyClass & p_oMyClass)\n{\n if(p_oMyClass.hasValue())\n {\n MyValue & oValue = p_oMyClass.getValue() ;\n }\n}\n</code></pre>\n<p>So, if your main problem is choosing between the two user codes above, your problem is not about performance, but "code ergonomy". Thus, the exception solution should not be put aside because of potential performance issues.</p>\n<p>:-)</p>\n"
},
{
"answer_id": 144418,
"author": "Edwin Jarvis",
"author_id": 18623,
"author_profile": "https://Stackoverflow.com/users/18623",
"pm_score": 2,
"selected": false,
"text": "<h1>Accessor?</h1>\n\n<blockquote>\n <p>The \"iterator\" idea proposed before me is interesting, but the real point of iterators is navigation through a container. Not as an simple accessor.</p>\n</blockquote>\n\n<p>I agree with <strong>paercebal</strong>, an iterator is to <em>iterate</em>. I don't like the way STL does. But the idea of an accessor seems more appealing. So what we need? A container like class that feels like a boolean for testing but behaves like the original return type. That would be feasible with cast operators.</p>\n\n<pre>\ntemplate <T> class Accessor {\n public:\n Accessor(): _value(NULL) \n {}\n\n Accessor(T &value): _value(&value)\n {}\n\n operator T &() const\n {\n if (!_value)\n throw Exception(\"that is a problem and you made a mistake somewhere.\");\n else\n return *_value;\n }\n\n operator bool () const\n {\n return _value != NULL;\n }\n\n private:\n T *_value;\n};\n</pre>\n\n<p>Now, any foreseeable problem? An example usage:</p>\n\n<pre>\nAccessor <type> value = list.get(key);\n\nif (value) {\n type &v = value;\n\n v.doSomething();\n}\n</pre>\n"
},
{
"answer_id": 144501,
"author": "Roman Odaisky",
"author_id": 21055,
"author_profile": "https://Stackoverflow.com/users/21055",
"pm_score": 3,
"selected": false,
"text": "<p>The correct answer (according to Alexandrescu) is:</p>\n\n<h1><code>Optional</code> and Enforce</h1>\n\n<p>First of all, do use the Accessor, but in a safer way without inventing the wheel:</p>\n\n<pre><code>boost::optional<X> get_X_if_possible();\n</code></pre>\n\n<p>Then create an <code>enforce</code> helper:</p>\n\n<pre><code>template <class T, class E>\nT& enforce(boost::optional<T>& opt, E e = std::runtime_error(\"enforce failed\"))\n{\n if(!opt)\n {\n throw e;\n }\n\n return *opt;\n}\n\n// and an overload for T const &\n</code></pre>\n\n<p>This way, depending on what might the absence of the value mean, you either check explicitly:</p>\n\n<pre><code>if(boost::optional<X> maybe_x = get_X_if_possible())\n{\n X& x = *maybe_x;\n\n // use x\n}\nelse\n{\n oops(\"Hey, we got no x again!\");\n}\n</code></pre>\n\n<p>or implicitly:</p>\n\n<pre><code>X& x = enforce(get_X_if_possible());\n\n// use x\n</code></pre>\n\n<p>You use the first way when you’re concerned about efficiency, or when you want to handle the failure right where it occurs. The second way is for all other cases.</p>\n"
},
{
"answer_id": 144524,
"author": "Aaron",
"author_id": 14153,
"author_profile": "https://Stackoverflow.com/users/14153",
"pm_score": 0,
"selected": false,
"text": "<p>@aradtke, you said.</p>\n\n<blockquote>\n <p>I agree with paercebal, an iterator is\n to iterate. I don't like the way STL\n does. But the idea of an accessor\n seems more appealing. So what we need?\n A container like class that feels like\n a boolean for testing but behaves like\n the original return type. That would\n be feasible with cast operators. [..] Now,\n any foreseeable problem? </p>\n</blockquote>\n\n<p>First, YOU DO NOT WANT OPERATOR bool. See <a href=\"http://www.artima.com/cppsource/safebool2.html\" rel=\"nofollow noreferrer\">Safe Bool idiom</a> for more info. But about your question...</p>\n\n<p>Here's the problem, users need to now explict cast in cases. Pointer-like-<a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"nofollow noreferrer\">proxies</a> (such as iterators, ref-counted-ptrs, and raw pointers) have a concise 'get' syntax. Providing a conversion operator is not very useful if callers have to invoke it with extra code.</p>\n\n<p>Starting with your refence like example, the most concise way to write it:</p>\n\n<pre><code>// 'reference' style, check before use\nif (Accessor<type> value = list.get(key)) {\n type &v = value;\n v.doSomething();\n}\n// or\nif (Accessor<type> value = list.get(key)) {\n static_cast<type&>(value).doSomething();\n}\n</code></pre>\n\n<p>This is okay, don't get me wrong, but it's more verbose than it has to be. now consider if we <em>know</em>, for some reason, that list.get will succeed. Then:</p>\n\n<pre><code>// 'reference' style, skip check \ntype &v = list.get(key);\nv.doSomething();\n// or\nstatic_cast<type&>(list.get(key)).doSomething();\n</code></pre>\n\n<p>Now lets go back to iterator/pointer behavior: </p>\n\n<pre><code>// 'pointer' style, check before use\nif (Accessor<type> value = list.get(key)) {\n value->doSomething();\n}\n\n// 'pointer' style, skip check \nlist.get(key)->doSomething();\n</code></pre>\n\n<p>Both are pretty good, but pointer/iterator syntax is just a bit shorter. You could give 'reference' style a member function 'get()'... but that's already what operator*() and operator->() are for.</p>\n\n<p>The 'pointer' style Accessor now has operator 'unspecified bool', operator*, and operator->. </p>\n\n<p>And guess what... raw pointer meets these requirements, so for prototyping, list.get() returns T* instead of Accessor. Then when the design of list is stable, you can come back and write the Accessor, a pointer-like <a href=\"http://en.wikipedia.org/wiki/Proxy_pattern\" rel=\"nofollow noreferrer\">Proxy</a> type.</p>\n"
},
{
"answer_id": 145238,
"author": "Euro Micelli",
"author_id": 2230,
"author_profile": "https://Stackoverflow.com/users/2230",
"pm_score": 1,
"selected": false,
"text": "<p><em>(I realize this is not always the right answer, and my tone a bit strong, but you <strong>should</strong> consider this question before deciding for other more complex alternatives):</em></p>\n\n<p>So, what's wrong with returning a pointer?</p>\n\n<p>I've seen this one many times in SQL, where people will do their earnest to never deal with NULL columns, like they have some contagious decease or something. Instead, they cleverly come up with a \"blank\" or \"not-there\" artificial value like -1, 9999 or even something like '@X-EMPTY-X@'.</p>\n\n<p>My answer: the language already has a construct for \"not there\"; go ahead, don't be afraid to use it.</p>\n"
}
]
| 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#1028373\" rel=\"nofollow noreferrer\">click()</a> method but for input elements only, not links.</p>\n\n<p>Why don't you just create a function that the button will call on the onClick handler and, whenever you want to 'click' the button call the function instead?</p>\n"
},
{
"answer_id": 143763,
"author": "unexist",
"author_id": 18179,
"author_profile": "https://Stackoverflow.com/users/18179",
"pm_score": 0,
"selected": false,
"text": "<p>Mozilla has a stricter policy for allowed JS actions/events - I had similar problems with the click() event too. It's disabled on some elements to prevent XSS. </p>\n\n<p>What is wrong with redirecting the browser? This sould work everywhere.</p>\n"
},
{
"answer_id": 143771,
"author": "Chris MacDonald",
"author_id": 18146,
"author_profile": "https://Stackoverflow.com/users/18146",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://jehiah.cz/archive/firing-javascript-events-properly\" rel=\"noreferrer\">http://jehiah.cz/archive/firing-javascript-events-properly</a></p>\n\n<pre><code>function fireEvent(element,event) {\n if (document.createEvent) {\n // dispatch for firefox + others\n var evt = document.createEvent(\"HTMLEvents\");\n evt.initEvent(event, true, true ); // event type,bubbling,cancelable\n return !element.dispatchEvent(evt);\n } else {\n // dispatch for IE\n var evt = document.createEventObject();\n return element.fireEvent('on'+event,evt)\n }\n}\n</code></pre>\n"
},
{
"answer_id": 145370,
"author": "Andrew Hedges",
"author_id": 11577,
"author_profile": "https://Stackoverflow.com/users/11577",
"pm_score": 2,
"selected": false,
"text": "<p>I wouldn't recommend it, but you can call the onclick attribute of an HTML element as a method.</p>\n\n<pre><code><a id=\"my-link\" href=\"#\" onclick=\"alert('Hello world');\">My link</a>\n\ndocument.getElementById('my-link').onclick();\n</code></pre>\n"
},
{
"answer_id": 1435344,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Hey, I don't mean to dig up an old thread - but I was searching for an answer to this same problem as well, and found a function new to jQuery 1.3x (I was having a problem with Ajax Loaded content)</p>\n\n<p>Here's how I implemented it:</p>\n\n<p>HTML</p>\n\n<pre><code><a class=\"navlink\" href=\"mypage.html\">Online Estimate</a>\n</code></pre>\n\n<p>LOADED SCRIPT</p>\n\n<pre><code>$(\".pagelink\").click(function(){\n $(\".navlink[href=\"+$(this).attr(\"href\")+\"]\").trigger('click');\n return false;\n});\n</code></pre>\n\n<p>LOADED HTML</p>\n\n<pre><code><a class=\"pagelink\" href=\"mypage.html\">Online Estimate</a>\n</code></pre>\n\n<p>The function is the 'Trigger Event'...<br/>\nMore details on it here:\n<a href=\"http://docs.jquery.com/Events/trigger#eventdata\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Events/trigger#eventdata</a></p>\n"
},
{
"answer_id": 3593165,
"author": "Achshar",
"author_id": 433905,
"author_profile": "https://Stackoverflow.com/users/433905",
"pm_score": -1,
"selected": false,
"text": "<p>i was searching for this one quiet desperately and the simplest one seemed to work!</p>\n\n<pre><code>document.getElementById('foo').onclick();\n</code></pre>\n\n<p>it worked in chrome 7.0.5 and ie 8.0.6</p>\n"
}
]
| 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>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.</p>\n"
},
{
"answer_id": 143787,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 2,
"selected": false,
"text": "<p>Unexist told me in comment to restart the database and it works! Restarting the database kill all existing connection and then I connect to an other database and was able to rename it with my initial query.</p>\n\n<p>Thx all.</p>\n"
},
{
"answer_id": 143852,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": 2,
"selected": false,
"text": "<p>Instead of deploying a nuke (restarting the server) you should try to close those connections that bother you either by finding where are they from and shutting down the client processes or by using the <a href=\"http://www.postgresql.org/docs/current/static/functions-admin.html#FUNCTIONS-ADMIN-SIGNAL-TABLE\" rel=\"nofollow noreferrer\"><code>pg_cancel_backend()</code></a> function.</p>\n"
},
{
"answer_id": 7678959,
"author": "gsiems",
"author_id": 642201,
"author_profile": "https://Stackoverflow.com/users/642201",
"pm_score": 7,
"selected": false,
"text": "<p>For future reference, you should be able to:</p>\n\n<pre><code>-- disconnect from the database to be renamed\n\\c postgres\n\n-- force disconnect all other clients from the database to be renamed\nSELECT pg_terminate_backend( pid )\nFROM pg_stat_activity\nWHERE pid <> pg_backend_pid( )\n AND datname = 'name of database';\n\n-- rename the database (it should now have zero clients)\nALTER DATABASE \"name of database\" RENAME TO \"new name of database\";\n</code></pre>\n\n<p>Note that table <code>pg_stat_activity</code> column <code>pid</code> was named as <code>procpid</code> in versions prior to 9.2. So if your PostgreSQL version is lower than 9.2, use <code>procpid</code> instead of <code>pid</code>.</p>\n"
},
{
"answer_id": 18430601,
"author": "smoore4",
"author_id": 1143681,
"author_profile": "https://Stackoverflow.com/users/1143681",
"pm_score": 3,
"selected": false,
"text": "<p>I just ran into this and below is what worked:</p>\n\n<p>1) <code>pgAdmin</code> is one of the sessions. Use <code>psql</code> instead.<br>\n2) Stop the <code>pgBouncer</code> and/or scheduler services on Windows as these also create sessions</p>\n"
},
{
"answer_id": 60557872,
"author": "rovyko",
"author_id": 3769464,
"author_profile": "https://Stackoverflow.com/users/3769464",
"pm_score": 0,
"selected": false,
"text": "<p>For anyone running into this issue using DBeaver and getting an error message like this:</p>\n\n<pre><code>ERROR: database \"my_stubborn_db\" is being accessed by other users\n Detail: There is 1 other session using the database.\n</code></pre>\n\n<p>Disconnect your current connection, and reconnect to the same server with a connection that doesn't target the database you are renaming.</p>\n\n<p>Changing the active database is not enough.</p>\n"
},
{
"answer_id": 66951818,
"author": "Valsaraj Viswanathan",
"author_id": 2581174,
"author_profile": "https://Stackoverflow.com/users/2581174",
"pm_score": 1,
"selected": false,
"text": "<p>When connected via pgadmin, the default database will be postgres.</p>\n<pre><code>ALTER DATABASE postgres RENAME TO pgnew;\n</code></pre>\n<p>This will not work.</p>\n<p>You need to right click on server in pgadmin and set Maintenance DB to some other DB and save. Then retry and it should work if no other connections exists.</p>\n"
}
]
| 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/trunk/\n/repo/tags/1.1\n/repo/tags/1.2\n/repo/tags/1.3\n</code></pre>\n<p>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.</p>\n<p>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.</p>\n<p>Now whenever we need to <em>hotfix</em> an issue, we fix it in <code>tags/x</code> first and then we <code>svn update</code> 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.</p>\n<p>The only thing to remember is to apply all patches from <code>tags/x</code> to <code>trunk</code>.</p>\n<p>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.</p>\n"
},
{
"answer_id": 143877,
"author": "Ben Hoffstein",
"author_id": 4482,
"author_profile": "https://Stackoverflow.com/users/4482",
"pm_score": 1,
"selected": false,
"text": "<p>One strategy is to heavily use declarative-style external configuration files for the different components. </p>\n\n<p>Examples of this:</p>\n\n<ul>\n<li>Database access/object-relational mapping via a tool like <a href=\"http://ibatis.apache.org/\" rel=\"nofollow noreferrer\">IBatis/IBatis.NET</a></li>\n<li>Logging via a tool like <a href=\"http://jlog.org/\" rel=\"nofollow noreferrer\">JLog</a>/<a href=\"http://www.nlog-project.org/\" rel=\"nofollow noreferrer\">NLog</a></li>\n<li>Dependency injection via a tool like <a href=\"http://www.springframework.org/\" rel=\"nofollow noreferrer\">Spring</a>/<a href=\"http://www.springframework.net/\" rel=\"nofollow noreferrer\">Spring.NET</a></li>\n</ul>\n\n<p>In this way, you can often keep key components separated into discrete parts, hotfix a running application without recompile, and seamlessly use source control (particularly in comparison to stored procedures, which usually require manual effort to source control).</p>\n"
},
{
"answer_id": 143929,
"author": "Kalpesh Patel",
"author_id": 23003,
"author_profile": "https://Stackoverflow.com/users/23003",
"pm_score": -1,
"selected": false,
"text": "<p>We divide our code in framework code and business customizations. Business customization classes are loaded using a separate classloader and we have tool to submit changes to a running instance of production. whenever we need a change in any class we change it and submit it to a running instance. the running instance will reject the old classloader and use a new classloader insance to load the classes again. This is similar to Jboss hot deploy of EJBs.</p>\n"
}
]
| 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.offsetHeight</code> / <code>element.offsetWidth</code></p>\n\n<p><a href=\"http://developer.mozilla.org/en/DOM/element.offsetWidth\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/element.offsetWidth</a><br>\n<a href=\"http://developer.mozilla.org/en/DOM/element.offsetHeight\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/element.offsetHeight</a><br>\n<a href=\"http://developer.mozilla.org/en/DOM/element.scrollWidth\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/element.scrollWidth</a><br>\n<a href=\"http://developer.mozilla.org/en/DOM/element.scrollHeight\" rel=\"noreferrer\">http://developer.mozilla.org/en/DOM/element.scrollHeight</a></p>\n"
},
{
"answer_id": 143889,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 9,
"selected": true,
"text": "<p>Normally, you can compare the <code>client[Height|Width]</code> with <code>scroll[Height|Width]</code> in order to detect this... but the values will be the same when overflow is visible. So, a detection routine must account for this:</p>\n\n<pre><code>// Determines if the passed element is overflowing its bounds,\n// either vertically or horizontally.\n// Will temporarily modify the \"overflow\" style to detect this\n// if necessary.\nfunction checkOverflow(el)\n{\n var curOverflow = el.style.overflow;\n\n if ( !curOverflow || curOverflow === \"visible\" )\n el.style.overflow = \"hidden\";\n\n var isOverflowing = el.clientWidth < el.scrollWidth \n || el.clientHeight < el.scrollHeight;\n\n el.style.overflow = curOverflow;\n\n return isOverflowing;\n}\n</code></pre>\n\n<p>Tested in FF3, FF40.0.2, IE6, Chrome 0.2.149.30.</p>\n"
},
{
"answer_id": 29689110,
"author": "zjalex",
"author_id": 1386591,
"author_profile": "https://Stackoverflow.com/users/1386591",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think this answer is perfect. Sometimes the scrollWidth/clientWidth/offsetWidth are the same even though the text is overflow.</p>\n\n<p>This works well in Chrome, but not in IE and Firefox.</p>\n\n<p>At last, I tried this answer: <a href=\"https://stackoverflow.com/questions/7738117/html-text-overflow-ellipsis-detection\">HTML text-overflow ellipsis detection</a></p>\n\n<p>It's perfect and works well anywhere. So I choose this, maybe you can try, you won't disappoint. </p>\n"
},
{
"answer_id": 37425662,
"author": "Paul V",
"author_id": 945389,
"author_profile": "https://Stackoverflow.com/users/945389",
"pm_score": -1,
"selected": false,
"text": "<p>This is a javascript solution (with Mootools) that will reduce the font size to fit the bounds of elHeader. </p>\n\n<pre><code>while (elHeader.clientWidth < elHeader.scrollWidth || elHeader.clientHeight < elHeader.scrollHeight) {\n var f = parseInt(elHeader.getStyle('font-size'), 10);\n f--;\n elHeader.setStyle('font-size', f + 'px');\n}\n</code></pre>\n\n<p>The CSS of elHeader:</p>\n\n<pre><code> width:100%;\n font-size:40px;\n line-height:36px;\n font-family:Arial;\n text-align:center;\n max-height:36px;\n overflow:hidden;\n</code></pre>\n\n<p>Note the wrapper of elHeader sets the width of elHeader.</p>\n"
},
{
"answer_id": 56464302,
"author": "Agu Dondo",
"author_id": 936703,
"author_profile": "https://Stackoverflow.com/users/936703",
"pm_score": 1,
"selected": false,
"text": "<p>With jQuery you could do:</p>\n\n<pre><code>if ( $(\".inner-element\").prop('scrollHeight') > $(\".inner-element\").height() ) {\n\n console.log(\"element is overflowing\");\n\n} else {\n\n console.log(\"element is not overflowing\");\n\n}\n</code></pre>\n\n<p>Change to <code>.prop('scrollWidth')</code> and <code>.width()</code> if needed.</p>\n"
},
{
"answer_id": 62272697,
"author": "Alisson Nunes",
"author_id": 4718937,
"author_profile": "https://Stackoverflow.com/users/4718937",
"pm_score": 3,
"selected": false,
"text": "<p>Another way is compare the element width with its parent's width:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>function checkOverflow(elem) {\n const elemWidth = elem.getBoundingClientRect().width\n const parentWidth = elem.parentElement.getBoundingClientRect().width\n\n return elemWidth > parentWidth\n}\n</code></pre>\n"
}
]
| 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 c\nend\n</code></pre>\n\n<p>yields</p>\n\n<pre><code>115\n116\n114\n105\n110\n103\n</code></pre>\n"
},
{
"answer_id": 1557734,
"author": "Mark",
"author_id": 137100,
"author_profile": "https://Stackoverflow.com/users/137100",
"pm_score": 2,
"selected": false,
"text": "<pre><code>\"a\"[0]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>?a\n</code></pre>\n\n<p>Both would return their ASCII equivalent.</p>\n"
},
{
"answer_id": 2370125,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>please refer to this post for the changes in ruby1.9 <a href=\"https://stackoverflow.com/questions/1270209/getting-an-ascii-character-code-in-ruby-fails\">Getting an ASCII character code in Ruby using `?` (question mark) fails</a></p>\n"
},
{
"answer_id": 9774098,
"author": "alexsuslin",
"author_id": 1167345,
"author_profile": "https://Stackoverflow.com/users/1167345",
"pm_score": 5,
"selected": false,
"text": "<pre><code>puts \"string\".split('').map(&:ord).to_s\n</code></pre>\n"
},
{
"answer_id": 20599087,
"author": "Sh.K",
"author_id": 3105218,
"author_profile": "https://Stackoverflow.com/users/3105218",
"pm_score": 4,
"selected": false,
"text": "<p>use \"x\".ord for a single character or \"xyz\".sum for a whole string. </p>\n"
},
{
"answer_id": 31591016,
"author": "LastZactionHero",
"author_id": 1895150,
"author_profile": "https://Stackoverflow.com/users/1895150",
"pm_score": 4,
"selected": false,
"text": "<p>Ruby String provides the <code>codepoints</code> method after 1.9.1.</p>\n<pre><code>str = 'hello world'\nstr.codepoints\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] \n\nstr = "你好世界"\nstr.codepoints\n=> [20320, 22909, 19990, 30028]\n</code></pre>\n"
},
{
"answer_id": 33700454,
"author": "nikkypx",
"author_id": 1395009,
"author_profile": "https://Stackoverflow.com/users/1395009",
"pm_score": 3,
"selected": false,
"text": "<p>You could also just call to_a after each_byte or even better String#bytes</p>\n\n<pre><code>=> 'hello world'.each_byte.to_a\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n\n=> 'hello world'.bytes\n=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]\n</code></pre>\n"
}
]
| 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/Global_Objects/Array/includes\" rel=\"noreferrer\"><code>includes()</code></a></p>\n<pre><code>arr.includes(obj);\n</code></pre>\n<p>If you want to support IE or other older browsers:</p>\n<pre><code>function include(arr,obj) {\n return (arr.indexOf(obj) != -1);\n}\n</code></pre>\n<p>EDIT:\nThis will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:</p>\n<ol>\n<li><p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf\" rel=\"noreferrer\">Mozilla's</a> (ECMA-262) version:</p>\n<pre><code> if (!Array.prototype.indexOf)\n {\n\n Array.prototype.indexOf = function(searchElement /*, fromIndex */)\n\n {\n\n\n "use strict";\n\n if (this === void 0 || this === null)\n throw new TypeError();\n\n var t = Object(this);\n var len = t.length >>> 0;\n if (len === 0)\n return -1;\n\n var n = 0;\n if (arguments.length > 0)\n {\n n = Number(arguments[1]);\n if (n !== n)\n n = 0;\n else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))\n n = (n > 0 || -1) * Math.floor(Math.abs(n));\n }\n\n if (n >= len)\n return -1;\n\n var k = n >= 0\n ? n\n : Math.max(len - Math.abs(n), 0);\n\n for (; k < len; k++)\n {\n if (k in t && t[k] === searchElement)\n return k;\n }\n return -1;\n };\n\n }\n</code></pre>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144172\">Daniel James</a>'s version:</p>\n<pre><code> if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (obj, fromIndex) {\n if (fromIndex == null) {\n fromIndex = 0;\n } else if (fromIndex < 0) {\n fromIndex = Math.max(0, this.length + fromIndex);\n }\n for (var i = fromIndex, j = this.length; i < j; i++) {\n if (this[i] === obj)\n return i;\n }\n return -1;\n };\n }\n</code></pre>\n</li>\n<li><p><a href=\"https://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array#144664\">roosteronacid</a>'s version:</p>\n<pre><code> Array.prototype.hasObject = (\n !Array.indexOf ? function (o)\n {\n var l = this.length + 1;\n while (l -= 1)\n {\n if (this[l - 1] === o)\n {\n return true;\n }\n }\n return false;\n } : function (o)\n {\n return (this.indexOf(o) !== -1);\n }\n );\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 143873,
"author": "assortedslog",
"author_id": 20472,
"author_profile": "https://Stackoverflow.com/users/20472",
"pm_score": 4,
"selected": false,
"text": "<p>If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:</p>\n\n<ol>\n<li>Pick the middle element of the array.</li>\n<li>Is the element you're looking for bigger than the element you picked? If so, you've eliminated the bottom half of the array. If it isn't, you've eliminated the top half.</li>\n<li>Pick the middle element of the remaining half of the array, and continue as in step 2, eliminating halves of the remaining array. Eventually you'll either find your element or have no array left to look through.</li>\n</ol>\n\n<p>Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.</p>\n"
},
{
"answer_id": 143879,
"author": "Paul Dixon",
"author_id": 6521,
"author_profile": "https://Stackoverflow.com/users/6521",
"pm_score": 3,
"selected": false,
"text": "<p>Here's some meta-knowledge for you - if you want to know what you can do with an Array, check the documentation - here's the Array page for Mozilla</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array</a></p>\n\n<p>There you'll see reference to indexOf, added in Javascript 1.6</p>\n"
},
{
"answer_id": 143945,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 3,
"selected": false,
"text": "<p>It depends on your purpose. If you program for the Web, avoid <code>indexOf</code>, it isn't supported by Internet Explorer 6 (lot of them still used!), or do conditional use:</p>\n\n<pre><code>if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);\nelse result = customSlowerSearch(yourArray, target);\n</code></pre>\n\n<p><code>indexOf</code> is probably coded in native code, so it is faster than anything you can do in JavaScript (except binary search/dichotomy if the array is appropriate).\nNote: it is a question of taste, but I would do a <code>return false;</code> at the end of your routine, to return a true Boolean...</p>\n"
},
{
"answer_id": 144172,
"author": "Daniel James",
"author_id": 2434,
"author_profile": "https://Stackoverflow.com/users/2434",
"pm_score": 5,
"selected": false,
"text": "<p>First, implement <code>indexOf</code> in JavaScript for browsers that don't already have it. For example, see <a href=\"http://erik.eae.net/playground/arrayextras/arrayextras.js\" rel=\"noreferrer\">Erik Arvidsson's array extras</a> (also, the <a href=\"http://erik.eae.net/archives/2005/06/05/17.53.19/\" rel=\"noreferrer\">associated blog post</a>). And then you can use <code>indexOf</code> without worrying about browser support. Here's a slightly optimised version of his <code>indexOf</code> implementation:</p>\n\n<pre><code>if (!Array.prototype.indexOf) {\n Array.prototype.indexOf = function (obj, fromIndex) {\n if (fromIndex == null) {\n fromIndex = 0;\n } else if (fromIndex < 0) {\n fromIndex = Math.max(0, this.length + fromIndex);\n }\n for (var i = fromIndex, j = this.length; i < j; i++) {\n if (this[i] === obj)\n return i;\n }\n return -1;\n };\n}\n</code></pre>\n\n<p>It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:</p>\n\n<pre><code>var include = Array.prototype.indexOf ?\n function(arr, obj) { return arr.indexOf(obj) !== -1; } :\n function(arr, obj) {\n for(var i = -1, j = arr.length; ++i < j;)\n if(arr[i] === obj) return true;\n return false;\n };\n</code></pre>\n\n<p>I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the <a href=\"https://blogs.oracle.com/greimer/resource/loop-test.html\" rel=\"noreferrer\">benchmarks</a> that roosterononacid linked to in the comments, to <a href=\"http://obscurity.nfshost.com/x/bench.html\" rel=\"noreferrer\">benchmark searching in arrays</a>. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.</p>\n"
},
{
"answer_id": 2527680,
"author": "Germán Rodríguez",
"author_id": 56748,
"author_profile": "https://Stackoverflow.com/users/56748",
"pm_score": 8,
"selected": false,
"text": "<p>If you are using jQuery: </p>\n\n<pre><code>$.inArray(5 + 5, [ \"8\", \"9\", \"10\", 10 + \"\" ]);\n</code></pre>\n\n<p>For more information: <a href=\"http://api.jquery.com/jQuery.inArray/\" rel=\"noreferrer\">http://api.jquery.com/jQuery.inArray/</a></p>\n"
},
{
"answer_id": 7093224,
"author": "Aaria Carter-Weir",
"author_id": 647351,
"author_profile": "https://Stackoverflow.com/users/647351",
"pm_score": 3,
"selected": false,
"text": "<p>A robust way to check if an object is an array in javascript is detailed here:</p>\n\n<p>Here are two functions from the <a href=\"http://xajs.chalmershouse.com\" rel=\"noreferrer\">xa.js</a> framework which I attach to a <code>utils = {}</code> ‘container’. These should help you properly detect arrays.</p>\n\n<pre><code>var utils = {};\n\n/**\n * utils.isArray\n *\n * Best guess if object is an array.\n */\nutils.isArray = function(obj) {\n // do an instanceof check first\n if (obj instanceof Array) {\n return true;\n }\n // then check for obvious falses\n if (typeof obj !== 'object') {\n return false;\n }\n if (utils.type(obj) === 'array') {\n return true;\n }\n return false;\n };\n\n/**\n * utils.type\n *\n * Attempt to ascertain actual object type.\n */\nutils.type = function(obj) {\n if (obj === null || typeof obj === 'undefined') {\n return String (obj);\n }\n return Object.prototype.toString.call(obj)\n .replace(/\\[object ([a-zA-Z]+)\\]/, '$1').toLowerCase();\n};\n</code></pre>\n\n<p>If you then want to check if an object is in an array, I would also include this code:</p>\n\n<pre><code>/**\n * Adding hasOwnProperty method if needed.\n */\nif (typeof Object.prototype.hasOwnProperty !== 'function') {\n Object.prototype.hasOwnProperty = function (prop) {\n var type = utils.type(this);\n type = type.charAt(0).toUpperCase() + type.substr(1);\n return this[prop] !== undefined\n && this[prop] !== window[type].prototype[prop];\n };\n}\n</code></pre>\n\n<p>And finally this in_array function:</p>\n\n<pre><code>function in_array (needle, haystack, strict) {\n var key;\n\n if (strict) {\n for (key in haystack) {\n if (!haystack.hasOwnProperty[key]) continue;\n\n if (haystack[key] === needle) {\n return true;\n }\n }\n } else {\n for (key in haystack) {\n if (!haystack.hasOwnProperty[key]) continue;\n\n if (haystack[key] == needle) {\n return true;\n }\n }\n }\n\n return false;\n}\n</code></pre>\n"
},
{
"answer_id": 9435838,
"author": "bortunac",
"author_id": 544803,
"author_profile": "https://Stackoverflow.com/users/544803",
"pm_score": 3,
"selected": false,
"text": "<p><strong>[ ].has(obj)</strong></p>\n\n<p>assuming <code>.indexOf()</code> is implemented </p>\n\n<pre><code>Object.defineProperty( Array.prototype,'has',\n{\n value:function(o, flag){\n if (flag === undefined) {\n return this.indexOf(o) !== -1;\n } else { // only for raw js object\n for(var v in this) {\n if( JSON.stringify(this[v]) === JSON.stringify(o)) return true;\n }\n return false; \n },\n // writable:false,\n // enumerable:false\n})\n</code></pre>\n\n<p>!!! do not make <code>Array.prototype.has=function(){...</code> because you'll add an enumerable element in every array and js is broken.</p>\n\n<pre><code>//use like \n[22 ,'a', {prop:'x'}].has(12) // false\n[\"a\",\"b\"].has(\"a\") // true\n\n[1,{a:1}].has({a:1},1) // true\n[1,{a:1}].has({a:1}) // false\n</code></pre>\n\n<p>the use of 2nd arg (flag) forces comparation by value instead of reference </p>\n\n<p>comparing raw objects </p>\n\n<pre><code>[o1].has(o2,true) // true if every level value is same\n</code></pre>\n"
}
]
| 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 copy of <code>i</code>.</p>\n"
},
{
"answer_id": 143860,
"author": "jmatthias",
"author_id": 2768,
"author_profile": "https://Stackoverflow.com/users/2768",
"pm_score": 0,
"selected": false,
"text": "<p>Since i is a local variable it is stored on the thread's own private stack. Hence, you do not need to protect i with a critical section.</p>\n"
},
{
"answer_id": 143867,
"author": "Alaric",
"author_id": 19744,
"author_profile": "https://Stackoverflow.com/users/19744",
"pm_score": 0,
"selected": false,
"text": "<p>As Adam said, i is a variable stored on the stack and the arguments are passed in so this is safe. When you have to be careful and apply mutexes or other synchronization mechanisms is if you were accessing shared member variables in the same instance of the class or global variables in the program (even scoped statics).</p>\n"
},
{
"answer_id": 143960,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 2,
"selected": false,
"text": "<p>Be careful. In the example provided the method <strong>processArray</strong> seems to be <em>reentrant</em> (it's not clear what happens in <em>// do something with values in the array</em>). If so, no race occurs while two or more threads invoke it simultaneously and therefore it's safe to call it without any locking mechanism. \nTo enforce this, you could mark both the instance and the method with the <strong>volatile</strong> qualifier, to let users know that no lock is required.\nIt has been published an interesting article of Andrei Alexandrescu about <em>volatile qualifier</em> and how it can be used to write correct multithreaded classes. The article is published here: \n<a href=\"http://www.ddj.com/cpp/184403766\" rel=\"nofollow noreferrer\">http://www.ddj.com/cpp/184403766</a></p>\n"
}
]
| 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=\"-e \\\"should log in with cookie\\\"\"\n</pre>\n\n<p>Now figure out how to embed this into your editor.</p>\n"
},
{
"answer_id": 144063,
"author": "Cameron Booth",
"author_id": 14873,
"author_profile": "https://Stackoverflow.com/users/14873",
"pm_score": 10,
"selected": true,
"text": "<p>Or you can skip rake and use the 'rspec' command:</p>\n<pre><code>bundle exec rspec path/to/spec/file.rb\n</code></pre>\n<p>In your case I think as long as your ./spec/db_spec.rb file includes the appropriate helpers, it should work fine.</p>\n<p>If you're using an older version of rspec it is:</p>\n<pre><code>bundle exec spec path/to/spec/file.rb\n</code></pre>\n"
},
{
"answer_id": 146612,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 4,
"selected": false,
"text": "<p>If you installed rspec as a plugin rather than as a gem, then you won't have the <code>spec</code> executable.</p>\n\n<p>At any rate, All you need to do is run the file using ruby. The rspec code is clever enough to run the tests for you.</p>\n\n<p>eg:</p>\n\n<pre><code>ruby myclass_spec.rb\n</code></pre>\n"
},
{
"answer_id": 166049,
"author": "fatgeekuk",
"author_id": 17518,
"author_profile": "https://Stackoverflow.com/users/17518",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively, have a look at autotest.</p>\n\n<p>Running autotest in a command window will mean that the spec file will be executed whenever you save it. Also, it will be run whenever the file you are speccing is run.</p>\n\n<p>For instance, if you have a model spec file called person_spec.rb, and a model file that it is speccing called person.rb, then whenever you save either of these files from your editor, the spec file will be executed.</p>\n"
},
{
"answer_id": 432460,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>specky.vim</p>\n"
},
{
"answer_id": 1909419,
"author": "Zeke",
"author_id": 95670,
"author_profile": "https://Stackoverflow.com/users/95670",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://github.com/grosser/single_test\" rel=\"noreferrer\">http://github.com/grosser/single_test</a> lets you do stuff like..</p>\n\n<pre><code>rake spec:user #run spec/model/user_spec.rb (searches for user*_spec.rb)\nrake test:users_c #run test/functional/users_controller_test.rb\nrake spec:user:token #run the first spec in user_spec.rb that matches /token/\nrake test:user:token #run all tests in user_test.rb that match /token/\nrake test:last\nrake spec:last\n</code></pre>\n"
},
{
"answer_id": 3501347,
"author": "boblin",
"author_id": 2190153,
"author_profile": "https://Stackoverflow.com/users/2190153",
"pm_score": 4,
"selected": false,
"text": "<p>from help (spec -h):</p>\n\n<pre><code>-l, --line LINE_NUMBER Execute example group or example at given line.\n (does not work for dynamically generated examples)\n</code></pre>\n\n<p>Example: spec spec/runner_spec.rb -l 162</p>\n"
},
{
"answer_id": 5157821,
"author": "Greg Hemphill",
"author_id": 141983,
"author_profile": "https://Stackoverflow.com/users/141983",
"pm_score": 3,
"selected": false,
"text": "<p>I was having trouble getting any of these examples to work, maybe because the post is old and the commands have changed?</p>\n\n<p>After some poking around I found this works:</p>\n\n<p>rspec spec/models/user_spec.rb</p>\n\n<p>That will run just the single file and provides useful output in the terminal.</p>\n"
},
{
"answer_id": 5658081,
"author": "joelparkerhenderson",
"author_id": 528726,
"author_profile": "https://Stackoverflow.com/users/528726",
"pm_score": 3,
"selected": false,
"text": "<p>Ruby 1.9.2 and Rails 3 have an easy way to run one spec file:</p>\n\n<pre>\n ruby -I spec spec/models/user_spec.rb\n</pre>\n\n<p>Explanation:</p>\n\n<ul>\n<li><code>ruby</code> command tends to be faster than the <code>rake</code> command\n<li><code>-I spec</code> means \"include the 'spec' directory when looking for files\"\n<li><code>spec/models/user_spec.rb</code> is the file we want to run.\n</ul>\n"
},
{
"answer_id": 5679783,
"author": "tcurdt",
"author_id": 33165,
"author_profile": "https://Stackoverflow.com/users/33165",
"pm_score": 6,
"selected": false,
"text": "<p>You can also use the actual text of the *e*xample test case with <code>-e</code> !</p>\n\n<p>So for:</p>\n\n<pre><code>it \"shows the plane arrival time\"\n</code></pre>\n\n<p>you can use</p>\n\n<pre><code>rspec path/to/spec/file.rb -e 'shows the plane arrival time'\n./scripts/spec path/to/spec/file.rb -e 'shows the plane arrival time'\n</code></pre>\n\n<p>no need for rake here.</p>\n"
},
{
"answer_id": 11639611,
"author": "juanpaco",
"author_id": 322418,
"author_profile": "https://Stackoverflow.com/users/322418",
"pm_score": 7,
"selected": false,
"text": "<p>This question is an old one, but it shows up at the top of Google when searching for how to run a single test. I don't know if it's a recent addition, but to run a single test out of a spec you can do the following:</p>\n\n<pre><code>rspec path/to/spec:<line number>\n</code></pre>\n\n<p>where -line number- is a line number that contains part of your test. For example, if you had a spec like:</p>\n\n<pre><code>1: \n2: it \"should be awesome\" do\n3: foo = 3\n4: foo.should eq(3)\n5: end\n6:\n</code></pre>\n\n<p>Let's say it's saved in spec/models/foo_spec.rb. Then you would run:</p>\n\n<pre><code>rspec spec/models/foo_spec.rb:2\n</code></pre>\n\n<p>and it would just run that one spec. In fact, that number could be anything from 2 to 5.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 27356175,
"author": "Prabhakar Undurthi",
"author_id": 2200417,
"author_profile": "https://Stackoverflow.com/users/2200417",
"pm_score": 2,
"selected": false,
"text": "<p>Lets say, you're running test for creating todo. You can always run that specific todo spec code using the file crete_spec.rb file as below.</p>\n\n<pre><code> rspec/spec/features/controller/spec_file_name.rb\n\n Example:\n\n Creating rspec spec/features/todos/create_spec.rb\n Editing rspec spec/features/todos/edit_spec.rb\n Deleting rspec spec/features/todos/destroy_spec.rb\n</code></pre>\n\n<p>If you want to run all the specs in one single short.</p>\n\n<pre><code> rspec \n</code></pre>\n\n<p>If you want to run all the specs in a specific controller user this.</p>\n\n<pre><code> rspec/spec/feaures/controller_name\n\n Example: rspec/spec/features/todos\n</code></pre>\n\n<p>Hope it gives you more understanding!</p>\n"
},
{
"answer_id": 43983110,
"author": "Victor BV",
"author_id": 2930272,
"author_profile": "https://Stackoverflow.com/users/2930272",
"pm_score": 3,
"selected": false,
"text": "<p>Although many great answers were written to this question, none of them uses the <a href=\"https://relishapp.com/rspec/rspec-core/v/2-4/docs/command-line/tag-option\" rel=\"noreferrer\">Rspec <code>tags</code></a> approach. </p>\n\n<p>I use tags to run one or more specs in different files -- only those related to my current development task.</p>\n\n<p>For example, I add the tag \"dev\" with the value \"current\":</p>\n\n<pre><code>it \"creates an user\", dev: :current do\n user = create(:user)\n expect(user.persisted?).to be_truthy\nend\n</code></pre>\n\n<p>then I run</p>\n\n<pre><code>bundle exec rspec . --tag dev:current\n</code></pre>\n\n<p>Different tags/values can be set in individual specs or groups.</p>\n"
},
{
"answer_id": 47064184,
"author": "nflauria",
"author_id": 5656846,
"author_profile": "https://Stackoverflow.com/users/5656846",
"pm_score": 4,
"selected": false,
"text": "<p>To run <strong>all</strong> of your rspec files: <code>rspec</code></p>\n\n<p><em>note: you must be in the root of your project</em> </p>\n\n<p>To run <strong>one</strong> rspec file: <code>rspec 'path_to/spec.rb'</code></p>\n\n<p><em>note: replace 'path_to/spec.rb' with your path. Quotation marks optional.</em></p>\n\n<p>To run <strong>one</strong> rspec <strong>test</strong> from one file: <code>rspec 'path_to/spec.rb:7'</code></p>\n\n<p><em>note: :7 is the line number where the test starts</em></p>\n"
},
{
"answer_id": 70170831,
"author": "Khaireddine Hamdi",
"author_id": 6430324,
"author_profile": "https://Stackoverflow.com/users/6430324",
"pm_score": -1,
"selected": false,
"text": "<p>And you can run specific line into your test file</p>\n<pre><code>rspec spec/models/model_spec.rb:47\n</code></pre>\n"
}
]
| 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 you're using MySQL. Its always a bit dangerous opening up an application like that if the db is intended to live behind a firewall, but as you say you could set it up ith a read-only account and possibly add extra layers of security on top like simple HTTP Basic auth.</p>\n"
},
{
"answer_id": 143981,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n"
},
{
"answer_id": 145082,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 0,
"selected": false,
"text": "<p>On my current project, we use <a href=\"http://www.quest.com/sql-navigator/\" rel=\"nofollow noreferrer\">SQL Navigator</a> in order to run queries on our Oracle database. I've also heard decent things about <a href=\"http://www.toadsoft.com/toad_oracle.htm\" rel=\"nofollow noreferrer\">TOAD</a>. I would advise against writing a web application just to run ad hoc SQL queries, because it seems to me that plenty of tools can support your debugging needs.</p>\n"
},
{
"answer_id": 145097,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://www.oracletool.com/\" rel=\"nofollow noreferrer\">Oracle Tool</a> is a pretty decent oracle web front end. But so is enterprise manager.</p>\n\n<p>Either way, you don't want your database open to the outside world in any way, either via some website or a listener or anything really. </p>\n\n<p>The VPN solution is the way to go, just get VPN and then you can use whatever tools you normally use, if VPN is not an option then a simple firewall rule allowing just your IP's access would be ok, but not quite as nice as VPN.</p>\n"
}
]
| 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, which means O(n).</p>\n\n<p>It seems like a classic case in which the language designers decided to trade performance for generality.</p>\n"
},
{
"answer_id": 144085,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n\n<p>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 :)</p>\n\n<p>To examine the predicate, you'd have to use expression trees instead of delegates, and life would become a lot harder.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 144089,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, the generic case is always O(n), as Sklivvz said.</p>\n\n<p>However, many LINQ methods special case for when the object implementing IEnumerable actually implements e.g. ICollection. (I've seen this for IEnumerable.Contains at least.)</p>\n\n<p>In practice this means that LINQ IEnumerable.Contains calls the fast HashSet.Contains for example if the IEnumerable actually is a HashSet.</p>\n\n<pre><code>IEnumerable<int> mySet = new HashSet<int>();\n\n// calls the fast HashSet.Contains because HashSet implements ICollection.\nif (mySet.Contains(10)) { /* code */ }\n</code></pre>\n\n<p>You can use reflector to check exactly how the LINQ methods are defined, that is how I figured this out.</p>\n\n<p>Oh, and also LINQ contains methods IEnumerable.ToDictionary (maps key to single value) and IEnumerable.ToLookup (maps key to multiple values). This dictionary/lookup table can be created once and used many times, which can speed up some LINQ-intensive code by orders of magnitude.</p>\n"
}
]
| 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 is a more explicit call to a function that converts. They probably go about doing the same thing in different ways.</p>\n"
},
{
"answer_id": 144006,
"author": "Sklivvz",
"author_id": 7028,
"author_profile": "https://Stackoverflow.com/users/7028",
"pm_score": 5,
"selected": false,
"text": "<p>Absolutely not!</p>\n\n<p>Convert tries to get you an Int32 via \"any means possible\". Cast does nothing of the sort. With cast you are telling the compiler to treat the object as Int, without conversion.</p>\n\n<p>You should always use cast when you know (by design) that the object is an Int32 or another class that has an casting operator to Int32 (like float, for example).</p>\n\n<p>Convert should be used with String, or with other classes.</p>\n\n<p>Try this</p>\n\n<pre><code>static void Main(string[] args)\n{\n long l = long.MaxValue;\n\n Console.WriteLine(l);\n\n byte b = (byte) l;\n\n Console.WriteLine(b);\n\n b = Convert.ToByte(l);\n\n Console.WriteLine(b);\n\n}\n</code></pre>\n\n<p>Result:</p>\n\n<blockquote>\n <p>9223372036854775807 </p>\n \n <p>255 </p>\n \n <p>Unhandled Exception: </p>\n \n <p>System.OverflowException: Value is\n greater than Byte.MaxValue or less\n than Byte.MinValue at\n System.Convert.ToByte (Int64 value)\n [0x00000] at Test.Main\n (System.String[] args) [0x00019] in\n /home/marco/develop/test/Exceptions.cs:15</p>\n</blockquote>\n"
},
{
"answer_id": 144008,
"author": "Per Hornshøj-Schierbeck",
"author_id": 11619,
"author_profile": "https://Stackoverflow.com/users/11619",
"pm_score": 0,
"selected": false,
"text": "<p>A cast is telling the compiler/interperter that the object in fact is of that type (or has a basetype/interface of that type). It's a pretty fast thing to do compared to a convert where it's no longer the compiler/interperter doing the job but a function actualling parsing a string and doing math to convert to a number.</p>\n"
},
{
"answer_id": 144010,
"author": "OregonGhost",
"author_id": 20363,
"author_profile": "https://Stackoverflow.com/users/20363",
"pm_score": 0,
"selected": false,
"text": "<p>Casting always means changing the data type of an object. This can be done for instance by converting a float value into an integer value, or by reinterpreting the bits. It is usally a language-supported (read: compiler-supported) operation.</p>\n\n<p>The term \"converting\" is sometimes used for casting, but it is usually done by some library or your own code and does not necessarily result in the same as casting. For example, if you have an imperial weight value and convert it to metric weight, it may stay the same data type (say, float), but become a different number. Another typical example is converting from degrees to radian.</p>\n"
},
{
"answer_id": 144020,
"author": "Wayne Bloss",
"author_id": 16387,
"author_profile": "https://Stackoverflow.com/users/16387",
"pm_score": 3,
"selected": false,
"text": "<p>The best explanation that I've seen can be seen below, followed by a link to the source:</p>\n\n<p>\"... The truth is a bit more complex than that. .NET provides\nthree methods of getting from point A to point B, as it were.</p>\n\n<p>First, there is the implicit cast. This is the cast that doesn't\nrequire you to do anything more than an assignment:</p>\n\n<pre><code>int i = 5;\ndouble d = i;\n</code></pre>\n\n<p>These are also called \"widening conversions\" and .NET allows you to\nperform them without any cast operator because you could never lose any\ninformation doing it: the possible range of valid values of a double\nencompasses the range of valid values for an int and then some, so\nyou're never going to do this assignment and then discover to your\nhorror that the runtime dropped a few digits off your int value. For\nreference types, the rule behind an implicit cast is that the cast\ncould never throw an InvalidCastException: it is clear to the compiler\nthat the cast is always valid.</p>\n\n<p>You can make new implicit cast operators for your own types (which\nmeans that you can make implicit casts that break all of the rules, if\nyou're stupid about it). The basic rule of thumb is that an implicit\ncast can never include the possibility of losing information in the\ntransition.</p>\n\n<p>Note that the underlying representation <em>did</em> change in this\nconversion: a double is represented completely differently from an int.</p>\n\n<p>The second kind of conversion is an explicit cast. An explicit cast is\nrequired wherever there is the possibility of losing information, or\nthere is a possibility that the cast might not be valid and thus throw\nan InvalidCastException:</p>\n\n<pre><code>double d = 1.5;\nint i = (int)d;\n</code></pre>\n\n<p>Here you are obviously going to lose information: i will be 1 after the\ncast, so the 0.5 gets lost. This is also known as a \"narrowing\"\nconversion, and the compiler requires that you include an explicit cast\n(int) to indicate that yes, you know that information may be lost, but\nyou don't care.</p>\n\n<p>Similarly, with reference types the compiler requires explicit casts in\nsituations in which the cast may not be valid at run time, as a signal\nthat yes, you know there's a risk, but you know what you're doing.</p>\n\n<p>The third kind of conversion is one that involves such a radical change\nin representation that the designers didn't provide even an explicit\ncast: they make you call a method in order to do the conversion:</p>\n\n<pre><code>string s = \"15\";\nint i = Convert.ToInt32(s);\n</code></pre>\n\n<p>Note that there is nothing that absolutely requires a method call here.\nImplicit and explicit casts are method calls too (that's how you make\nyour own). The designers could quite easily have created an explicit\ncast operator that converted a string to an int. The requirement that\nyou call a method is a stylistic choice rather than a fundamental\nrequirement of the language.</p>\n\n<p>The stylistic reasoning goes something like this: String-to-int is a\ncomplicated conversion with lots of opportunity for things going\nhorribly wrong:</p>\n\n<pre><code>string s = \"The quick brown fox\";\nint i = Convert.ToInt32(s);\n</code></pre>\n\n<p>As such, the method call gives you documentation to read, and a broad\nhint that this is something more than just a quick cast.</p>\n\n<p>When designing your own types (particularly your own value types), you\nmay decide to create cast operators and conversion functions. The lines\ndividing \"implicit cast\", \"explicit cast\", and \"conversion function\"\nterritory are a bit blurry, so different people may make different\ndecisions as to what should be what. Just try to keep in mind\ninformation loss, and potential for exceptions and invalid data, and\nthat should help you decide.\"</p>\n\n<ul>\n<li>Bruce Wood, November 16th 2005</li>\n</ul>\n\n<p><a href=\"http://bytes.com/forum/post1068532-4.html\" rel=\"nofollow noreferrer\">http://bytes.com/forum/post1068532-4.html</a></p>\n"
},
{
"answer_id": 144021,
"author": "Sören Kuklau",
"author_id": 1600,
"author_profile": "https://Stackoverflow.com/users/1600",
"pm_score": 0,
"selected": false,
"text": "<p>In a language- / framework-agnostic manner of speaking, converting from one type or class to another is known as <strong>casting</strong>. This is true for .NET as well, as your first four lines show:</p>\n\n<pre><code>object x;\nint y;\n\nx = 4;\n\ny = ( int )x;\n</code></pre>\n\n<p>C and C-like languages (such as C#) use the <code>(newtype)somevar</code> syntax for casting. In VB.NET, for example, there are explicit built-in functions for this. The last line would be written as:</p>\n\n<pre><code>y = CInt(x)\n</code></pre>\n\n<p>Or, for more complex types:</p>\n\n<pre><code>y = CType(x, newtype)\n</code></pre>\n\n<p>Where 'C' obviously is short for 'cast'.</p>\n\n<p>.NET also has the <code>Convert()</code> function, however. This isn't a built-in language feature (unlike the above two), but rather one of the framework. This becomes clearer when you use a language that isn't necessarily used together with .NET: they still very likely have their own means of casting, but it's .NET that adds <code>Convert()</code>.</p>\n\n<p>As Matt says, the difference in behavior is that <code>Convert()</code> is more explicit. Rather than merely telling the compiler to treat <code>y</code> as an integer equivalent of <code>x</code>, you are specifically telling it to alter <code>x</code> in such a way that is suitable for the integer class, <em>then</em> assign the result to <code>y</code>.</p>\n\n<p>In your particular case, the casting does what is called 'unboxing', whereas <code>Convert()</code> will actually get the integer value. The result will appear the same, but there are subtle differences better <a href=\"https://stackoverflow.com/questions/18465/net-parse-verses-convert#18523\">explained by Keith</a>.</p>\n"
},
{
"answer_id": 144040,
"author": "CodeRedick",
"author_id": 17145,
"author_profile": "https://Stackoverflow.com/users/17145",
"pm_score": -1,
"selected": false,
"text": "<p>Casting is essentially just telling the runtime to \"pretend\" the object is the new type. It doesn't actually convert or change the object in any way.</p>\n\n<p>Convert, however, will perform operations to turn one type into another. </p>\n\n<p>As an example:</p>\n\n<pre><code>char caster = '5';\nConsole.WriteLine((int)caster);\n</code></pre>\n\n<p>The output of those statements will be 53, because all the runtime did is look at the bit pattern and treat it as an int. What you end up getting is the ascii value of the character 5, rather than the number 5.</p>\n\n<p>If you use Convert.ToInt32(caster) however, you will get 5 because it actually reads the string and modifies it correctly. (Essentially it knows that ASCII value 53 is really the integer value 5.)</p>\n"
},
{
"answer_id": 144069,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>The simple answer is: it depends.</p>\n\n<p>For value types, casting will involve genuinely converting it to a different type. For instance:</p>\n\n<pre><code>float f = 1.5f;\nint i = (int) f; // Conversion\n</code></pre>\n\n<p>When the casting expression unboxes, the result (assuming it works) is <em>usually</em> 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>.</p>\n\n<p>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 <em>reference</em> \"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:</p>\n\n<pre><code>object o = \"hello\";\nstring x = (string) o; // No data is \"converted\"; x and o refer to the same object\n</code></pre>\n\n<p>When user-defined conversions get involved, this <em>usually</em> entails returning a different object/value. For example, you could define a conversion to string for your own type - and \n 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.</p>\n\n<p>All of these count as conversions in terms of the specification - but they don't all count as converting an <em>object</em> into an <em>object</em> 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.</p>\n\n<p>Does that cover everything?</p>\n"
},
{
"answer_id": 144116,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<h2>Casting involves References</h2>\n\n<pre><code>List<int> myList = new List<int>();\n//up-cast\nIEnumerable<int> myEnumerable = (IEnumerable<int>) myList;\n//down-cast\nList<int> myOtherList = (List<int>) myEnumerable;\n</code></pre>\n\n<p>Notice that operations against myList, such as adding an element, are reflected in myEnumerable and myOtherList. This is because they are all references (of varying types) to the same instance.</p>\n\n<p>Up-casting is safe. Down-casting can generate run-time errors if the programmer has made a mistake in the type. Safe down-casting is beyond the scope of this answer.</p>\n\n<h2>Converting involves Instances</h2>\n\n<pre><code>List<int> myList = new List<int>();\nint[] myArray = myList.ToArray();\n</code></pre>\n\n<p>myList is used to produce myArray. This is a non-destructive conversion (myList works perfectly fine after this operation). Also notice that operations against myList, such as adding an element, are not reflected in myArray. This is because they are completely seperate instances.</p>\n\n<pre><code>decimal w = 1.1m;\nint x = (int)w;\n</code></pre>\n\n<p>There are operations using the cast syntax in C# that are <a href=\"http://forums.microsoft.com/msdn/ShowPost.aspx?PostID=3895492&SiteID=1\" rel=\"nofollow noreferrer\">actually conversions</a>.</p>\n"
},
{
"answer_id": 144181,
"author": "hurst",
"author_id": 10991,
"author_profile": "https://Stackoverflow.com/users/10991",
"pm_score": 0,
"selected": false,
"text": "<p>According to Table 1-7 titled \"Methods for Explicit Conversion\" on page 55 in Chapter 1, Lesson 4 of <strong>MCTS Self-Paced Training Kit (Exam 70-536): Microsoft® .NET Framework 2.0—Application Development Foundation</strong>, there is certainly a difference between them.</p>\n\n<p><strong>System.Convert</strong> is language-independent and converts \"Between types that implement the <em>System.IConvertible interface</em>.\"</p>\n\n<p><strong>(type) cast operator</strong> is a <strong>C#-specific</strong> language feature that converts \"Between types that define <em>conversion operators</em>.\"</p>\n\n<p>Furthermore, when implementing custom conversions, <strong>advice differs</strong> between them.</p>\n\n<p>Per the section titled <strong>How to Implement Conversion in Custom Types</strong> on pp. 56-57 in the lesson cited above, <em>conversion operators (casting) are meant for simplifying conversions between numeric types, whereas Convert() enables culture-specific conversions</em>.</p>\n\n<blockquote>\n <p>Which technique you choose depends on the type of conversion you want to perform:</p>\n \n <ul>\n <li><p>Define <strong>conversion operators</strong> to simplify narrowing and widening\n conversions between numeric types.</p></li>\n <li><p>Implement <strong>System.IConvertible</strong> to enable conversion through\n System.Convert. Use this technique to enable culture-specific conversions.</p></li>\n <li><p>...</p></li>\n </ul>\n</blockquote>\n\n<p>It should be clearer now that since the cast conversion operator is implemented separately from the IConvertible interface, that Convert() is not necessarily merely another name for casting. (But I can envision where one implementation may refer to the other to ensure consistency).</p>\n"
},
{
"answer_id": 246850,
"author": "Mark T",
"author_id": 10722,
"author_profile": "https://Stackoverflow.com/users/10722",
"pm_score": 1,
"selected": false,
"text": "<p>Semantics aside, a quick test shows they are <b>NOT equivalent !</b><Br>\nThey do the task differently (or perhaps, they do different tasks).</p>\n\n<pre><code>x=-2.5 (int)x=-2 Convert.ToInt32(x)=-2\nx=-1.5 (int)x=-1 Convert.ToInt32(x)=-2\nx=-0.5 (int)x= 0 Convert.ToInt32(x)= 0\nx= 0.5 (int)x= 0 Convert.ToInt32(x)= 0\nx= 1.5 (int)x= 1 Convert.ToInt32(x)= 2\nx= 2.5 (int)x= 2 Convert.ToInt32(x)= 2\n</code></pre>\n\n<p>Notice the <code>x=-1.5</code> and <code>x=1.5</code> cases.</p>\n"
}
]
| 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 Booth",
"author_id": 14873,
"author_profile": "https://Stackoverflow.com/users/14873",
"pm_score": 2,
"selected": false,
"text": "<p>I don't tend to use irb directly that frequently, as I tend to be inside rails and so use script/console a bunch, but I do like using the ruby debugger (Ruby Debug gem). It lets you set a breakpoint basically and then step through your code line by line. </p>\n\n<p>Here's a screencast about it that I haven't actually watched, but a quick search pulled it up, and it could be useful:</p>\n\n<p><a href=\"http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/\" rel=\"nofollow noreferrer\">http://brian.maybeyoureinsane.net/blog/2007/05/07/ruby-debug-basics-screencast/</a></p>\n"
},
{
"answer_id": 144325,
"author": "Atiaxi",
"author_id": 2555346,
"author_profile": "https://Stackoverflow.com/users/2555346",
"pm_score": 0,
"selected": false,
"text": "<p>If you're willing to use an IDE for debugging, I know <a href=\"http://www.eclipse.org/\" rel=\"nofollow noreferrer\" title=\"Eclipse\">Eclipse</a> (via the <a href=\"http://rubyeclipse.sourceforge.net/\" rel=\"nofollow noreferrer\">Ruby Development Tools</a>) has a relatively straightforward interface. If you're doing rails then there's a specific build of eclipse called <a href=\"http://www.aptana.com/rails\" rel=\"nofollow noreferrer\">RadRails</a> which may also help (though I haven't used it for debugging)</p>\n"
},
{
"answer_id": 144887,
"author": "webmat",
"author_id": 6349,
"author_profile": "https://Stackoverflow.com/users/6349",
"pm_score": 4,
"selected": true,
"text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>The command to step out of a given block/method never worked for me though. I never investigated why :-)</p>\n"
},
{
"answer_id": 534947,
"author": "user64842",
"author_id": 64842,
"author_profile": "https://Stackoverflow.com/users/64842",
"pm_score": 1,
"selected": false,
"text": "<p>For Ruby development in Eclipse: there's a much improved version of RDT (ruby development tools) available now. To install it directly in Eclipse, click Help > Software Updates > Find and Install > Search for new features radio button > next > new remote Site > Name = Ruby and URL = <a href=\"http://update.aptana.com/update/rdt/3.2/\" rel=\"nofollow noreferrer\">http://update.aptana.com/update/rdt/3.2/</a> </p>\n\n<p>Another Ruby plugin is the shiny new Eclipse DLTK (dynamic languages toolkit). \n<a href=\"http://download.eclipse.org/technology/dltk/downloads/\" rel=\"nofollow noreferrer\">DLTK stable release 1.0.M5</a> just came out a few days ago.\nHere are some <a href=\"http://wiki.openqa.org/display/WTR/Setting+up+Eclipse+for+Ruby\" rel=\"nofollow noreferrer\">useful installation tips</a>.</p>\n"
}
]
| 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 got associated with a wrong editor, and content checking.\nYou can find a reasonably good JSP editor in the Web Tools Platform (WTP) toolkit.</p>\n"
},
{
"answer_id": 203838,
"author": "nitind",
"author_id": 27905,
"author_profile": "https://Stackoverflow.com/users/27905",
"pm_score": 2,
"selected": false,
"text": "<p>It's not actually something about the editor itself.</p>\n\n<p>This usually happens because of<br>\nA) custom tags that are missing a start or end tag cause an imbalance in the translation<br>\nor<br>\nB) is the result improper handling of scripting variable for custom tags by the JSP Validator. </p>\n\n<p>One's a fault in the JSP file and the other's the fault of the validator. Neither will cause this problem in the upcoming WTP 3.0.3 and Ganymede SR2 releases.</p>\n"
},
{
"answer_id": 281282,
"author": "Greg",
"author_id": 28002,
"author_profile": "https://Stackoverflow.com/users/28002",
"pm_score": 1,
"selected": false,
"text": "<p>I have the same issue. Whatever JSP editor is in Ganymede does not like my if/else scriptlets:</p>\n\n<pre><code><% if(message != null) { %>\n <p id=\"message\"><%=message %></p>\n<% } else { %>\n <p>Please login to view your account information.</p>\n<% } %>\n</code></pre>\n\n<p>It tells me:</p>\n\n<pre><code>Syntax error on token \"}\", delete this token\nSyntax error on token \"catch\", Identifier expected\nSyntax error, insert \"Finally\" to complete TryStatement\n</code></pre>\n\n<p>...on the final closing brace. I have the same file associations as the original poster.\n I suppose I will try to find another JSP editor in the WTP toolkit, but I was under the impression that came with my build.</p>\n"
},
{
"answer_id": 290722,
"author": "Greg",
"author_id": 28002,
"author_profile": "https://Stackoverflow.com/users/28002",
"pm_score": 3,
"selected": false,
"text": "<p>I actually found out what my problem was through the <a href=\"http://www.eclipse.org/newsportal/article.php?id=17447&group=eclipse.webtools#17447\" rel=\"noreferrer\">eclipse webtools usergroup</a>. The issue for me was the use of the Spring form custom tag library. If you self-close the tag... </p>\n\n<pre><code><form:errors path=\"*\" />\n</code></pre>\n\n<p>...then you get the goofy JSP validation error. If you close the tag as if there was body content...</p>\n\n<pre><code><form:errors path=\"*\"></form:errors>\n</code></pre>\n\n<p>Then the error goes away. I need to follow-up with a bug for the Ganymede team.</p>\n"
},
{
"answer_id": 461588,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This is unfortunately a known bug apparently introduced in Service Release 1 of Ganymede (Eclipse Ganymede SR1, v 3.4.1).</p>\n\n<p>See the following pages for more information:</p>\n\n<p><a href=\"http://www.coderanch.com/t/106846/IDEs-Version-Control-other-tools/Ganymede-bug-using-jsp-include\" rel=\"nofollow noreferrer\">http://www.coderanch.com/t/106846/IDEs-Version-Control-other-tools/Ganymede-bug-using-jsp-include</a></p>\n\n<p><a href=\"http://www.eclipse.org/newsportal/article.php?id=17447&group=eclipse.webtools#17447\" rel=\"nofollow noreferrer\">http://www.eclipse.org/newsportal/article.php?id=17447&group=eclipse.webtools#17447</a></p>\n\n<p>The bug is fixed in WTP 3.0.3. Note that to get the fix through the Eclipse \"Software Updates\" function, you have to manually add the WTP update site to the list of sites that get searched during updates, by using the \"Maage Sites...\" function and check the Eclipse Webtools site.</p>\n"
},
{
"answer_id": 562472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Hm, I upgraded to 3.0.3, to no effect. This is happening mostly for <%@ include file=\"somefile.jsp\" %> -style includes. Incredibly frustrating -- makes it very hard to find real errors when I have 300+ of these. Anyone have any luck going back to an earlier version of WTP?</p>\n"
},
{
"answer_id": 604581,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": true,
"text": "<p>I have just downloaded Ganymede 3.4.2 and added WTP 3.0.4 to it and this error has gone for me.</p>\n"
},
{
"answer_id": 2397701,
"author": "Gopal Bairwa",
"author_id": 288338,
"author_profile": "https://Stackoverflow.com/users/288338",
"pm_score": 2,
"selected": false,
"text": "<p>I just ran a update for Software Updates->Gynemede Update Site-> \"Web and Java EE Development\" and the error seems to go away. </p>\n"
}
]
| 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, description and keywords:</p>\n\n<pre><code><head>\n<asp:ContentPlaceHolder ID=\"cphHead\" runat=\"server\">\n <title>Default Title</title>\n <meta name=\"description\" content=\"Default Description\" />\n <meta name=\"keywords\" content=\"Default Keywords\" />\n</asp:ContentPlaceHolder>\n</head>\n</code></pre>\n\n<p>And then in the page, you can override all this content:</p>\n\n<pre><code><asp:Content ID=\"headContent\" ContentPlaceHolderID=\"cphHead\" runat=\"server\">\n <title>Page Specific Title</title>\n <meta name=\"description\" content=\"Page Specific Description\" />\n <meta name=\"keywords\" content=\"Page Specific Keywords\" />\n</asp:Content>\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 147494,
"author": "Charlino",
"author_id": 10202,
"author_profile": "https://Stackoverflow.com/users/10202",
"pm_score": 4,
"selected": false,
"text": "<p>Put it in your viewdata! Do something like the following...</p>\n\n<p>BaseViewData.cs - this is a viewdata class that all other viewdata classes will inherit from</p>\n\n<pre><code>public class BaseViewData\n{\n public string Title { get; set; }\n public string MetaKeywords { get; set; }\n public string MetaDescription { get; set; }\n}\n</code></pre>\n\n<p>Then your Site.Master (or whatever) class should be defined as follows:</p>\n\n<pre><code>public partial class Site : System.Web.Mvc.ViewMasterPage<BaseViewData>\n{\n}\n</code></pre>\n\n<p>Now in your Site.Master page simply have</p>\n\n<pre><code><title><%=ViewData.Model.Title %></title>\n<meta name=\"keywords\" content=\"<%=ViewData.Model.MetaKeywords %>\" />\n<meta name=\"description\" content=\"<%=ViewData.Model.MetaDescription %>\" />\n</code></pre>\n\n<p>And you're away laughing!</p>\n\n<p>HTHs,\nCharles</p>\n\n<p>Ps. You can then expand on this idea, e.g. put a getter to your User (IPrincipal) Class into a LoggedInBaseViewData class.</p>\n"
}
]
| 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 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.</p>\n\n<p>And finally: \"NAME\" is a reserved word in at least one DBMS, so consider using something else, e.g. fullname.</p>\n"
},
{
"answer_id": 144159,
"author": "user7116",
"author_id": 7116,
"author_profile": "https://Stackoverflow.com/users/7116",
"pm_score": 2,
"selected": false,
"text": "<p>I think if your VARCHAR was larger you would notice you're duplicating quite a bit of data throughout the database. Whereas if you went with a numeric ID column, you're not duplicating nearly the same amount of data when adding foreign key columns to other tables.</p>\n\n<p>Moreover, textual data is a royal pain in terms of comparisons, your life is much easier when you're doing <strong>WHERE id = user_id</strong> versus <strong>WHERE name LIKE inputname</strong> (or something similar).</p>\n"
},
{
"answer_id": 144180,
"author": "technophile",
"author_id": 23029,
"author_profile": "https://Stackoverflow.com/users/23029",
"pm_score": 3,
"selected": false,
"text": "<p>Using any kind of non-synthetic data (i.e. anything from the user, as opposed to generated by the application) as a PK is problematic; you have to worry about culture/localization differences, case sensitivity (and other issues depending on DB collation), can result in data problems if/when that user-entered data ever changes, etc.</p>\n\n<p>Using non-user-generated data (Sequential GUIDs (or non-sequential if your DB doesn't support them or you don't care about page splits) or identity ints (if you don't need GUIDs)) is much easier and much safer.</p>\n\n<p>Regarding duplicate data: I don't see how using non-synthetic keys protects you from that. You still have issues where the user enters \"Bob Smith\" instead of \"Bob K. Smith\" or \"Smith, Bob\" or \"bob smith\" etc. Duplication management is necessary (and pretty much identical) regardless of whether your key is synthetic or non-synthetic, and non-synthetic keys have a host of other potential issues that synthetic keys neatly avoid.</p>\n\n<p>Many projects don't need to worry about that (tightly constrained collation choices avoid many of them, for example) but in general I prefer synthetic keys. This is not to say you can't be successful with organic keys, clearly you can, but for many projects they're not the better choice.</p>\n"
},
{
"answer_id": 144276,
"author": "Darrel Miller",
"author_id": 6819,
"author_profile": "https://Stackoverflow.com/users/6819",
"pm_score": 3,
"selected": false,
"text": "<p>I believe that the majority of people who have developed any significant sized real world database applications will tell you that surrogate keys are the only realistic solution.<br>\nI know the academic community will disagree but that is the difference between theoretical purity and practicality.</p>\n\n<p>Any reasonable sized query that has to do joins between tables that use non-surrogate keys where some tables have composite primary keys quickly becomes unmaintainable.</p>\n"
},
{
"answer_id": 144317,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 1,
"selected": false,
"text": "<p>If the \"name\" field really is appropriate as a primary key, then do it. The database will <em>not</em> get more normalized by creating a surrogate key in that case. You will get some duplicate strings for foreign keys, but that is not a normalization issue, since the FK constraint guarantrees integrity on strings just as it would on surrogate keys.</p>\n\n<p>However you are not explaining what the \"name\" is. In practice it is very seldom that a string is appropriate as a primary key. If it is the name of a person, it wont work as a PK, since more than one person can have the same name, people can change names and so on.</p>\n"
},
{
"answer_id": 144452,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 1,
"selected": false,
"text": "<p>One thing that others don't seem to have mentioned is that joins on int fields tend to perform better than joins on varchar fields.</p>\n\n<p>And I definitely would always use a surrogate key over using names (of people or businesses) because they are never unique over time. In our database, for instance, we have 164 names with over 100 instances of the same name. This clearly shows the dangers of considering using name as a key field.</p>\n"
},
{
"answer_id": 146566,
"author": "Walter Mitty",
"author_id": 19937,
"author_profile": "https://Stackoverflow.com/users/19937",
"pm_score": 1,
"selected": false,
"text": "<p>The original question is not one of normalization. If you have a normalized database, as you stated, then you do not need to change it for normalization reasons.</p>\n\n<p>There are really two issues in your question. The first is whether ints or varchars a preferable for use as primary keys and foreign keys. The second is whether you can use the natural keys given in the problem definition, or whether you should generate a synthetic key (surrogate key) to take the place of the natural key.</p>\n\n<p>ints are a little more concise than varchars, and a little more efficient for such things as index processing. But the difference is not overwhelming. You should probably not make your decision on this basis alone.</p>\n\n<p>The question of whether the natural key provided really works as a natural key or not is much more significant. The problem of duplicates in a \"name\" column is not the only problem. There is also the problem of what happens when a person changes her name. This problem probably doesn't surface in the example you've given, but it does surface in lots of other database applications. An example would be the transcript over four years of all the courses taken by a student. A woman might get married and change her name in the course of four years, and now you're stuck. </p>\n\n<p>You either have to leave the name unchanged, in which case it no longer agrees with the real world, or update it retroactively in all the courses the person took, which makes the database disagree with the printed rosters made at the time.</p>\n\n<p>If you do decide on a synthetic key, you now have to decide whether or not the application is going to reveal the value of the synthetic key to the user community. That's another whole can of worms, and beyond the scope of this discussion.</p>\n"
}
]
| 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 \"orderProperty\" is itself named \"OrderPropertyList\".</p>\n\n<p>What I would do is first generate it without any custom bindings, and look at the class names and hierarchies that it generates. Then, consider what you want to override, and how.</p>\n"
},
{
"answer_id": 179916,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>I believe what you need to to is set:</p>\n\n<pre><code><jaxb:globalBindings localScoping=\"toplevel\"/>\n</code></pre>\n\n<p>This will generate standalone classes instead of nested classes.</p>\n\n<p>Doing</p>\n\n<pre><code><jaxb:bindings schemaLocation=\"../xsd/Schema.xsd\" node=\"/xs:schema\">\n <jaxb:bindings node=\"//xs:element[@name='orderPropertyList']\">\n <jaxb:class name=\"OrderPropertyList\"/>\n </jaxb:bindings>\n</jaxb:bindings>\n</code></pre>\n\n<p>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.</p>\n\n<p>Also, if you did want to change the name of the generated class, I think the XPath would actually be:</p>\n\n<pre><code><jaxb:bindings node=\"//xs:element[@name='orderPropertyList']/xs:complexType\">\n</code></pre>\n\n<p>with complexType on the end. I think excluding this was what was causing the error message you got.</p>\n"
},
{
"answer_id": 7775099,
"author": "Jeff Evans",
"author_id": 375670,
"author_profile": "https://Stackoverflow.com/users/375670",
"pm_score": 2,
"selected": false,
"text": "<p>It's really fun when you have a schema like the following:</p>\n\n<pre><code><xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" elementFormDefault=\"qualified\" attributeFormDefault=\"unqualified\" version=\"1.0\">\n <xsd:element name=\"TopLevelElement\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"Something\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"Something\" maxOccurs=\"unbounded\">\n <xsd:complexType>\n <xsd:sequence>\n <xsd:element name=\"somethingFieldA\" type=\"xsd:string\"/>\n <xsd:element name=\"somethingFieldB\" type=\"xsd:string\"/>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n </xsd:sequence>\n </xsd:complexType>\n </xsd:element>\n</xsd:schema>\n</code></pre>\n\n<p>In this case, xjc seems to be trying to actually generate four classes called <code>Something</code>, one for each element named <code>Something</code>, and one for each of their <code>complexType</code>s. So you need to provide a binding that hits each of these four elements <strong>and</strong> complex types specifically at the level where they occur in the schema (well really only three, because then the 4th can just become the lone <code>Something</code> class).</p>\n"
},
{
"answer_id": 7890899,
"author": "dolbysurnd",
"author_id": 654200,
"author_profile": "https://Stackoverflow.com/users/654200",
"pm_score": 0,
"selected": false,
"text": "<p>I needed to do customizations for a schema like the one <strong>jeff303</strong> presented. My scenario was slightly different in that the schema was inlined within a WSDL document.</p>\n\n<p>One thing pointed out by <strong>philvarner</strong> is that the <em>node selection for the element should end with '/xs:complexType'</em> and this seemed very important, as the compiler would continually generate an IllegalArgumentException related to looping inheritance without it.</p>\n\n<p>These posts are related so I figured a link back would be helpful to someone 'googling' that ends up here.</p>\n\n<p>Check out question <a href=\"https://stackoverflow.com/questions/7881883/jaxb-customizations-with-a-poorly-formed-wsdl/7884729#7884729\">7881883</a> </p>\n"
},
{
"answer_id": 33867623,
"author": "amit dahiya",
"author_id": 5594528,
"author_profile": "https://Stackoverflow.com/users/5594528",
"pm_score": 0,
"selected": false,
"text": "<p>Entering this <code>/xs:complexType</code> at the end of the element helped in fixing the illegal class inheritance loop error.</p>\n"
}
]
| 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. 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:</p>\n\n<pre><code><script type=\"text/javascript\">\n//define and initialize your object/hastable\nvar obj = {};\nobj[20] = 'C';\nobj[10] = 'B';\nobj[-10] = 'A';\n\n// get the indexes and sort them\nvar indexes = [];\nfor(var i in obj){\n indexes.push(i);\n}\nindexes.sort(function(a,b){\n return a-b;\n});\n\n// write the values to the page in index order (increasing)\nfor(var i=0,l=indexes.length; i<l; i++){\n document.write(obj[indexes[i]] + ' ');\n}\n// Should print out as \"A B C\" to the page\n</script>\n</code></pre>\n"
},
{
"answer_id": 144188,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 2,
"selected": false,
"text": "<p>You're bumping into the boundary between <code>Array</code>s and <code>Object</code>s in Javascript. Array elements are accessed by ordinal, an integer between 0 and 4294967294 (maximum unsigned 32-bit integer - 1), inclusive. Object properties are accessed by name. Since -10 isn't a valid ordinal number, it is interpreted as a name. Here's a simpler example:</p>\n\n<pre><code>var arr = new Array();\narr[0] = 'A';\narr[1] = 'B';\narr[-1] = 'C';\narr.length\n</code></pre>\n\n<p>The result is 2 - there are only two elements in the array, at indices 0 and 1.</p>\n"
}
]
| 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 press F9.</p>\n"
},
{
"answer_id": 144160,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 2,
"selected": false,
"text": "<p>Application.ScreenUpdating = False</p>\n\n<p>And of course set it back to True again when you've finished, even if an error is raised.\nExample:</p>\n\n<pre><code>Public Sub MyMacro\n On Error GoTo ErrHandler\n Application.ScreenUpdating = False\n ... do my stuff that might raise an error\n Application.ScreenUpdating = True\n Exit Sub\nErrHandler:\n Application.ScreenUpdating = True\n ... Do something with the error, e.g. MsgBox \nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 144173,
"author": "SeeR",
"author_id": 22569,
"author_profile": "https://Stackoverflow.com/users/22569",
"pm_score": 5,
"selected": true,
"text": "<p>I use both of the proposed solutions:</p>\n\n<pre><code>Application.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\n...\n...\n...\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\n</code></pre>\n"
},
{
"answer_id": 144221,
"author": "wilth",
"author_id": 5218,
"author_profile": "https://Stackoverflow.com/users/5218",
"pm_score": 1,
"selected": false,
"text": "<p>Building upon Joe and SeeR (this uses old syntax so it's compatible with VBA of Office 2000):</p>\n\n<pre><code>On Error Goto AfterCalculation\nApplication.ScreenUpdating = False\nApplication.Calculation = xlCalculationManual\n...\n\nAfterCalculation:\nApplication.Calculation = xlCalculationAutomatic\nApplication.ScreenUpdating = True\n</code></pre>\n"
},
{
"answer_id": 452544,
"author": "user37130",
"author_id": 37130,
"author_profile": "https://Stackoverflow.com/users/37130",
"pm_score": 2,
"selected": false,
"text": "<p>I also prefer to use both of the proposed solutions, \nbut also keeping the users previous calculation mode.</p>\n\n<p>For this particular application this might be no biggie, \nbut it's usually best practice to let the users have their settings restored after your procedure is finished:</p>\n\n<pre><code>Application.ScreenUpdating = False\nPreviousCalcMode = Application.Calculation\nApplication.Calculation = xlCalculationManual\n ... \n ...\n ...\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n</code></pre>\n\n<p>NB. It would also be worth your time to insert some error handling that turns on Application.ScreenUpdating should an error occur in your otherwise brilliant code ;)\nIf memory serves me right, Excel will not show any errormessages etc when ScreenUpdating = false.\nSomething like this:</p>\n\n<pre><code>Sub DoSomeThing\n\n\nOn Error Goto DisplayError\n\nApplication.ScreenUpdating = False\nPreviousCalcMode = Application.Calculation\nApplication.Calculation = xlCalculationManual\n ... \n ...\n ...\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n\nExit Sub\n\nDisplayError:\nApplication.Calculation = PreviousCalcMode\nApplication.ScreenUpdating = True\n\nMsgBox Err.Description\nEnd 'This stops execution of macro, in some macros this might not be what you want'\n '(i.e you might want to close files etc)'\nEnd Sub\n</code></pre>\n"
}
]
| 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 that whatever tool you are using to generate the results has some method of modifying the output. </p>\n\n<p>By default Oracle outputs columns based upon the width of the title or the width of the column data which ever is wider. </p>\n\n<p>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. </p>\n\n<pre><code>select substr(assigner_staff_id, 8) as staff_id, \n active_flag as Flag, \n to_char(assign_date, 'DD/MM/YY'),\n to_char(complete_date, 'DD/MM/YY'), \n mod_date\nfrom work where assigner_staff_id = '2096';\n</code></pre>\n"
},
{
"answer_id": 144197,
"author": "AJ.",
"author_id": 7211,
"author_profile": "https://Stackoverflow.com/users/7211",
"pm_score": 0,
"selected": false,
"text": "<p>Nice question. I really had to think about it. </p>\n\n<p>One thing you could do is change your SQL so that it only returns the narrowest usable columns. </p>\n\n<p>e.g. (I'm not very hot on oracle syntax, but something similar should work): </p>\n\n<pre><code>select substring( convert(varchar(4), assigner_staff_id), 1, 4 ) as id, \n active_flag as act, -- use shorter column name\n\n -- etc. \n\nfrom work where assigner_staff_id = '2096';\n</code></pre>\n\n<p>Does that make sense?<br>\nIf you were doing this on unix/linux, I would suggest running it from the command line and piping it through an awk script. </p>\n\n<p>If I've miss-understood, then please update your question and I'll have another go :)</p>\n"
},
{
"answer_id": 144205,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>What you can do with sql is limited by your tool. SQL Plus has commands to format the columns but they are not real easy to use. </p>\n\n<p>One quick approach is to paste the output into excel and format it there or just attach the spreadsheet. Some tools will save the output directly as a spreadsheet.</p>\n"
},
{
"answer_id": 145055,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 0,
"selected": false,
"text": "<p>If you don't have alot of rows returned I'll often use <a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:2264752026530068::::P11_QUESTION_ID:1035431863958\" rel=\"nofollow noreferrer\">Tom Kytes print_table</a> function.</p>\n\n<pre><code>SQL> set serveroutput on \nSQL> execute print_table('select * from all_objects where rownum < 3');\nOWNER : SYS\nOBJECT_NAME : /1005bd30_LnkdConstant\nSUBOBJECT_NAME :\nOBJECT_ID : 27574\nDATA_OBJECT_ID :\nOBJECT_TYPE : JAVA CLASS\nCREATED : 22-may-2008 11:41:13\nLAST_DDL_TIME : 22-may-2008 11:41:13\nTIMESTAMP : 2008-05-22:11:41:13\nSTATUS : VALID\nTEMPORARY : N\nGENERATED : N\nSECONDARY : N\n-----------------\nOWNER : SYS\nOBJECT_NAME : /10076b23_OraCustomDatumClosur\nSUBOBJECT_NAME :\nOBJECT_ID : 22390\nDATA_OBJECT_ID :\nOBJECT_TYPE : JAVA CLASS\nCREATED : 22-may-2008 11:38:34\nLAST_DDL_TIME : 22-may-2008 11:38:34\nTIMESTAMP : 2008-05-22:11:38:34\nSTATUS : VALID\nTEMPORARY : N\nGENERATED : N\nSECONDARY : N\n-----------------\n\nPL/SQL procedure successfully completed.\n\nSQL> \n</code></pre>\n\n<p>If its lots of rows, i'll just do the query in SQL Developer and save as xls, businessy types love excel for some reason.</p>\n"
},
{
"answer_id": 13185162,
"author": "Jim Clouse",
"author_id": 868541,
"author_profile": "https://Stackoverflow.com/users/868541",
"pm_score": 2,
"selected": false,
"text": "<p>In your statement, you can specify the type of output you're looking for:</p>\n\n<pre><code>select /*csv*/ col1, col2 from table;\nselect /*Delimited*/ col1, col2 from table;\n</code></pre>\n\n<p>there are other formats available such as xml, html, text, loader, etc.</p>\n\n<p>You can change the formatting of these particular options under tools > preferences > Database > Utilities > Export</p>\n\n<p>Be sure to choose Run Script rather than Run Statement.</p>\n\n<p>* this is for Oracle SQL Developer v3.2</p>\n"
},
{
"answer_id": 20098946,
"author": "Bubba",
"author_id": 3013559,
"author_profile": "https://Stackoverflow.com/users/3013559",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just use the \"cast\" function?</p>\n\n<pre><code>select \n(cast(assigner_staff_id as VARCHAR2(4)) AS STAFF_ID,\n(cast(active_flag as VARCHAR2(1))) AS A,\n(cast(assign_date as VARCHAR2(10))) AS ASSIGN_DATE,\n(cast(COMPLETE_date as VARCHAR2(10))) AS COMPLETE_DATE,\n(cast(mod_date as VARCHAR2(10))) AS MOD_DATE\nfrom work where assigner_staff_id = '2096';\n</code></pre>\n"
}
]
| 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 buffer you need, the rest should be simple:</p>\n\n<pre><code>public static string UnsafeAsciiBytesToString(byte[] buffer, int offset, int length)\n{\n unsafe\n {\n fixed (byte* pAscii = buffer)\n { \n return new String((sbyte*)pAscii, offset, length);\n }\n }\n}\n</code></pre>\n\n<p>If you need to look first:</p>\n\n<pre><code>public static string UnsafeAsciiBytesToString(byte[] buffer, int offset)\n{\n int end = offset;\n while (end < buffer.Length && buffer[end] != 0)\n {\n end++;\n }\n unsafe\n {\n fixed (byte* pAscii = buffer)\n { \n return new String((sbyte*)pAscii, offset, end - offset);\n }\n }\n}\n</code></pre>\n\n<p>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 <em>particularly</em> strange default codepage which isn't based on ASCII.</p>\n\n<p>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)?</p>\n"
},
{
"answer_id": 144194,
"author": "Jeffrey L Whitledge",
"author_id": 10174,
"author_profile": "https://Stackoverflow.com/users/10174",
"pm_score": 1,
"selected": false,
"text": "<p>One possibility to consider: check that the default code-page is acceptable and use that information to select the conversion mechanism at run-time.</p>\n\n<p>This could also take into account whether the string is in fact null-terminated, but once you've done that, of course, the speed gains my vanish.</p>\n"
},
{
"answer_id": 1835186,
"author": "Pat",
"author_id": 116891,
"author_profile": "https://Stackoverflow.com/users/116891",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure of the speed, but I found it easiest to use LINQ to remove the nulls before encoding:</p>\n\n<pre><code>string s = myEncoding.GetString(bytes.TakeWhile(b => !b.Equals(0)).ToArray());\n</code></pre>\n"
},
{
"answer_id": 2466242,
"author": "Adam Pierce",
"author_id": 5324,
"author_profile": "https://Stackoverflow.com/users/5324",
"pm_score": -1,
"selected": false,
"text": "<p>This is a bit ugly but you don't have to use unsafe code:</p>\n\n<pre><code>string result = \"\";\nfor (int i = 0; i < data.Length && data[i] != 0; i++)\n result += (char)data[i];\n</code></pre>\n"
},
{
"answer_id": 8248997,
"author": "Vladimir Poslavskiy",
"author_id": 1062758,
"author_profile": "https://Stackoverflow.com/users/1062758",
"pm_score": 3,
"selected": false,
"text": "<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace TestProject1\n{\n class Class1\n {\n static public string cstr_to_string( byte[] data, int code_page)\n {\n Encoding Enc = Encoding.GetEncoding(code_page); \n int inx = Array.FindIndex(data, 0, (x) => x == 0);//search for 0\n if (inx >= 0)\n return (Enc.GetString(data, 0, inx));\n else \n return (Enc.GetString(data)); \n }\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12584758,
"author": "euwe",
"author_id": 1512586,
"author_profile": "https://Stackoverflow.com/users/1512586",
"pm_score": 2,
"selected": false,
"text": "<pre><code>s = s.Substring(0, s.IndexOf((char) 0));\n</code></pre>\n"
},
{
"answer_id": 17588566,
"author": "Harald Coppoolse",
"author_id": 2281790,
"author_profile": "https://Stackoverflow.com/users/2281790",
"pm_score": 0,
"selected": false,
"text": "<p>An easy / safe / fast way to convert byte[] objects to strings containing their ASCII equivalent and vice versa using the .NET class System.Text.Encoding. The class has a static function that returns an ASCII encoder:</p>\n\n<p>From String to byte[]:</p>\n\n<pre><code>string s = \"Hello World!\"\nbyte[] b = System.Text.Encoding.ASCII.GetBytes(s);\n</code></pre>\n\n<p>From byte[] to string:</p>\n\n<pre><code>byte[] byteArray = new byte[] {0x41, 0x42, 0x09, 0x00, 0x255};\nstring s = System.Text.Encoding.ASCII.GetString(byteArray);\n</code></pre>\n"
},
{
"answer_id": 20247598,
"author": "user3042599",
"author_id": 3042599,
"author_profile": "https://Stackoverflow.com/users/3042599",
"pm_score": 4,
"selected": false,
"text": "<p>Oneliner (assuming the buffer actually contains ONE well formatted null terminated string):</p>\n\n<pre><code>String MyString = Encoding.ASCII.GetString(MyByteBuffer).TrimEnd((Char)0);\n</code></pre>\n"
},
{
"answer_id": 57975836,
"author": "Heinzi",
"author_id": 87698,
"author_profile": "https://Stackoverflow.com/users/87698",
"pm_score": 2,
"selected": false,
"text": "<p>Just for completeness, you can also use built-in methods of the .NET framework to do this:</p>\n\n<pre><code>var handle = GCHandle.Alloc(buffer, GCHandleType.Pinned);\ntry\n{\n return Marshal.PtrToStringAnsi(handle.AddrOfPinnedObject());\n}\nfinally\n{\n handle.Free();\n}\n</code></pre>\n\n<p>Advantages:</p>\n\n<ul>\n<li>It doesn't require unsafe code (i.e., you can also use this method for VB.NET) and</li>\n<li>it also works for \"wide\" (UTF-16) strings, if you use <code>Marshal.PtrToStringUni</code> instead.</li>\n</ul>\n"
}
]
| 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 precision.</p>\n"
},
{
"answer_id": 144231,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Decimals won't throw away decimal places like that. If you really want to limit precision to 2 d.p. then try</p>\n\n<pre><code>decimal.getcontext().prec=2\n</code></pre>\n\n<p>EDIT: You can alternatively call quantize() every time you multiply or divide (addition and subtraction will preserve the 2 dps).</p>\n"
},
{
"answer_id": 144253,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": -1,
"selected": false,
"text": "<p>If I undertand Decimal correctly, the \"precision\" is the number of digits after the decimal point in <em>decimal notation</em>.</p>\n\n<p>You seem to want something else: the number of significant digits. That is one more than the number of digits after the decimal point in <em>scientific notation</em>.</p>\n\n<p>I would be interested in learning about a Python module that does significant-digits-aware floating point point computations.</p>\n"
},
{
"answer_id": 144263,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>What's wrong with floating point? </p>\n\n<pre><code>>>> \"%8.2e\"% ( 1.0/3.0 )\n'3.33e-01'\n</code></pre>\n\n<p>It was designed for scientific-style calculations with a limited number of significant digits.</p>\n"
},
{
"answer_id": 144573,
"author": "Fredrik Johansson",
"author_id": 1163767,
"author_profile": "https://Stackoverflow.com/users/1163767",
"pm_score": 4,
"selected": true,
"text": "<p>Changing the decimal working precision to 2 digits is <em>not</em> a good idea, unless you absolutely only are going to perform a single operation.</p>\n\n<p>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.</p>\n\n<p>Once you've arrived at the final result, what you probably want is quantize:</p>\n\n<pre>\n>>> (Decimal('1.00') / Decimal('3.00')).quantize(Decimal(\"0.001\"))\nDecimal(\"0.333\")\n</pre>\n\n<p>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 <a href=\"http://pyinterval.googlecode.com/\" rel=\"noreferrer\">pyinterval</a> and <a href=\"http://code.google.com/p/mpmath/\" rel=\"noreferrer\">mpmath</a> (which supports arbitrary precision). It is also straightforward to implement interval arithmetic with the decimal library, since it supports directed rounding.</p>\n\n<p>You may also want to read the <a href=\"http://speleotrove.com/decimal/decifaq4.html#signif\" rel=\"noreferrer\">Decimal Arithmetic FAQ: Is the decimal arithmetic ‘significance’ arithmetic?</a></p>\n"
},
{
"answer_id": 719519,
"author": "user86317",
"author_id": 86317,
"author_profile": "https://Stackoverflow.com/users/86317",
"pm_score": 1,
"selected": false,
"text": "<p>Just out of curiosity...is it necessary to use the decimal module? Why not floating point with a significant-figures rounding of numbers when you are ready to see them? Or are you trying to keep track of the significant figures of the computation (like when you have to do an error analysis of a result, calculating the computed error as a function of the uncertainties that went into the calculation)? If you want a rounding function that rounds from the left of the number instead of the right, try:</p>\n\n<pre><code>def lround(x,leadingDigits=0): \n \"\"\"Return x either as 'print' would show it (the default) \n or rounded to the specified digit as counted from the leftmost \n non-zero digit of the number, e.g. lround(0.00326,2) --> 0.0033\n \"\"\" \n assert leadingDigits>=0 \n if leadingDigits==0: \n return float(str(x)) #just give it back like 'print' would give it\n return float('%.*e' % (int(leadingDigits),x)) #give it back as rounded by the %e format \n</code></pre>\n\n<p>The numbers will look right when you print them or convert them to strings, but if you are working at the prompt and don't explicitly print them they may look a bit strange:</p>\n\n<pre><code>>>> lround(1./3.,2),str(lround(1./3.,2)),str(lround(1./3.,4))\n(0.33000000000000002, '0.33', '0.3333')\n</code></pre>\n"
}
]
| 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-size. This is becoming less useful now that most browsers can do full page zoom. Before when they could only change the size of the text, using em for width/height would allow those elements to scale also.</p>\n"
},
{
"answer_id": 144238,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 0,
"selected": false,
"text": "<p>They are re-calculating exact pixel values to <code>em</code> to make them scalable.</p>\n\n<p>See this <a href=\"http://riddle.pl/emcalc/\" rel=\"nofollow noreferrer\">on-line calculator</a> for example.</p>\n"
},
{
"answer_id": 144240,
"author": "Apocalisp",
"author_id": 3434,
"author_profile": "https://Stackoverflow.com/users/3434",
"pm_score": 2,
"selected": false,
"text": "<p>Traditionally, em is the width of the upper case M. In practise though, an em is the point size of the font.</p>\n\n<p><a href=\"http://comm415.wordpress.com/2008/04/04/em-dash-versus-en-dash/\" rel=\"nofollow noreferrer\">em dash versus en dash</a>.</p>\n"
},
{
"answer_id": 144245,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 5,
"selected": true,
"text": "<p>Historically it is the width of an \"M\" in the font. Hence the name!\nIn CSS2.1 it is <a href=\"http://www.w3.org/TR/CSS21/syndata.html#em-width\" rel=\"noreferrer\">defined</a> to be the same as the font-size.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 144271,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 1,
"selected": false,
"text": "<p>An em size is proportional to its containing element.</p>\n\n<p>For example:</p>\n\n<pre><code><!-- Browser default size (usually 16px) -->\n<div style=\"font-size: 1.00em;\">\n <!-- 150 % of the container's size: 16 + (16/2) = 24 -->\n <div style=\"font-size: 1.50em;\">\n</code></pre>\n\n<p><a href=\"http://riddle.pl/emcalc/\" rel=\"nofollow noreferrer\">This editor</a> keeps it in mind for me (as to how it works).</p>\n"
}
]
| 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, new connection requests will be denied. </p>\n\n<p>That said, connections do time out after a while if they're not closed. </p>\n"
},
{
"answer_id": 144248,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 0,
"selected": false,
"text": "<p>You could run out of connections available if it happens often enought, you should use a finally everywhere you execute a command to close the connection.</p>\n"
},
{
"answer_id": 144251,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 0,
"selected": false,
"text": "<p>The garbage collector will eventually finalize your open connection object, but you don't know when the GC comes around the next time. Until then you might run out of connections in your pool if you have a lot of traffic or it's a shared sql server.</p>\n\n<p>Why not dispose it in the finally section of your try/catch block?</p>\n\n<pre><code>finally\n{\n if (cn != null)\n {\n cn.Dispose();\n cn = null;\n }\n}\n</code></pre>\n\n<p>This should be done in the web service method obviously.</p>\n"
},
{
"answer_id": 144252,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 0,
"selected": false,
"text": "<pre><code>try\n{\n sqlCommandObject.Execute(); // this line will throw a timeout exception\n}\nfinally\n{\n sqlConnectionObject.Close(); // this will execute no matter what happens\n}\n</code></pre>\n"
},
{
"answer_id": 144281,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>If the app stops working after an hour or so, that could definitely be caused by connections not being closed/disposed.</p>\n"
},
{
"answer_id": 144299,
"author": "ullmark",
"author_id": 23044,
"author_profile": "https://Stackoverflow.com/users/23044",
"pm_score": 4,
"selected": true,
"text": "<p>Since a SqlConnection closes while disposing i usually use this syntax</p>\n\n<pre><code>using (SqlConnection conn = new SqlConnection())\n{\n // SqlCode here \n}\n</code></pre>\n"
},
{
"answer_id": 144304,
"author": "kervin",
"author_id": 16549,
"author_profile": "https://Stackoverflow.com/users/16549",
"pm_score": 1,
"selected": false,
"text": "<p>This is why the 'using' keyword is so important when using ADO.Net</p>\n\n<pre><code> using ( SqlConnection conn = new SqlConnection() )\n {\n ...\n }\n</code></pre>\n\n<p>This forces a type of deterministic garbage collection on the ADO.Net object using the IDispose interface.</p>\n\n<p>Most database code uses a lot of nested 'using' clauses for that purpose.</p>\n"
}
]
| 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. Then get the CGImage's data provider, from that a CFData representation of the bitmap. Make sure to release the CFData when done.</p>\n\n<pre><code>CGImageRef cgImage = [image CGImage];\nCGDataProviderRef provider = CGImageGetDataProvider(cgImage);\nCFDataRef bitmapData = CGDataProviderCopyData(provider);\n</code></pre>\n\n<p>You will probably want to look at the bitmap info of the CGImage to get pixel order, image dimensions, etc.</p>\n"
},
{
"answer_id": 159879,
"author": "Mark Bessey",
"author_id": 17826,
"author_profile": "https://Stackoverflow.com/users/17826",
"pm_score": 1,
"selected": false,
"text": "<p>To do something similar in my application, I created a small off-screen CGImageContext, and then rendered the UIImage into it. This allowed me a fast way to extract a number of pixels at once. This means that you can set up the target bitmap in a format you find easy to parse, and let CoreGraphics do the hard work of converting between color models or bitmap formats.</p>\n"
},
{
"answer_id": 396931,
"author": "iggames",
"author_id": 49622,
"author_profile": "https://Stackoverflow.com/users/49622",
"pm_score": 3,
"selected": false,
"text": "<p>Lajos's answer worked for me. To get the pixel data as an array of bytes, I did this:</p>\n\n<p><code>UInt8* data = CFDataGetBytePtr(bitmapData);</code></p>\n\n<p>More info: CFDataRef <a href=\"http://developer.apple.com/DOCUMENTATION/CoreFoundation/Reference/CFDataRef/Reference/reference.html#//apple_ref/c/func/CFDataGetBytePtr\" rel=\"noreferrer\">documentation</a>.</p>\n\n<p>Also, remember to include <code>CoreGraphics.framework</code></p>\n"
},
{
"answer_id": 645341,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>I dont know how to index into image data correctly based on given X,Y cordination. Does anyone know?</p>\n</blockquote>\n\n<p>pixelPosition = (x+(y*((imagewidth)*BytesPerPixel))); </p>\n\n<p>// pitch isn't an issue with this device as far as I know and can be let zero...\n// ( or pulled out of the math ).</p>\n"
},
{
"answer_id": 694139,
"author": "Asher",
"author_id": 84181,
"author_profile": "https://Stackoverflow.com/users/84181",
"pm_score": 6,
"selected": true,
"text": "<h2>A little more detail...</h2>\n\n<p>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). </p>\n\n<p>Method 1: Writable Pixel Information</p>\n\n<ol>\n<li><p>I defined constants</p>\n\n<pre><code>#define RGBA 4\n#define RGBA_8_BIT 8\n</code></pre></li>\n<li><p>In my UIImage subclass I declared instance variables:</p>\n\n<pre><code>size_t bytesPerRow;\nsize_t byteCount;\nsize_t pixelCount;\n\nCGContextRef context;\nCGColorSpaceRef colorSpace;\n\nUInt8 *pixelByteData;\n// A pointer to an array of RGBA bytes in memory\nRPVW_RGBAPixel *pixelData;\n</code></pre></li>\n<li><p>The pixel struct (with alpha in this version)</p>\n\n<pre><code>typedef struct RGBAPixel {\n byte red;\n byte green;\n byte blue;\n byte alpha;\n} RGBAPixel;\n</code></pre></li>\n<li><p>Bitmap function (returns pre-calculated RGBA; divide RGB by A to get unmodified RGB):</p>\n\n<pre><code>-(RGBAPixel*) bitmap {\n NSLog( @\"Returning bitmap representation of UIImage.\" );\n // 8 bits each of red, green, blue, and alpha.\n [self setBytesPerRow:self.size.width * RGBA];\n [self setByteCount:bytesPerRow * self.size.height];\n [self setPixelCount:self.size.width * self.size.height];\n\n // Create RGB color space\n [self setColorSpace:CGColorSpaceCreateDeviceRGB()];\n\n if (!colorSpace)\n {\n NSLog(@\"Error allocating color space.\");\n return nil;\n }\n\n [self setPixelData:malloc(byteCount)];\n\n if (!pixelData)\n {\n NSLog(@\"Error allocating bitmap memory. Releasing color space.\");\n CGColorSpaceRelease(colorSpace);\n\n return nil;\n }\n\n // Create the bitmap context. \n // Pre-multiplied RGBA, 8-bits per component. \n // The source image format will be converted to the format specified here by CGBitmapContextCreate.\n [self setContext:CGBitmapContextCreate(\n (void*)pixelData,\n self.size.width,\n self.size.height,\n RGBA_8_BIT,\n bytesPerRow,\n colorSpace,\n kCGImageAlphaPremultipliedLast\n )];\n\n // Make sure we have our context\n if (!context) {\n free(pixelData);\n NSLog(@\"Context not created!\");\n }\n\n // Draw the image to the bitmap context. \n // The memory allocated for the context for rendering will then contain the raw image pixelData in the specified color space.\n CGRect rect = { { 0 , 0 }, { self.size.width, self.size.height } };\n\n CGContextDrawImage( context, rect, self.CGImage );\n\n // Now we can get a pointer to the image pixelData associated with the bitmap context.\n pixelData = (RGBAPixel*) CGBitmapContextGetData(context);\n\n return pixelData;\n}\n</code></pre></li>\n</ol>\n\n<hr>\n\n<h2>Read-Only Data (Previous information) - method 2:</h2>\n\n<hr>\n\n<p>Step 1. I declared a type for byte:</p>\n\n<pre><code> typedef unsigned char byte;\n</code></pre>\n\n<p>Step 2. I declared a struct to correspond to a pixel: </p>\n\n<pre><code> typedef struct RGBPixel{\n byte red;\n byte green;\n byte blue; \n } \nRGBPixel;\n</code></pre>\n\n<p>Step 3. I subclassed UIImageView and declared (with corresponding synthesized properties):</p>\n\n<pre><code>// Reference to Quartz CGImage for receiver (self) \nCFDataRef bitmapData; \n\n// Buffer holding raw pixel data copied from Quartz CGImage held in receiver (self) \nUInt8* pixelByteData;\n\n// A pointer to the first pixel element in an array \nRGBPixel* pixelData;\n</code></pre>\n\n<p>Step 4. Subclass code I put in a method named bitmap (to return the bitmap pixel data):</p>\n\n<pre><code>//Get the bitmap data from the receiver's CGImage (see UIImage docs) \n[self setBitmapData: CGDataProviderCopyData(CGImageGetDataProvider([self CGImage]))];\n\n//Create a buffer to store bitmap data (unitialized memory as long as the data) \n[self setPixelBitData:malloc(CFDataGetLength(bitmapData))];\n\n//Copy image data into allocated buffer \nCFDataGetBytes(bitmapData,CFRangeMake(0,CFDataGetLength(bitmapData)),pixelByteData);\n\n//Cast a pointer to the first element of pixelByteData \n//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). \npixelData = (RGBPixel*) pixelByteData;\n\n//Now you can access pixels by index: pixelData[ index ] \nNSLog(@\"Pixel data one red (%i), green (%i), blue (%i).\", pixelData[0].red, pixelData[0].green, pixelData[0].blue);\n\n//You can determine the desired index by multiplying row * column. \nreturn pixelData;\n</code></pre>\n\n<p>Step 5. I made an accessor method:</p>\n\n<pre><code>-(RGBPixel*)pixelDataForRow:(int)row column:(int)column{\n //Return a pointer to the pixel data\n return &pixelData[row * column]; \n}\n</code></pre>\n"
},
{
"answer_id": 10145308,
"author": "smdvlpr",
"author_id": 208113,
"author_profile": "https://Stackoverflow.com/users/208113",
"pm_score": 1,
"selected": false,
"text": "<p>Use <a href=\"https://github.com/unixpickle/ANImageBitmapRep\" rel=\"nofollow\">ANImageBitmapRep</a> which gives pixel-level access (read/write). </p>\n"
},
{
"answer_id": 12032147,
"author": "garafajon",
"author_id": 698967,
"author_profile": "https://Stackoverflow.com/users/698967",
"pm_score": 2,
"selected": false,
"text": "<p>Thanks everyone! Putting a few of these answers together I get:</p>\n\n<pre><code>- (UIColor*)colorFromImage:(UIImage*)image sampledAtPoint:(CGPoint)p {\n CGImageRef cgImage = [image CGImage];\n CGDataProviderRef provider = CGImageGetDataProvider(cgImage);\n CFDataRef bitmapData = CGDataProviderCopyData(provider);\n const UInt8* data = CFDataGetBytePtr(bitmapData);\n size_t bytesPerRow = CGImageGetBytesPerRow(cgImage);\n size_t width = CGImageGetWidth(cgImage);\n size_t height = CGImageGetHeight(cgImage);\n int col = p.x*(width-1);\n int row = p.y*(height-1);\n const UInt8* pixel = data + row*bytesPerRow+col*4;\n UIColor* returnColor = [UIColor colorWithRed:pixel[0]/255. green:pixel[1]/255. blue:pixel[2]/255. alpha:1.0];\n CFRelease(bitmapData);\n return returnColor;\n}\n</code></pre>\n\n<p>This just takes a point range 0.0-1.0 for both x and y. Example:</p>\n\n<pre><code>UIColor* sampledColor = [self colorFromImage:image\n sampledAtPoint:CGPointMake(p.x/imageView.frame.size.width,\n p.y/imageView.frame.size.height)];\n</code></pre>\n\n<p>This works great for me. I am making a couple assumptions like bits per pixel and RGBA colorspace, but this should work for most cases. </p>\n\n<p>Another note - it is working on both Simulator and device for me - I have had problems with that in the past because of the PNG optimization that happened when it went on the device.</p>\n"
},
{
"answer_id": 12059435,
"author": "Matej Bukovinski",
"author_id": 88854,
"author_profile": "https://Stackoverflow.com/users/88854",
"pm_score": 5,
"selected": false,
"text": "<p>Here is my solution for sampling color of an UIImage.</p>\n\n<p>This approach renders the requested pixel into a 1px large RGBA buffer and returns the resulting color values as an UIColor object. This is much faster than most other approaches I've seen and uses only very little memory. </p>\n\n<p>This should work pretty well for something like a color picker, where you typically only need the value of one specific pixel at a any given time. </p>\n\n<p><strong>Uiimage+Picker.h</strong></p>\n\n<pre><code>#import <UIKit/UIKit.h>\n\n\n@interface UIImage (Picker)\n\n- (UIColor *)colorAtPosition:(CGPoint)position;\n\n@end\n</code></pre>\n\n<p><strong>Uiimage+Picker.m</strong></p>\n\n<pre><code>#import \"UIImage+Picker.h\"\n\n\n@implementation UIImage (Picker)\n\n- (UIColor *)colorAtPosition:(CGPoint)position {\n\n CGRect sourceRect = CGRectMake(position.x, position.y, 1.f, 1.f);\n CGImageRef imageRef = CGImageCreateWithImageInRect(self.CGImage, sourceRect);\n\n CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();\n unsigned char *buffer = malloc(4);\n CGBitmapInfo bitmapInfo = kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big;\n CGContextRef context = CGBitmapContextCreate(buffer, 1, 1, 8, 4, colorSpace, bitmapInfo);\n CGColorSpaceRelease(colorSpace);\n CGContextDrawImage(context, CGRectMake(0.f, 0.f, 1.f, 1.f), imageRef);\n CGImageRelease(imageRef);\n CGContextRelease(context);\n\n CGFloat r = buffer[0] / 255.f;\n CGFloat g = buffer[1] / 255.f;\n CGFloat b = buffer[2] / 255.f;\n CGFloat a = buffer[3] / 255.f;\n\n free(buffer);\n\n return [UIColor colorWithRed:r green:g blue:b alpha:a];\n}\n\n@end \n</code></pre>\n"
}
]
| 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 (interposed with grep) is probably going to hurt the performance a great deal, though...</p>\n\n<pre><code>## perl code to do some dirty work\n\nfor my $line (`grep 'X Y Z' myhugefile`) {\n chomp $line;\n my ($a, $b, $c, $d, $e) = split(/ /,$line);\n my $cmd = 'grep -P \"' . $d . ' .+? ' . $e .'\" otherfile';\n for my $from_otherfile (`$cmd`) {\n chomp $from_otherfile;\n my ($oa, $ob, $oc, $od) = split(/ /,$from_otherfile);\n print \"$a $ob $oc\\n\";\n }\n}\n</code></pre>\n\n<p><strong>EDIT:</strong> Use tsee's solution (above), it's much more well-thought-out.</p>\n"
},
{
"answer_id": 147796,
"author": "tsee",
"author_id": 13164,
"author_profile": "https://Stackoverflow.com/users/13164",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>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:</p>\n\n<pre><code>#!/usr/bin/env perl -nwa\nuse strict;\nuse File::Find 'find';\nmy @search = qw(X Y Z);\n\n# if you know in advance that the otherfile isn't\n# huge, you can cache it in memory as an optimization.\n\n# with any more columns, you want a loop here:\nif ($F[0] eq $search[0]\n and $F[1] eq $search[1]\n and $F[2] eq $search[2])\n{\n my @files;\n find(sub {\n return if not -f $_;\n # verbatim search for the columns in the file name.\n # I'm still not sure what your file-search criteria are, though.\n push @files, $File::Find::name if /\\Q$F[3]\\E/ and /\\Q$F[4]\\E/;\n # alternatively search for the combination:\n #push @files, $File::Find::name if /\\Q$F[3]\\E.*\\Q$F[4]\\E/;\n # or search *all* files in the search path?\n #push @files, $File::Find::name;\n }, '/search/path'\n )\n foreach my $file (@files) {\n open my $fh, '<', $file or die \"Can't open file '$file': $!\";\n while (defined($_ = <$fh>)) {\n chomp;\n # order of fields doesn't matter per your requirement.\n my @cols = split ' ', $_;\n my %seen = map {($_=>1)} @cols;\n if ($seen{$F[3]} and $seen{$F[4]}) {\n print join(' ', $F[0], @cols[1,2]), \"\\n\";\n }\n }\n close $fh;\n }\n} # end if matching line\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 149725,
"author": "Tanktalus",
"author_id": 23512,
"author_profile": "https://Stackoverflow.com/users/23512",
"pm_score": 1,
"selected": false,
"text": "<p>This is the type of work that got me to move from awk to perl in the first place. If you are going to accomplish this, you may actually find it easier to create a shell script that creates awk script(s) to query and then update in separate steps.</p>\n\n<p>(I've written such a beast for reading/updating windows-ini-style files - it's ugly. I wish I could have used perl.)</p>\n"
},
{
"answer_id": 152070,
"author": "Corion",
"author_id": 11253,
"author_profile": "https://Stackoverflow.com/users/11253",
"pm_score": 1,
"selected": false,
"text": "<p>I often see the restriction \"I can't use any Perl modules\", and when it's not a homework question, it's often just due to a lack of information. <a href=\"http://perlmonks.org/?node_id=693828\" rel=\"nofollow noreferrer\">Yes, even you can use CPAN</a> contains the instructions on how to install CPAN modules locally without having root privileges. Another alternative is just to take the source code of a CPAN module and paste it into your program.</p>\n\n<p>None of this helps if there are other, unstated, restrictions, like lack of disk space that prevent installation of (too many) additional files.</p>\n"
}
]
| 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 [email protected] 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 "[email protected]" 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=\"http://www.antlr.org/\" rel=\"noreferrer\">ANTLR</a> isn't that hard to pickup and I think it is worthing looking into based on your problem.</strong> 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.</p>\n\n<p>You'll find ANTLR in many places including Eclipse, Groovy, and Grails for a start. <a href=\"https://rads.stackoverflow.com/amzn/click/com/0978739256\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">The Definitive ANTLR Reference</a> even makes it fairly straightforward to get up to speed on the basic fairly quickly.</p>\n\n<p>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.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 144863,
"author": "Fabian Steeg",
"author_id": 18154,
"author_profile": "https://Stackoverflow.com/users/18154",
"pm_score": 3,
"selected": false,
"text": "<p>You might want to consider <a href=\"http://wiki.eclipse.org/Xtext\" rel=\"noreferrer\">Xtext</a>, which internally uses ANTLR and does some nice things like auto-generating an editor for your DSL.</p>\n"
},
{
"answer_id": 144925,
"author": "Alex Miller",
"author_id": 7671,
"author_profile": "https://Stackoverflow.com/users/7671",
"pm_score": 1,
"selected": false,
"text": "<p>You might find this multi-part blog series I did on using Antlr to be useful as a starting point. It uses Antlr 2, so some stuff will be different for Antlr 3:</p>\n\n<p><a href=\"http://tech.puredanger.com/2007/01/13/implementing-a-scripting-language-with-antlr-part-1-lexer/\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/2007/01/13/implementing-a-scripting-language-with-antlr-part-1-lexer/</a></p>\n\n<p>Mark Volkman's presentations/articles on Antlr are quite helpful as well:</p>\n\n<p><a href=\"http://www.ociweb.com/mark/programming/ANTLR3.html\" rel=\"nofollow noreferrer\">http://www.ociweb.com/mark/programming/ANTLR3.html</a></p>\n\n<p>I will second the suggestion about the Definitive ANTLR book, which is also excellent.</p>\n"
},
{
"answer_id": 485961,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 2,
"selected": false,
"text": "<p>The first time I heard of DSL was from Jetbrains, the creator of IntellJ Idea.</p>\n\n<p>They have this tool: <a href=\"http://www.jetbrains.com/mps/\" rel=\"nofollow noreferrer\">MPS ( Meta Programming System )</a></p>\n"
},
{
"answer_id": 681060,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>\"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>\n\n<p>What you are talking about here sounds exactly like the tool, FitNesse.\nExactly as you describe, clients write acceptance tests \"scripts\" in some kind of language that makese sense to them, and programmers build systems that make the tests pass. Even the implementation you talk about is pretty much exactly how FitNesse works - the vocabulary used in the scripts are concatenated to form function names etc, so that the FitNesse framework knows what function to call.</p>\n\n<p>Anyway, check it out :)</p>\n"
},
{
"answer_id": 681109,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 3,
"selected": false,
"text": "<p>If you call that \"natural language\", you're deluding yourself. It's still a programming language, just one that tries to mimic natural language - and I suspect that it will fail once you get into implementation details. In order to make in unambiguous, you'll have to put restrictions on the syntax that will confuse the users who've been led to think that they're writing \"English\".</p>\n\n<p>The advantage of a DSL is (or should be, at any rate) is that it's simple and clear, yet powerful in regard to the problem domain. Mimicking a natural language is a secondary concern, and may in fact be counter-productive to those primary goals.</p>\n\n<p>If someone is too stupid or lacks the ability for formally rigorous thinking that's required for programming, then a programming language that mimicks a natural one will NOT magically turn them into a programmer.</p>\n\n<p>When COBOL was invented, some people seriously believed that within 10 years there would be zero demand for professional programmers, since COBOL was \"like English\", and anyone who needed software could write it himself. And we all know how that's been working out.</p>\n"
}
]
| 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 [email protected] 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 "[email protected]" 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/developing_with_web_standards/csslayout/2-col/\" rel=\"nofollow noreferrer\">simple implementation here</a>. And you can find a bit more detailed <a href=\"http://www.lissaexplains.com/css3.shtml\" rel=\"nofollow noreferrer\">article here</a></p>\n"
},
{
"answer_id": 144384,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>I think you could do something like this.</p>\n\n\n\n<pre class=\"lang-css prettyprint-override\"><code>div#col2 {\n padding-left: 160px;\n width: 100%;\n}\n\ndiv#col1 {\n float: left;\n width: 160px;\n}\n</code></pre>\n\n<p>This relies on <code>#col1</code> coming before <code>#col2</code>, which might make it unusable. </p>\n\n<p>This will not, but relies on <code>#col1</code> being the longer:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#content {\n position: relative; \n}\ndiv#col2 {\n width: 160px;\n position: absolute;\n}\n\ndiv#col1 {\n width: 100%;\n margin-left: 160px;\n}\n</code></pre>\n\n<p>This'll keep the footer in place.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div#footer {\n clear: both;\n}\n</code></pre>\n"
},
{
"answer_id": 144391,
"author": "MattBelanger",
"author_id": 655,
"author_profile": "https://Stackoverflow.com/users/655",
"pm_score": 1,
"selected": false,
"text": "<p>Neither of the above will work.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div#col2 {\n width: 160px;\n float: left;\n position: relative;\n}\n\ndiv#col1 {\n width:100%;\n margin-left: 160px;\n}\n</code></pre>\n\n<p>That's assuming that Column 2 should appear as a left sidebar, with col 1 as the main content.</p>\n"
},
{
"answer_id": 15767907,
"author": "Muchomasquewebs",
"author_id": 2236689,
"author_profile": "https://Stackoverflow.com/users/2236689",
"pm_score": 0,
"selected": false,
"text": "<p>You have to use float:left on first column and float:right on the second column</p>\n"
},
{
"answer_id": 34469081,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "<p>Although the question is for years ago, I provide this useful answer for any future reference and similar cases.</p>\n\n<p>Putting <code>#col1</code> before <code>#col2</code> in markup, you may float it to the right, in case you have LTR lauout (if you have an RTL layout then float to the left) and give the other col <code>overflow: hidden</code>.</p>\n\n<p>Note that the parent ( <code>#content</code> ) should have the <code>overflow: hidden</code> too:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#content{\r\n overflow: hidden;\r\n padding: 20px 0;\r\n height: 100px;\r\n background-color: #cdeecd;\r\n}\r\n\r\n#content #col1{\r\n float: right;\r\n width: 160px;\r\n height: 100px;\r\n background-color: #eecdcd;\r\n}\r\n\r\n#content #col2{\r\n height: 100px;\r\n overflow: hidden;\r\n background-color: #cdcdee;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"content\">\r\n <div id=\"col1\"></div>\r\n <div id=\"col2\"></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 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/developing_with_web_standards/csslayout/2-col/\" rel=\"nofollow noreferrer\">simple implementation here</a>. And you can find a bit more detailed <a href=\"http://www.lissaexplains.com/css3.shtml\" rel=\"nofollow noreferrer\">article here</a></p>\n"
},
{
"answer_id": 144384,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>I think you could do something like this.</p>\n\n\n\n<pre class=\"lang-css prettyprint-override\"><code>div#col2 {\n padding-left: 160px;\n width: 100%;\n}\n\ndiv#col1 {\n float: left;\n width: 160px;\n}\n</code></pre>\n\n<p>This relies on <code>#col1</code> coming before <code>#col2</code>, which might make it unusable. </p>\n\n<p>This will not, but relies on <code>#col1</code> being the longer:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>#content {\n position: relative; \n}\ndiv#col2 {\n width: 160px;\n position: absolute;\n}\n\ndiv#col1 {\n width: 100%;\n margin-left: 160px;\n}\n</code></pre>\n\n<p>This'll keep the footer in place.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div#footer {\n clear: both;\n}\n</code></pre>\n"
},
{
"answer_id": 144391,
"author": "MattBelanger",
"author_id": 655,
"author_profile": "https://Stackoverflow.com/users/655",
"pm_score": 1,
"selected": false,
"text": "<p>Neither of the above will work.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>div#col2 {\n width: 160px;\n float: left;\n position: relative;\n}\n\ndiv#col1 {\n width:100%;\n margin-left: 160px;\n}\n</code></pre>\n\n<p>That's assuming that Column 2 should appear as a left sidebar, with col 1 as the main content.</p>\n"
},
{
"answer_id": 15767907,
"author": "Muchomasquewebs",
"author_id": 2236689,
"author_profile": "https://Stackoverflow.com/users/2236689",
"pm_score": 0,
"selected": false,
"text": "<p>You have to use float:left on first column and float:right on the second column</p>\n"
},
{
"answer_id": 34469081,
"author": "Peyman Mohamadpour",
"author_id": 5104596,
"author_profile": "https://Stackoverflow.com/users/5104596",
"pm_score": 0,
"selected": false,
"text": "<p>Although the question is for years ago, I provide this useful answer for any future reference and similar cases.</p>\n\n<p>Putting <code>#col1</code> before <code>#col2</code> in markup, you may float it to the right, in case you have LTR lauout (if you have an RTL layout then float to the left) and give the other col <code>overflow: hidden</code>.</p>\n\n<p>Note that the parent ( <code>#content</code> ) should have the <code>overflow: hidden</code> too:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#content{\r\n overflow: hidden;\r\n padding: 20px 0;\r\n height: 100px;\r\n background-color: #cdeecd;\r\n}\r\n\r\n#content #col1{\r\n float: right;\r\n width: 160px;\r\n height: 100px;\r\n background-color: #eecdcd;\r\n}\r\n\r\n#content #col2{\r\n height: 100px;\r\n overflow: hidden;\r\n background-color: #cdcdee;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"content\">\r\n <div id=\"col1\"></div>\r\n <div id=\"col2\"></div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 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 keyword. Will make it easy to write a function that just calls Path.Combine the appropriate number of times, like this (untested):</p>\n\n<pre><code>string CombinePaths(params string[] parts) {\n string result = String.Empty;\n foreach (string s in parts) {\n result = Path.Combine(result, s);\n }\n return result;\n}\n</code></pre>\n"
},
{
"answer_id": 144449,
"author": "Seb Nilsson",
"author_id": 2429,
"author_profile": "https://Stackoverflow.com/users/2429",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one:</p>\n\n<pre><code>public static string CreateDirectoryName(string fileName, params string[] folders)\n{\n if(folders == null || folders.Length <= 0)\n {\n return fileName;\n }\n\n string directory = string.Empty;\n foreach(string folder in folders)\n {\n directory = System.IO.Path.Combine(directory, folder);\n }\n directory = System.IO.Path.Combine(directory, fileName);\n\n return directory;\n}\n</code></pre>\n\n<p>The params makes it so that you can append an infinite amount of strings.</p>\n\n<p>Path.Combine does is to make sure that the inputted strings does not begin with or ends with slashes and checks for any invalid characters.</p>\n"
},
{
"answer_id": 144577,
"author": "Jason Jackson",
"author_id": 13103,
"author_profile": "https://Stackoverflow.com/users/13103",
"pm_score": 3,
"selected": false,
"text": "<p>LINQ to the rescue again. The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate\" rel=\"nofollow noreferrer\">Aggregate</a> extension function can be used to accomplish what you want. Consider this example:</p>\n\n<pre><code>string[] ary = new string[] { \"c:\\\\\", \"Windows\", \"System\" };\nstring path = ary.Aggregate((aggregation, val) => Path.Combine(aggregation, val));\nConsole.WriteLine(path); //outputs c:\\Windows\\System\n</code></pre>\n"
},
{
"answer_id": 144587,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer to use DirectoryInfo vs. the static methods on Directory, because I think it's better OO design. Here's a solution with DirectoryInfo + extension methods, that I think is quite nice to use:</p>\n\n<pre><code> public static DirectoryInfo Subdirectory(this DirectoryInfo self, params string[] subdirectoryName)\n {\n Array.ForEach(\n subdirectoryName, \n sn => self = new DirectoryInfo(Path.Combine(self.FullName, sn))\n );\n return self;\n }\n</code></pre>\n\n<p>I don't love the fact that I'm modifying <code>self</code>, but for this short method, I think it's cleaner than making a new variable.</p>\n\n<p>The call site makes up for it, though:</p>\n\n<pre><code> DirectoryInfo di = new DirectoryInfo(\"C:\\\\\")\n .Subdirectory(\"Windows\")\n .Subdirectory(\"System32\");\n\n DirectoryInfo di2 = new DirectoryInfo(\"C:\\\\\")\n .Subdirectory(\"Windows\", \"System32\");\n</code></pre>\n\n<p>Adding a way to get a FileInfo is left as an exercise (for another SO question!).</p>\n"
}
]
| 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>, which are keyed by just about anything. <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/HashMap.html\" rel=\"nofollow noreferrer\">HashMap</a>s work in most cases. </p>\n\n<p>Something like this.</p>\n\n<pre><code>List<String> col1Vals = new java.util.ArrayList<String>();\ncol1Vals.add(\"col_value_1\");\ncol1Vals.add(\"col_value_2\");\nMap<String, List<String>> map = new HashMap<String, List<String>>();\nmap.put(\"col_name_1\", col1Vals);\n</code></pre>\n\n<p>If you want something simpler, the <a href=\"http://commons.apache.org/collections/\" rel=\"nofollow noreferrer\">commons-lang</a> library has a <a href=\"http://commons.apache.org/collections/api-release/org/apache/commons/collections/MultiMap.html\" rel=\"nofollow noreferrer\">MultiMap</a>.</p>\n"
},
{
"answer_id": 144486,
"author": "Dave L.",
"author_id": 3093,
"author_profile": "https://Stackoverflow.com/users/3093",
"pm_score": 4,
"selected": false,
"text": "<p>Try using a <code>Map<String, List<String>></code>. This will allow you to use Strings as keys / indices into the outer map and get a result being a list of Strings as values. You'll probably want to use a <code>HashMap</code> for the outer map and <code>ArrayList</code>'s for the inner lists.</p>\n\n<p>If you want some clean code that is similar to the PHP you gave to initialize it, you can do something like this:</p>\n\n<pre><code>Map<String, List<String>> columns = new HashMap<String, List<String>>() {{\n put(\"col_name_1\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n put(\"col_name_2\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n put(\"col_name_n\", Arrays.asList(\"col_val_1\", \"col_val_2\", \"col_val_n\"));\n}};\n</code></pre>\n"
},
{
"answer_id": 144499,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 5,
"selected": true,
"text": "<p>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). </p>\n\n<p>For more information check the tutorials for <a href=\"http://java.sun.com/docs/books/tutorial/collections/interfaces/map.html\" rel=\"noreferrer\">Map</a> and <a href=\"http://java.sun.com/docs/books/tutorial/collections/interfaces/list.html\" rel=\"noreferrer\">List</a> and maybe you should start with the <a href=\"http://java.sun.com/docs/books/tutorial/collections/\" rel=\"noreferrer\">Collections</a> tutorial.</p>\n\n<p>An example:</p>\n\n<pre><code>import java.util.*;\n\npublic class Foo {\n public static void main(String[] args) {\n Map<String, List<String>> m = new HashMap<String, List<String>>();\n List<String> l = new LinkedList<String>();\n l.add(\"col_value_1\");\n l.add(\"col_value_2\");\n //and so on\n m.put(\"col_name_1\",l); //repeat for the rest of the colnames\n\n //then, to get it you do\n\n List<String> rl = m.get(\"col_name_1\");\n\n }\n}\n</code></pre>\n"
},
{
"answer_id": 145105,
"author": "Alan",
"author_id": 17205,
"author_profile": "https://Stackoverflow.com/users/17205",
"pm_score": 2,
"selected": false,
"text": "<p>Be forewarned that the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/Vector.html\" rel=\"nofollow noreferrer\">Vector</a> is legacy code for the Collections framework. It synchronizes access to its elements which slows down performance. Most use cases for using List don't need this kind of thread safety, and even if you did, I would be more inclined to use the <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/concurrent/CopyOnWriteArrayList.html\" rel=\"nofollow noreferrer\">CopyOnWriteArrayList</a>.</p>\n"
}
]
| 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\">repository pattern</a> for my DAO and I'm quite happy with it. Yes you end up with quite a few small classes, but it's very maintainable. It's a bit more powerful if you use the <code>IQueriable</code> interface (LINQ.) You could also use generics (Something like <code>T GetById<T>(int id)</code>) if you have a pretty consistent database structure.</p>\n"
},
{
"answer_id": 144541,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 2,
"selected": false,
"text": "<p>I work in PHP, but I have something similar set up for my data access layer. I have implemented an interface that looks something like this:</p>\n\n<pre><code>interface DataAccessObject\n{\npublic static function get(array $filters = array(), array $order = array(), array $limit = array());\npublic function insert();\npublic function update(); \npublic function delete();\n}\n</code></pre>\n\n<p>And then each of my data access objects work something like this:</p>\n\n<pre><code>class DataAccessObject implements DataAccessObject\n{\n public function __construct($dao_id = null) // So you can construct an empty object\n {\n // Some Code that get the values from the database and assigns them as properties\n }\n public static function get(array $filters = array(), array $order = array(), array $limit = array()) {}; // Code to implement function\n public function insert() {}; // Code to implement function\n public function update() {}; // Code to implement function \n public function delete() {}; // Code to implement function \n}\n</code></pre>\n\n<p>I am currently building each of the data access object classes manually so when I add a table or modify an existing table in the database, obviously I have to write the new code by hand. In my case, this is still a huge step up from where our code base was. </p>\n\n<p>However, you can also use the SQL metadata (assuming that you've got a fairly sound database design that takes advantage of foreign key constraints and the like) to generate these data access objects. Then in theory, you could use a single parent DataAccessObject class to construct the properties and methods of the class and even build relationships to the other tables in the database automatically. This would more or less accomplish the same thing that you're describing because then you could extend the DataAccessObject class to provide custom methods and properties for situations that require some amount of manually constructed code.</p>\n\n<p>As a sidenote for .NET development, have you looked at a framework that handles the underlying structure of the data access layer for you, such as Subsonic? If not, I would recommend looking into just such a framework: <a href=\"http://subsonicproject.com/\" rel=\"nofollow noreferrer\">http://subsonicproject.com/</a>. </p>\n\n<p>Or for PHP development, a framework such as Zend Framework would provide similar functionality: <a href=\"http://framework.zend.com\" rel=\"nofollow noreferrer\">http://framework.zend.com</a></p>\n"
},
{
"answer_id": 148410,
"author": "Owen",
"author_id": 425,
"author_profile": "https://Stackoverflow.com/users/425",
"pm_score": 2,
"selected": false,
"text": "<p>George I know exactly how you feel. Billy's architecture makes sense to me but the need to create a container, Imapper and mapper files are painfull. Then if you are using NHibernate the corrosponding .hbm file and usually a few unit test scripts to check everythings working. </p>\n\n<p>I assume that even though your not using NHibernate your still using a generic base class lo load/save your containers i.e. </p>\n\n<pre><code>public class BaseDAO<T> : IDAO<T> \n{\n public T Save(T entity)\n { \n //etc......\n }\n}\npublic class YourDAO : BaseDAO<YourEntity>\n{\n}\n</code></pre>\n\n<p>I guess that without NHibernate you'd be using reflection or some other machanism to determine what SQL/SPROC to call?</p>\n\n<p>Eitherway, my thought on this would be where DAO only need to perform the basic CRUD operations defined in the base class then there should be no need to write custom mappers and interfaces. The only way I can think of achiving this is to use Reflection.Emit to dynamically create your DAO on the fly. </p>\n"
},
{
"answer_id": 148432,
"author": "ARKBAN",
"author_id": 11889,
"author_profile": "https://Stackoverflow.com/users/11889",
"pm_score": 0,
"selected": false,
"text": "<p>The main draw back to the second approach is in unit testing -- mocking out big factory methods like your SimpleObjectRepository requires more work than mocking out just ICustomerDao. But, my project goes with the second approach for highly related objects (where most will be used in any unit tests) because it lightens the mental load and makes it more maintainable. </p>\n\n<p>I'd figure out what makes your system more maintainable and easy to understand and do that.</p>\n"
},
{
"answer_id": 236673,
"author": "Colin Jack",
"author_id": 7252,
"author_profile": "https://Stackoverflow.com/users/7252",
"pm_score": 3,
"selected": true,
"text": "<p>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. </p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Hope this helps.</p>\n"
}
]
| 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 the data to another system, I'd go with the IDictionary because it makes using your interface more flexible.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 144527,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>(Assuming .NET 3.5 here. Pre .NET 3.5, NameValueCollection would have the benefit of being able to tie multiple values to a key, with no direct equivalent in \"normal\" collections.)</p>\n\n<p>Do you want keys to have potentially multiple values? If so, I'd consider ILookup<TKey, TValue>. Otherwise, I'd go for IDictionary<TKey, TValue>.</p>\n\n<p>Aside from anything else, if the receiver wants to do any processing where LINQ would be of use to them, either of the generic interfaces is going to be nicer than NameValuePair. Likewise, it may be easier for the caller to produce a dictionary/lookup using LINQ if they've already got a generic or dynamic kind of context.</p>\n"
}
]
| 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>\n\n<p>You could append the ingrediant name to the join conditions which may be quicker.</p>\n\n<p>You could also hash combinations of ingredients for receipes for a quick lookup.</p>\n"
},
{
"answer_id": 144602,
"author": "Michael Brown",
"author_id": 14359,
"author_profile": "https://Stackoverflow.com/users/14359",
"pm_score": 4,
"selected": true,
"text": "<p>You have two options. If you're using SQL Server 2008 (or Oracle) you can pass in a <a href=\"http://www.sqlteam.com/article/sql-server-2008-table-valued-parameters\" rel=\"nofollow noreferrer\">table value parameter</a>. </p>\n\n<p>If you're using SQL Server 2005, you can use <a href=\"http://weblogs.asp.net/jgalloway/archive/2007/02/16/passing-lists-to-sql-server-2005-with-xml-parameters.aspx\" rel=\"nofollow noreferrer\">XML to simulate this capability</a></p>\n\n<p>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.</p>\n"
},
{
"answer_id": 144626,
"author": "albertein",
"author_id": 23020,
"author_profile": "https://Stackoverflow.com/users/23020",
"pm_score": 2,
"selected": false,
"text": "<p>You could at least parametrize the where clausule to avoid SQL injection, something alike:</p>\n\n<pre><code>using System.Data;\nusing System.Data.SqlClient;\nusing System.Text;\n\nclass Foo\n{\n public static void Main ()\n {\n string[] parameters = {\"salt\", \"water\", \"flower\"};\n SqlConnection connection = new SqlConnection ();\n SqlCommand command = connection.CreateCommand ();\n StringBuilder where = new StringBuilder ();\n for (int i = 0; i < parametes.Length; i++)\n {\n if (i != 0)\n where.Append (\",\");\n where.AppendFormat (\"@Param{0}\", i);\n command.Parameters.Add (new SqlParameter (\"Param\" + i, parameters [i]));\n }\n }\n}\n</code></pre>\n"
}
]
| 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 types available from System.Collections.Generic or System.Collections.ComponentModel.</p>\n"
},
{
"answer_id": 144575,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": true,
"text": "<p><code>List<T></code> was introduced with generics in .NET 2.0:</p>\n\n<pre><code>using System.Collections.Generic;\n\nvar list = new List<int>();\nlist.Add(1);\nlist.Add(\"string\"); //compile-time error!\nint i = list[0];\n</code></pre>\n"
},
{
"answer_id": 144595,
"author": "Mark",
"author_id": 18264,
"author_profile": "https://Stackoverflow.com/users/18264",
"pm_score": -1,
"selected": false,
"text": "<p>If you have to use ArrayList and can't start using List, and you know the type of every element in that ArrayList you can do:</p>\n\n<pre><code> string[] stringArray = myArrayList.ToArray(typeof(string)) as string[];\n</code></pre>\n\n<p>If something in myArrayList wasn't a string, in this case, you would get an InvalidCastException.</p>\n\n<p>If you can, I would start using List as OregonGhost mentioned.</p>\n"
}
]
| 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\n<p>See it like an alias :)</p>\n\n<p>Ofcourse, since you're asp.net/windows based, i think you'll have to digg deep into IIS to automate this kind of stuff. If you were on apache it would be adding 3 simple lines to httpd.conf.</p>\n"
},
{
"answer_id": 144704,
"author": "sfg",
"author_id": 19830,
"author_profile": "https://Stackoverflow.com/users/19830",
"pm_score": 1,
"selected": false,
"text": "<p>Smugmug (who you mentioned) get their users to setup a CNAME record that will alias the url for the user's personal photo section. For most users this will probably require them contacting their host or looking up help files in order to get it all setup.</p>\n\n<p>So, while www.tomsite.com could transparently serve up pages hosted at www.mywebapp.com the users will have to put some kind of effort in. To make it a completely seamless you will need some kind of arrangement with the users web host (Smugmug appear to have such an arrangement with GoDaddy). </p>\n\n<p>I doubt you will be able to setup such integration with all the web hosts out there, so the only complete solution would be to host the websites of your users yourself (I do not know enough about your wider situation to determine if that is a reasonable solution).</p>\n\n<p>Note: setting up an alias on your own web server (aka url rewriting) will not work, unless you host their site yourself, as obviously people fetching from your user's domain will not arrive at your server in the first place.</p>\n"
},
{
"answer_id": 144714,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 1,
"selected": false,
"text": "<p>Have each customer's friendlyname pointed at the external ip address of your webserver.</p>\n\n<p>Use IIS to resolve the friendlyname specified in the host header request to the logical website you want delivered to that friendlyname. IIS will happily map both a website and a virtual folder to the same folder in the file system. Create a website for each customer. Then bind that website to the customer's friendlyname. </p>\n\n<p>Remember to map the default website only to your own friendlyname(s). If you leave it in promiscuous mode (mapped to \"*\") results will be unpredictable.</p>\n\n<h2>To set host header mapping</h2>\n\n<p>Select <em>Default Web Site</em> under the <em>Sites</em> node. In the <em>Actions</em> pane at top right click on <em>Bindings...</em> to open the <em>Site Bindings</em> dialog. There will be a list of bindings, probably containing a single entry that says http * 80. Select this and click the <em>Edit...</em> button. Set <em>Host name</em> to your own friendlyname.</p>\n\n<p>Run <em>IIS7 Manager</em> and for each customer site create a website under the <em>Sites</em> node. Set both file path and host header binding while you are creating each web site. Obviously the host header binding (host name) should be that customer's friendlyname.</p>\n"
},
{
"answer_id": 145544,
"author": "Troels Thomsen",
"author_id": 20138,
"author_profile": "https://Stackoverflow.com/users/20138",
"pm_score": 3,
"selected": true,
"text": "<p>This require multiple steps.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>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).</p>\n\n<pre><code>if (Dns.GetHostEntry(\"www.user.example.com\").HostName == \"www.example.com\")\n{\n // www.user.example.com is a CNAME for www.example.com\n}\n</code></pre>\n\n<p>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.</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.</p>\n\n<pre><code>\\bibliographystyle{unsrt}\n\\bibliography{bibliography}\n</code></pre>\n\n<p>However what if my style is not the default?</p>\n"
},
{
"answer_id": 144665,
"author": "lindelof",
"author_id": 1428,
"author_profile": "https://Stackoverflow.com/users/1428",
"pm_score": 4,
"selected": false,
"text": "<p>You answered your own question---<code>unsrt</code> is to be used when you want references to ne listed in the order of appeareance.</p>\n\n<p>But you might also want to have a look at <a href=\"http://www.ctan.org/tex-archive/help/Catalogue/entries/natbib.html\" rel=\"noreferrer\">natbib</a>, an extremely flexible citation package. I can not imagine living without it.</p>\n"
},
{
"answer_id": 145207,
"author": "Will Robertson",
"author_id": 4161,
"author_profile": "https://Stackoverflow.com/users/4161",
"pm_score": 9,
"selected": true,
"text": "<p>There are three good answers to this question.</p>\n<ul>\n<li>Use the <code>unsrt</code> bibliography style, if you're happy with its formatting otherwise</li>\n<li>Use the <code>makebst</code> <a href=\"http://www.ctan.org/tex-archive/macros/latex/contrib/custom-bib/\" rel=\"noreferrer\">(link)</a> tool to design your own bibliography style</li>\n</ul>\n<p>And my personal recommendation:</p>\n<ul>\n<li>Use the <code>biblatex</code> package <a href=\"https://ctan.org/pkg/biblatex\" rel=\"noreferrer\">(link)</a>. It's the most complete and flexible bibliography tool in the LaTeX world.</li>\n</ul>\n<p>Using <code>biblatex</code>, you'd write something like</p>\n<pre><code>\\documentclass[12pt]{article}\n\\usepackage[sorting=none]{biblatex}\n\\bibliography{journals,phd-references} % Where journals.bib and phd-references.bib are BibTeX databases\n\\begin{document}\n\\cite{robertson2007}\n\\cite{earnshaw1842}\n\\printbibliography\n\\end{document}\n</code></pre>\n"
},
{
"answer_id": 790387,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>with <code>unsrt</code> the problem is the format. use <code>\\bibliographystyle{ieeetr}</code> to get refences in order of citation in document.</p>\n"
},
{
"answer_id": 1514189,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 8,
"selected": false,
"text": "<p>Change </p>\n\n<pre><code>\\bibliographystyle{plain}\n</code></pre>\n\n<p>to</p>\n\n<pre><code>\\bibliographystyle{ieeetr}\n</code></pre>\n\n<p>Then rebuild it a few times to replace the <code>.aux</code> and <code>.bbl</code> files that were made when you used the plain style.</p>\n\n<p>Or simply delete the <code>.aux</code> and <code>.bbl</code> files and rebuild.</p>\n\n<p>If you use MiKTeX you shouldn't need to download anything extra.</p>\n"
},
{
"answer_id": 6562312,
"author": "sdaau",
"author_id": 277826,
"author_profile": "https://Stackoverflow.com/users/277826",
"pm_score": 5,
"selected": false,
"text": "<p>Just a brief note - I'm using a modified version of <a href=\"http://gallium.inria.fr/~remy/latex/plain.bst\" rel=\"noreferrer\">plain.bst</a> sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code: </p>\n\n<pre><code>...\nITERATE {presort}\n\nSORT\n...\n</code></pre>\n\n<p>... and comment it - I turned it to: </p>\n\n<pre><code>...\n%% % avoid sort:\n%% ITERATE {presort}\n%%\n%% SORT\n...\n</code></pre>\n\n<p>... and then, after running <code>bibtex</code>, <code>pdflatex</code>, <code>pdflatex</code> - the citations will be sorted by order of appearance (that is, they will be unsorted :) ). </p>\n\n<p>Cheers!</p>\n\n<p>EDIT: just realized that what I wrote is actually in the comment by @ChrisN: \"<em>can you edit it to remove the SORT command</em>\" ;) </p>\n"
},
{
"answer_id": 13630446,
"author": "Tung",
"author_id": 865603,
"author_profile": "https://Stackoverflow.com/users/865603",
"pm_score": 2,
"selected": false,
"text": "<p>I often use the bibliography style <code>natbib</code> because it supplies quite complete set of formats as well as tags for us.</p>\n"
},
{
"answer_id": 16787602,
"author": "kebs",
"author_id": 193789,
"author_profile": "https://Stackoverflow.com/users/193789",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://ctan.org/pkg/datatool\" rel=\"nofollow\">datatool</a> package offers a nice way to sort bibliography by an arbitrary criterion, by converting it first into some database format.</p>\n\n<p>Short example, taken <a href=\"http://www.latex-community.org/forum/viewtopic.php?f=50&t=20461\" rel=\"nofollow\">from here</a> and posted for the record:</p>\n\n<pre><code>\\documentclass{article}\n\n\\usepackage{databib}\n\n\\begin{document}\n% First argument is the name of new datatool database\n% Second argument is list of .bib files\n\\DTLloadbbl{mybibdata}{acmtr}\n% Sort database in order of year starting from most recent\n\\DTLsort{Year=descending}{mybibdata}\n% Add citations\n\\nocite{*}\n\n% Display bibliography\n\\DTLbibliography{mybibdata}\n\\end{document}\n</code></pre>\n"
},
{
"answer_id": 18217511,
"author": "Guest",
"author_id": 2679929,
"author_profile": "https://Stackoverflow.com/users/2679929",
"pm_score": 1,
"selected": false,
"text": "<p>If you happen to be using <code>amsrefs</code> they will override all the above - so comment out:</p>\n\n<p><code>\\usepackage{amsrefs}</code></p>\n"
},
{
"answer_id": 25329083,
"author": "HeWhoLikesWaffles",
"author_id": 2796499,
"author_profile": "https://Stackoverflow.com/users/2796499",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a bit new to Bibtex (and to Latex in general) and I'd like to revive this old post since I found it came up in many of my Google search inquiries about the ordering of a bibliography in Latex.</p>\n\n<p>I'm providing a more verbose answer to this question in the hope that it might help some novices out there facing the same difficulties as me.</p>\n\n<p>Here is an example of the main .tex file in which the bibliography is called:</p>\n\n<pre><code>\\documentclass{article}\n\\begin{document}\n\nSo basically this is where the body of your document goes.\n\n``FreeBSD is easy to install,'' said no one ever \\cite{drugtrafficker88}.\n\n``Yeah well at least I've got chicken,'' said Leeroy Jenkins \\cite{goodenough04}.\n\n\\newpage\n\\bibliographystyle{ieeetr} % Use ieeetr to list refs in the order they're cited\n\\bibliography{references} % Or whatever your .bib file is called\n\\end{document}\n</code></pre>\n\n<p>...and an example of the .bib file itself:</p>\n\n<pre><code>@ARTICLE{ goodenough04,\nAUTHOR = \"G. D. Goodenough and others\", \nTITLE = \"What it's like to have a sick-nasty last name\",\nJOURNAL = \"IEEE Trans. Geosci. Rem. Sens.\",\nYEAR = \"xxxx\",\nvolume = \"xx\",\nnumber = \"xx\",\npages = \"xx--xx\"\n}\n@BOOK{ drugtrafficker88,\nAUTHOR = \"G. Drugtrafficker\", \nTITLE = \"What it's Like to Have a Misleading Last Name\",\nYEAR = \"xxxx\",\nPUBLISHER = \"Harcourt Brace Jovanovich, Inc.\"\nADDRESS = \"The Florida Alps, FL, USA\"\n}\n</code></pre>\n\n<p>Note the references in the .bib file are listed in reverse order but the references are listed in the order they are cited in the paper.</p>\n\n<p>More information on the formatting of your .bib file can be found here: <a href=\"http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management\" rel=\"noreferrer\">http://en.wikibooks.org/wiki/LaTeX/Bibliography_Management</a></p>\n"
},
{
"answer_id": 41662000,
"author": "Tshilidzi Mudau",
"author_id": 5695374,
"author_profile": "https://Stackoverflow.com/users/5695374",
"pm_score": 0,
"selected": false,
"text": "<p>I use <code>natbib</code> in combination with <code>bibliographystyle{apa}</code>. Eg: </p>\n\n<pre><code>\\begin{document}\n\nThe body of the document goes here...\n\n\\newpage\n\n\\bibliography{bibliography} % Or whatever you decided to call your .bib file \n\n\\usepackage[round, comma, sort&compress ]{natbib} \n\nbibliographystyle{apa}\n\\end{document}\n</code></pre>\n"
},
{
"answer_id": 59255825,
"author": "Malak",
"author_id": 10474966,
"author_profile": "https://Stackoverflow.com/users/10474966",
"pm_score": 2,
"selected": false,
"text": "<p>Add this if you want the number of citations to appear in order in the document\nthey will only be unsorted in the reference page:</p>\n\n<pre><code>\\bibliographystyle{unsrt}\n</code></pre>\n"
},
{
"answer_id": 68309810,
"author": "sepideha",
"author_id": 6762269,
"author_profile": "https://Stackoverflow.com/users/6762269",
"pm_score": 2,
"selected": false,
"text": "<p>I used the following in overleaf and become in ascending order:</p>\n<p><code>\\usepackage{cite}</code></p>\n<p><code>\\bibliographystyle{unsrt}</code></p>\n"
}
]
| 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-structure-in-c\">a similar question</a> last week and ended up implementing my own tree. My implementation was very similar to what you're proposing:</p>\n\n<pre><code>public class TreeNode<T>\n{\n private LinkedList<TreeNode<T>> children = new LinkedList<TreeNode<T>>();\n public T value { get; set; }\n\n public TreeNode(T value)\n {\n this.value = value;\n }\n public LinkedList<TreeNode<T>> GetChildren()\n {\n return children;\n }\n}\n</code></pre>\n\n<p>You will have to add a link back to the parent(s). </p>\n"
},
{
"answer_id": 144697,
"author": "Zach Scrivena",
"author_id": 20029,
"author_profile": "https://Stackoverflow.com/users/20029",
"pm_score": 1,
"selected": false,
"text": "<p>I'd say it's better to roll out your own implementation (besides, you've already got the interface nicely thought out). What are the operations you are planning to perform on this tree anyway? You'd probably want to design your API around the things you want... direct access to individual nodes by key/value? types of traversals? add/remove operations?</p>\n"
},
{
"answer_id": 144772,
"author": "flicken",
"author_id": 12880,
"author_profile": "https://Stackoverflow.com/users/12880",
"pm_score": 0,
"selected": false,
"text": "<p>If you're looking for additional graph capabilities, <a href=\"https://jdigraph.dev.java.net/\" rel=\"nofollow noreferrer\">JDigraph</a>'s <a href=\"https://jdigraph.dev.java.net/nonav/api/net/walend/digraph/Digraph.html\" rel=\"nofollow noreferrer\">Digraph</a> class should fit the bill. </p>\n"
},
{
"answer_id": 440852,
"author": "user10536",
"author_id": 10536,
"author_profile": "https://Stackoverflow.com/users/10536",
"pm_score": 3,
"selected": false,
"text": "<p>There's also <a href=\"http://www.jgrapht.org\" rel=\"noreferrer\">http://www.jgrapht.org</a>, which has software licensed under the LGPL. I have to warn you though, implementing your own is fraught with danger. If you plan on using recursion on your structure (which is a graph), you'll have to ensure that it's acyclic, or you'll run into infinite loop problems. Better to use third party code where they've already dealt with the issues.</p>\n"
}
]
| 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#rewriterule\" rel=\"nofollow noreferrer\">force redirect</a> (add the [R] option), then the browser will be using the /groupdetail.php URL and the relative links will work fine. However, that adds one redirect and makes the URLs less pretty.</p>\n\n<pre><code>RewriteRule ^groups/([^/.]+)/?$ groupdetail.php?gname=$1 [L,NC,R]\n</code></pre>\n"
},
{
"answer_id": 155824,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Relative links are resolved by the browser, not the server, so there is nothing you can do with mod_rewrite.</p>\n\n<p>Either use relative links the go up the hierarchy (<code>../link.php</code>) or use absolute links.</p>\n"
},
{
"answer_id": 206759,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>If like me you had hundreds of relative links in the page, insert a <code><base href=\"\"></code> in the <code><head></code> with an absolute path (could use relative too). You'll need to also make the path to .js files in the <code><head></code> absolute because IE and firefox deal with the base href differently. I agree it is an annoying issue.</p>\n"
},
{
"answer_id": 609368,
"author": "Andy Swift",
"author_id": 72958,
"author_profile": "https://Stackoverflow.com/users/72958",
"pm_score": 0,
"selected": false,
"text": "<p>Hop's answer is correct. The browser sees <strong><code>www.example.com/groups/groupname</code></strong> as the address, so considers that <strong><code>/groups</code></strong> is the current directory. So, any links like <strong><code><a href=link.php></code></strong> are assumed to be in the <strong><code>/groups</code></strong> folder.</p>\n\n<p>When the user moves his mouse over the link, he'll see <strong><code>www.example.com/groups/link.php</code></strong> as the link address.</p>\n\n<p>The solution is to use absolute links -- just add a slash before the href:</p>\n\n<p><strong><code><a href=/link.php></code></strong></p>\n\n<p>The user will then see <strong><code>www.example.com/link.php</code></strong> as the url.</p>\n\n<p>That said, it seems from your question that you are using relative links on purpose... do you have a reason not to use absolute links?</p>\n"
},
{
"answer_id": 1980511,
"author": "Razvan",
"author_id": 240943,
"author_profile": "https://Stackoverflow.com/users/240943",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the BASE tag, if you don't want to use absolute paths:</p>\n\n<p><a href=\"http://www.w3schools.com/tags/tag_base.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/tags/tag_base.asp</a></p>\n"
},
{
"answer_id": 8336673,
"author": "Robin",
"author_id": 1074745,
"author_profile": "https://Stackoverflow.com/users/1074745",
"pm_score": 2,
"selected": false,
"text": "<p>If you do not want to have absolute links or use <code><base></code> because you are going to move the page around, you can have the base be generated by php, as following:</p>\n\n<pre><code>echo '<base href=\"http://'.$_SERVER['SERVER_NAME'].str_replace(\"index.php\",\"\",$_SERVER['PHP_SELF']).'\" />';\n</code></pre>\n"
}
]
| 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 StringHolder {\n private Long id;\n private String string;\n\n public StringHolder() {/* Not sure if this is necessary */}\n\n public StringHolder(String string) {\n this.string = string;\n }\n\n public void getString() {\n return this.string;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 144721,
"author": "Sam Martin",
"author_id": 19088,
"author_profile": "https://Stackoverflow.com/users/19088",
"pm_score": 1,
"selected": false,
"text": "<p>Building on sblundy's answer, you could probably get away with something like:</p>\n\n<pre><code>class Foo {\n // client code uses this to get the value... ignored by Hibernate\n @Transient\n public String getString() {\n return getStringHolder().getString();\n }\n\n public StringHolder getStringHolder() {...}\n}\n</code></pre>\n\n<p>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.</p>\n"
},
{
"answer_id": 173014,
"author": "Thilo",
"author_id": 14955,
"author_profile": "https://Stackoverflow.com/users/14955",
"pm_score": 0,
"selected": false,
"text": "<p>I believe you want to look at <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#mapping-types-custom\" rel=\"nofollow noreferrer\">custom value types</a>.\nThis should allow you to store your strings as integer ID in the database. Of course, you will have to provide the mapping/lookup yourself.</p>\n"
}
]
| 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 from the attic.</p>\n"
},
{
"answer_id": 145377,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 5,
"selected": false,
"text": "<p>I've found that you can not use <code>cvs add</code> to undo a <code>cvs remove</code> operation that has already been comitted. So this works:</p>\n\n<pre><code>$ cvs remove -f file.txt\n$ cvs add file.txt\n</code></pre>\n\n<p>but this doesn't work:</p>\n\n<pre><code>$ cvs remove -f file.txt\n$ cvs commit\n$ cvs add file.txt\n</code></pre>\n\n<hr>\n\n<p>The simplest method I've found so far is to run <code>cvs status file.txt</code> to find out the revision number. Then grab the contents of the revision and add it back in:</p>\n\n<pre><code>$ cvs update -p -r rev file.txt > file.txt\n$ cvs add file.txt\n$ cvs commit\n</code></pre>\n"
},
{
"answer_id": 145418,
"author": "Jason Etheridge",
"author_id": 2193,
"author_profile": "https://Stackoverflow.com/users/2193",
"pm_score": 2,
"selected": false,
"text": "<p>Given Harry's lack of success, here's a transcript of what I did to demonstrate that the above answer works (apologies in advance for its length):</p>\n\n<pre><code>C:\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\foo\n\n28/09/2008 05:12 PM <DIR> .\n28/09/2008 05:12 PM <DIR> ..\n28/09/2008 05:12 PM <DIR> CVS\n28/09/2008 05:11 PM 19 file.txt\n 1 File(s) 19 bytes\n 3 Dir(s) 22,686,416,896 bytes free\n\nC:\\foo>cvs status file.txt\n===================================================================\nFile: file.txt Status: Up-to-date\n\n Working revision: 1.2 Sun Sep 28 07:11:58 2008\n Repository revision: 1.2 C:\\jason\\CVSROOT/foo/file.txt,v\n Sticky Tag: (none)\n Sticky Date: (none)\n Sticky Options: (none)\n\n\nC:\\foo>cvs rm -f file.txt\ncvs remove: scheduling `file.txt' for removal\ncvs remove: use 'cvs commit' to remove this file permanently\n\nC:\\foo>cvs commit -m \"\" file.txt\nRemoving file.txt;\nC:\\jason\\CVSROOT/foo/file.txt,v <-- file.txt\nnew revision: delete; previous revision: 1.2\ndone\n\nC:\\foo>cvs status file.txt\n===================================================================\nFile: no file file.txt Status: Up-to-date\n\n Working revision: No entry for file.txt\n Repository revision: 1.3 C:\\jason\\CVSROOT/foo/Attic/file.txt,v\n\nC:\\foo>more file.txt\nCannot access file C:\\foo\\file.txt\n\nC:\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\foo\n\n28/09/2008 05:12 PM <DIR> .\n28/09/2008 05:12 PM <DIR> ..\n28/09/2008 05:12 PM <DIR> CVS\n 0 File(s) 0 bytes\n 3 Dir(s) 22,686,400,512 bytes free\n\nC:\\foo>cvs add file.txt\ncvs add: Resurrecting file `file.txt' from revision 1.2.\nU file.txt\ncvs add: Re-adding file `file.txt' (in place of dead revision 1.3).\ncvs add: use 'cvs commit' to add this file permanently\n\nC:\\foo>cvs commit -m \"\" file.txt\nChecking in file.txt;\nC:\\jason\\CVSROOT/foo/file.txt,v <-- file.txt\nnew revision: 1.4; previous revision: 1.3\ndone\n\nC:\\foo>more file.txt\nThis is a test...\n\nC:\\jason\\work\\dev1\\nrta\\foo>dir\n Volume in drive C is Local Disk\n Volume Serial Number is 344F-1517\n\n Directory of C:\\jason\\foo\n\n28/09/2008 05:15 PM <DIR> .\n28/09/2008 05:15 PM <DIR> ..\n28/09/2008 05:13 PM <DIR> CVS\n28/09/2008 05:13 PM 19 file.txt\n 1 File(s) 19 bytes\n 3 Dir(s) 22,686,375,936 bytes free\n</code></pre>\n\n<p>Clearly he's doing the right thing, but the behaviour he's observing is different. Perhaps there's a difference due to CVS version (I'm using 1.11.22 on Windows).</p>\n"
},
{
"answer_id": 145462,
"author": "Harry",
"author_id": 4704,
"author_profile": "https://Stackoverflow.com/users/4704",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>cvs add</code> did not work for me because my cvs version on the server was very old. I have confirmed that it works fine with CVS version 1.11.22.</p>\n"
},
{
"answer_id": 4205867,
"author": "Mike Glasspool",
"author_id": 510950,
"author_profile": "https://Stackoverflow.com/users/510950",
"pm_score": 0,
"selected": false,
"text": "<p>Here's what I do. I just create an empty file of the same name, then add and commit it, then retrieve the older version and re-commit that.</p>\n"
},
{
"answer_id": 11774387,
"author": "vvkatwss vvkatwss",
"author_id": 1150448,
"author_profile": "https://Stackoverflow.com/users/1150448",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>cvs add file.txt\ncvs update file.txt\ncvs commit file.txt\n</code></pre>\n"
},
{
"answer_id": 16084542,
"author": "Andy Page",
"author_id": 2295297,
"author_profile": "https://Stackoverflow.com/users/2295297",
"pm_score": 2,
"selected": false,
"text": "<p>cd into $CVSROOT directory and the relevant module directory and then the Attic, \nedit the fileOfInterest,v and change the line that says Dead; to Exp; and then move the fileOfInterest,v to the directory above.</p>\n\n<p>An update in the checked out module will now restore the file.</p>\n"
},
{
"answer_id": 21769866,
"author": "PKCLsoft",
"author_id": 880807,
"author_profile": "https://Stackoverflow.com/users/880807",
"pm_score": 1,
"selected": false,
"text": "<p>The simplest, though possible least elegant way to do this is to 'cd' into the CVS directory in the same place as the removed file.</p>\n\n<p>Then edit the file called \"Entries\".</p>\n\n<p>Find the line representing your removed file. Note that there is a '-' after the /</p>\n\n<p>Remove the '-', save the file and voila!</p>\n\n<p>Yuck, but it works.</p>\n"
}
]
| 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.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n</code></pre>\n\n<p>Also, be sure the <code>[STAThread]</code> attribute is declared above your <code>Main</code> function to indicate the COM threading model your Windows application will use (more about STAThread <a href=\"https://www.youtube.com/watch?v=S0jPzb9kk3o\" rel=\"noreferrer\">here</a>). </p>\n\n<p>Then right click your project and select properties and change the \"Output type\" to Windows application and you're done.</p>\n\n<p><strong>EDIT :</strong></p>\n\n<p>In VS2008 the property to change is Application type</p>\n\n<p><img src=\"https://i.stack.imgur.com/luhTN.jpg\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 699650,
"author": "dbruning",
"author_id": 84898,
"author_profile": "https://Stackoverflow.com/users/84898",
"pm_score": 5,
"selected": false,
"text": "<p>For completeness - and for other newbs like me - you also need to add:</p>\n\n<p>using System.Windows.Forms;</p>\n\n<p>... to the top of Program.cs</p>\n"
}
]
| 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-name()}\" namespace=\"A\" >\n <xsl:apply-templates />\n </xsl:element>\n</xsl:template>\n\n<xsl:template match=\"a-special-element\">\n <B:a-special-element xmlns:B=\"B\">\n <xsl:apply-templates />\n </B:a-special-element>\n</xsl:template>\n</code></pre>\n\n<p>This almost works; the problem is that it's not copying attributes. From what I've read thusfar, xsl:element doesn't have a way to copy all of the attributes from the element as-is (use-attribute-sets doesn't appear to cut it). </p>\n"
},
{
"answer_id": 144752,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 2,
"selected": false,
"text": "<p>You will need two main ingredients for this recipe.</p>\n\n<p>The sauce stock will be the <a href=\"http://www.w3.org/TR/xslt.html#copying\" rel=\"nofollow noreferrer\">identity transform</a>, and the main flavor will be given by the <code>namespace</code> attribute to <a href=\"http://www.w3.org/TR/xslt.html#section-Creating-Elements-with-xsl:element\" rel=\"nofollow noreferrer\"><code>xsl:element</code></a>.</p>\n\n<p>The following, untested code, should add the <a href=\"http://example.com/\" rel=\"nofollow noreferrer\">http://example.com/</a> namespace to all elements.</p>\n\n<pre><code><xsl:template match=\"*\">\n <xsl:element name=\"xmpl:{local-name()}\" namespace=\"http://example.com/\">\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:element>\n</xsl:template>\n\n<xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n</code></pre>\n\n<p>Personal message: Hello, Jeni Tennison. I know you are reading this.</p>\n"
},
{
"answer_id": 144775,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 5,
"selected": true,
"text": "<p>With foo.xml</p>\n\n<pre><code><foo x=\"1\">\n <bar y=\"2\">\n <baz z=\"3\"/>\n </bar>\n <a-special-element n=\"8\"/>\n</foo>\n</code></pre>\n\n<p>and foo.xsl</p>\n\n<pre><code> <xsl:template match=\"*\">\n <xsl:element name=\"{local-name()}\" namespace=\"A\" >\n <xsl:copy-of select=\"attribute::*\"/>\n <xsl:apply-templates />\n </xsl:element>\n </xsl:template>\n\n <xsl:template match=\"a-special-element\">\n <B:a-special-element xmlns:B=\"B\">\n <xsl:apply-templates match=\"children()\"/>\n </B:a-special-element>\n </xsl:template>\n\n</xsl:transform>\n</code></pre>\n\n<p>I get</p>\n\n<pre><code><foo xmlns=\"A\" x=\"1\">\n <bar y=\"2\">\n <baz z=\"3\"/>\n </bar>\n <B:a-special-element xmlns:B=\"B\"/>\n</foo>\n</code></pre>\n\n<p>Is that what you’re looking for?</p>\n"
}
]
| 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\">this already-answered question</a>? If so, does the answer apply to your code also?</p>\n"
},
{
"answer_id": 144822,
"author": "Joel Anair",
"author_id": 7441,
"author_profile": "https://Stackoverflow.com/users/7441",
"pm_score": 0,
"selected": false,
"text": "<p>Where you store your globals is a matter of personal choice. It's best to put them inside an object to avoid conflicts in the global namespace, so yes, a global object named Service would be a good place to store URLs, and other strings that are used in multiple places.</p>\n"
},
{
"answer_id": 146844,
"author": "David Robbins",
"author_id": 19799,
"author_profile": "https://Stackoverflow.com/users/19799",
"pm_score": 1,
"selected": false,
"text": "<p>You could create a collection of ValuePairs where you'd store each URL value and an identifier:</p>\n\n<pre><code>function ControlValuePair(Id, Value)\n{ \n this.Id = Id;\n this.Value = Value;\n}\n\nfunction CreateCollection(ClassName) \n{\n var obj=new Array();\n eval(\"var t=new \"+ClassName+\"()\");\n for(_item in t)\n {\n eval(\"obj.\"+_item+\"=t.\"+_item);\n }\n return obj;\n}\n\nfunction ValuePairsCollection()\n{\n this.Container=\"\";\n this.Add=function(obj)\n {\n this.push(obj);\n }\n}\n</code></pre>\n\n<p>Later you can iterate through the collection or look up the id.</p>\n"
},
{
"answer_id": 177089,
"author": "Ben Crouse",
"author_id": 6705,
"author_profile": "https://Stackoverflow.com/users/6705",
"pm_score": 1,
"selected": true,
"text": "<p>I've used something like this (used in Rails):</p>\n\n<pre><code>NAMESPACE.categories.baseUri = '/categories';\nNAMESPACE.categories.getUri = function(options)\n{\n options = options || {};\n var uri = [NAMESPACE.categories.baseUri];\n\n if(options.id)\n {\n uri.push(options.id); \n }\n if(options.action)\n {\n uri.push(options.action);\n }\n if(options.format)\n {\n uri.push('?format=' + options.format);\n }\n\n return uri.join('/');\n}\n</code></pre>\n"
}
]
| 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_node/tr-invocation.html\" rel=\"nofollow noreferrer\"><code>tr</code></a> facility for this: it's custom-built for this purpose. Remember, no code == no buggy code. :-)</p>\n\n<p>Edit: Sorry, you're right, <code>tr</code> doesn't seem to work. How about <code>sed</code>? It's a pretty stupid script I've written, but it works for me.</p>\n\n<pre><code>#!/bin/sed -f\ns/á/a/g;\ns/é/e/g;\ns/í/i/g;\ns/ó/o/g;\ns/ú/u/g;\ns/ñ/n/g;\n</code></pre>\n"
},
{
"answer_id": 144788,
"author": "Johan",
"author_id": 4804,
"author_profile": "https://Stackoverflow.com/users/4804",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to check out the boost (<a href=\"http://www.boost.org/\" rel=\"nofollow noreferrer\">http://www.boost.org/</a>) library.</p>\n\n<p>It has a regexp library, which you could use.\nIn addition it has a specific library that has some functions for string manipulation (<a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/string_algo/usage.html\" rel=\"nofollow noreferrer\">link</a>) including replace.</p>\n"
},
{
"answer_id": 144804,
"author": "andrewdotn",
"author_id": 14558,
"author_profile": "https://Stackoverflow.com/users/14558",
"pm_score": 5,
"selected": true,
"text": "<p>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.</p>\n\n<p>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.</p>\n\n<p>That said, libicu can do this for you. Open the <a href=\"http://www.icu-project.org/icu-bin/translit\" rel=\"noreferrer\">transform demo</a>; copy and paste your Spanish text into the “Input” box; enter</p>\n\n<pre><code>NFD; [:M:] remove; NFC\n</code></pre>\n\n<p>as “Compound 1” and click transform.</p>\n\n<p>(With help from slide 9 of <a href=\"http://macchiato.com/slides/icu_transforms.pdf\" rel=\"noreferrer\">Unicode Transforms in ICU</a>. Slides 29-30 show how to use the API.)</p>\n"
},
{
"answer_id": 144852,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Try using std::wstring instead of std::string. UTF-16 should work (as opposed to ASCII).</p>\n"
},
{
"answer_id": 145373,
"author": "wilhelmtell",
"author_id": 456,
"author_profile": "https://Stackoverflow.com/users/456",
"pm_score": 2,
"selected": false,
"text": "<p>I definitely think you should look into the root of the problem. That is, look for a solution that will allow you to support characters encoded in Unicode or for the user's locale.</p>\n\n<p>That being said, your problem is that you're dealing with multi-character strings. There is <code>std::wstring</code> but I'm not sure I'd use that. For one thing, wide characters aren't meant to handle variable width encodings. This hole goes deep, so I'll leave it at that.</p>\n\n<p>Now, as for the rest of your code, it is error prone because you mix the looping logic with translation logic. Thus, at least two kinds of bugs can occur: translation bugs and looping bugs. Do use the STL, it can help you a lot with the looping part.</p>\n\n<p>The following is a rough solution for replacing characters in a string.</p>\n\n<p><strong>main.cpp</strong>:</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <iterator>\n#include <algorithm>\n#include \"translate_characters.h\"\n\nusing namespace std;\n\nint main()\n{\n string text;\n cin.unsetf(ios::skipws);\n transform(istream_iterator<char>(cin), istream_iterator<char>(),\n inserter(text, text.end()), translate_characters());\n cout << text << endl;\n return 0;\n}\n</code></pre>\n\n<p><strong>translate_characters.h</strong>:</p>\n\n<pre><code>#ifndef TRANSLATE_CHARACTERS_H\n#define TRANSLATE_CHARACTERS_H\n\n#include <functional>\n#include <map>\n\nclass translate_characters : public std::unary_function<const char,char> {\npublic:\n translate_characters();\n char operator()(const char c);\n\nprivate:\n std::map<char, char> characters_map;\n};\n\n#endif // TRANSLATE_CHARACTERS_H\n</code></pre>\n\n<p><strong>translate_characters.cpp</strong>:</p>\n\n<pre><code>#include \"translate_characters.h\"\n\nusing namespace std;\n\ntranslate_characters::translate_characters()\n{\n characters_map.insert(make_pair('e', 'a'));\n}\n\nchar translate_characters::operator()(const char c)\n{\n map<char, char>::const_iterator translation_pos(characters_map.find(c));\n if( translation_pos == characters_map.end() )\n return c;\n return translation_pos->second;\n}\n</code></pre>\n"
},
{
"answer_id": 147369,
"author": "Alejo",
"author_id": 23084,
"author_profile": "https://Stackoverflow.com/users/23084",
"pm_score": 0,
"selected": false,
"text": "<p>I could not link the ICU libraries but I still think it's the best solution. As I need this program to be functional as soon as possible I made a little program (that I have to improve) and I'm going to use that. Thank you all for for suggestions and answers.</p>\n\n<p>Here's the code I'm gonna use:</p>\n\n<pre><code>for (it= dictionary.begin(); it != dictionary.end(); it++)\n{\n strMine=(it->first);\n found=toReplace.find(strMine);\n while (found != std::string::npos)\n {\n strAux=(it->second);\n toReplace.erase(found,2);\n toReplace.insert(found,strAux);\n found=toReplace.find(strMine,found+1);\n }\n} \n</code></pre>\n\n<p>I will change it next time I have to turn my program in for correction (in about 6 weeks).</p>\n"
},
{
"answer_id": 148510,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 5,
"selected": false,
"text": "<p>I disagree with the currently \"approved\" answer. The question makes perfect sense when you are indexing text. Like case-insensitive search, accent-insensitive search is a good idea. \"naïve\" matches \"Naïve\" matches \"naive\" matches \"NAİVE\" (you <em>do</em> know that an uppercase i is İ in Turkish? That's why you ignore accents)</p>\n\n<p>Now, the best algorithm is hinted at the approved answer: Use NKD (decomposition) to decompose accented letters into the base letter and a seperate accent, and then remove all accents. </p>\n\n<p>There is little point in the re-composition afterwards, though. You removed most sequences which would change, and the others are for all intents and purposes identical anyway. WHat's the difference between æ in NKC and æ in NKD?</p>\n"
},
{
"answer_id": 52972055,
"author": "vince",
"author_id": 10552815,
"author_profile": "https://Stackoverflow.com/users/10552815",
"pm_score": -1,
"selected": false,
"text": "<pre><code> /// <summary>\n /// \n /// Replace any accent and foreign character by their ASCII equivalent.\n /// In other words, convert a string to an ASCII-complient string.\n /// \n /// This also get rid of special hidden character, like EOF, NUL, TAB and other '\\0', except \\n\\r\n /// \n /// Tests with accents and foreign characters:\n /// Before: \"äæǽaeöœoeüueÄAeÜUeÖOeÀÁÂÃÄÅǺĀĂĄǍΑΆẢẠẦẪẨẬẰẮẴẲẶАAàáâãåǻāăąǎªαάảạầấẫẩậằắẵẳặаaБBбbÇĆĈĊČCçćĉċčcДDдdÐĎĐΔDjðďđδdjÈÉÊËĒĔĖĘĚΕΈẼẺẸỀẾỄỂỆЕЭEèéêëēĕėęěέεẽẻẹềếễểệеэeФFфfĜĞĠĢΓГҐGĝğġģγгґgĤĦHĥħhÌÍÎÏĨĪĬǏĮİΗΉΊΙΪỈỊИЫIìíîïĩīĭǐįıηήίιϊỉịиыїiĴJĵjĶΚКKķκкkĹĻĽĿŁΛЛLĺļľŀłλлlМMмmÑŃŅŇΝНNñńņňʼnνнnÒÓÔÕŌŎǑŐƠØǾΟΌΩΏỎỌỒỐỖỔỘỜỚỠỞỢОOòóôõōŏǒőơøǿºοόωώỏọồốỗổộờớỡởợоoПPпpŔŖŘΡРRŕŗřρрrŚŜŞȘŠΣСSśŝşșšſσςсsȚŢŤŦτТTțţťŧтtÙÚÛŨŪŬŮŰŲƯǓǕǗǙǛŨỦỤỪỨỮỬỰУUùúûũūŭůűųưǔǖǘǚǜυύϋủụừứữửựуuÝŸŶΥΎΫỲỸỶỴЙYýÿŷỳỹỷỵйyВVвvŴWŵwŹŻŽΖЗZźżžζзzÆǼAEßssIJIJijijŒOEƒf'ξksπpβvμmψpsЁYoёyoЄYeєyeЇYiЖZhжzhХKhхkhЦTsцtsЧChчchШShшshЩShchщshchЪъЬьЮYuюyuЯYaяya\"\n /// After: \"aaeooeuueAAeUUeOOeAAAAAAAAAAAAAAAAAAAAAAAaaaaaaaaaaaaaaaaaaaaaaaBbCCCCCCccccccDdDDjddjEEEEEEEEEEEEEEEEEEeeeeeeeeeeeeeeeeeeFfGGGGGgggggHHhhIIIIIIIIIIIIIiiiiiiiiiiiiJJjjKKkkLLLLllllMmNNNNNnnnnnOOOOOOOOOOOOOOOOOOOOOOooooooooooooooooooooooPpRRRRrrrrSSSSSSssssssTTTTttttUUUUUUUUUUUUUUUUUUUUUUUUuuuuuuuuuuuuuuuuuuuuuuuYYYYYYYYyyyyyyyyVvWWwwZZZZzzzzAEssIJijOEf'kspvmpsYoyoYeyeYiZhzhKhkhTstsChchShshShchshchYuyuYaya\"\n /// \n /// Tests with invalid 'special hidden characters':\n /// Before: \"\\0\\0\\000\\0000Bj��rk�\\'\\\"\\\\\\0\\a\\b\\f\\n\\r\\t\\v\\u0020���oacu\\'\\\\\\'te�\"\n /// After: \"00000Bjrk'\\\"\\\\\\n\\r oacu'\\\\'te\"\n /// \n /// </summary>\n private string Normalize(string StringToClean)\n {\n string normalizedString = StringToClean.Normalize(NormalizationForm.FormD);\n StringBuilder Buffer = new StringBuilder(StringToClean.Length);\n\n for (int i = 0; i < normalizedString.Length; i++)\n {\n if (CharUnicodeInfo.GetUnicodeCategory(normalizedString[i]) != UnicodeCategory.NonSpacingMark)\n {\n Buffer.Append(normalizedString[i]);\n }\n }\n\n string PreAsciiCompliant = Buffer.ToString().Normalize(NormalizationForm.FormC);\n StringBuilder AsciiComplient = new StringBuilder(PreAsciiCompliant.Length);\n\n foreach (char character in PreAsciiCompliant)\n {\n //Reject all special characters except \\n\\r (Carriage-Return and Line-Feed). \n //Get rid of special hidden character, like EOF, NUL, TAB and other '\\0'\n if (((int)character >= 32 && (int)character < 127) || ((int)character == 10 || (int)character == 13)) \n {\n AsciiComplient.Append(character);\n }\n }\n return AsciiComplient.ToString().Trim(); // Remove spaces at start and end of string if any\n }\n</code></pre>\n"
}
]
| 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 for round corners... but this is still a bad assumption to be making, and may very well not hold once you get to Vista.</p>\n\n<p>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 <code>SetWindowRgn()</code> fails... </p>\n"
},
{
"answer_id": 144896,
"author": "HitScan",
"author_id": 9490,
"author_profile": "https://Stackoverflow.com/users/9490",
"pm_score": 1,
"selected": false,
"text": "<p>You mention that you're trying to get the region of the window of <strong>another process</strong>. Vista tightened up the security of a lot of cross-process Win32 calls. I can't find any documentation one way or the other for <code>GetWindowRgn()</code>, but you could test it simply enough. Make a simple project that sets it's own region, and try to use your original app to get the simple app's region. If it works, then it's just going to be annoying and people can't use your app on just anything. If it doesn't work, there's a chance that your app won't work at all on Vista.</p>\n"
},
{
"answer_id": 146411,
"author": "Martin Plante",
"author_id": 4898,
"author_profile": "https://Stackoverflow.com/users/4898",
"pm_score": 2,
"selected": false,
"text": "<p>Under Vista, in order for a process that does not run as administrator to target a window from another process, it must:</p>\n\n<ul>\n<li>Embed a manifest file with uiAccess=\"true\" (example below)</li>\n<li>Digitally sign the application</li>\n<li>Install and execute it from a \"safe\" place, like \"Program Files\"</li>\n</ul>\n\n<p>Here's a sample manifest:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\" manifestVersion=\"1.0\">\n <assemblyIdentity version=\"1.0.0.0\" processorArchitecture=\"X86\" name=\"yourAssemblyNameWithoutExtension\" type=\"win32\"/>\n <trustInfo xmlns=\"urn:schemas-microsoft-com:asm.v3\">\n <security>\n <requestedPrivileges>\n <requestedExecutionLevel level=\"asInvoker\" uiAccess=\"true\" />\n </requestedPrivileges>\n </security>\n </trustInfo>\n</assembly>\n</code></pre>\n"
},
{
"answer_id": 7184756,
"author": "Mike",
"author_id": 911085,
"author_profile": "https://Stackoverflow.com/users/911085",
"pm_score": 1,
"selected": false,
"text": "<hr>\n\n<h2>My answer (based on my experience) regarding the Windows API function ::GetWindowRgn(...)</h2>\n\n<p>This function fails in Vista and in Windows 7, that is, it returns ERROR.</p>\n\n<p>But this function works good in Windows XP.</p>\n\n<p>Therefore, I would advice the following non-complex solution:\n If you use this function within an application expected to run\n under different Windows, provide the test like this:\n int nResultOfRgnOperation = ::GetWindowRegion(...);\n if (nResultOfRgnOperation != ERROR)\n < Use further the entire window's region determined by this function >\n else\n < Find the bounding rectangle for the entire window and use\n further that bounding rectangle instead of the window's region.\n In needed, you can create a rectangular region which represents\n the bounding rectangle. ></p>\n\n<p>Please use corresponding code in the places marked above as <...></p>\n\n<p>Thank you for your enthusiasm.</p>\n\n<hr>\n"
}
]
| 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 in what you need?</p>\n"
},
{
"answer_id": 144836,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 11,
"selected": true,
"text": "<p>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:</p>\n\n<pre><code>$('input#mybutton').click(function() {\n var text = $('textarea#mytextarea').val();\n //send to server and process response\n});\n</code></pre>\n"
},
{
"answer_id": 144871,
"author": "RodgerB",
"author_id": 20900,
"author_profile": "https://Stackoverflow.com/users/20900",
"pm_score": 3,
"selected": false,
"text": "<p>I have figured out that I can convert the keyCode of the event to a character by using the following function:</p>\n\n<pre><code>var char = String.fromCharCode(v_code);\n</code></pre>\n\n<p>From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).</p>\n\n<p>Thanks for all your help guys.</p>\n"
},
{
"answer_id": 3183413,
"author": "p3drosola",
"author_id": 249161,
"author_profile": "https://Stackoverflow.com/users/249161",
"pm_score": 5,
"selected": false,
"text": "<p>You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.</p>\n\n<pre><code>-------------------------------\n| consle output ... |\n| more output |\n| prevous commands and data |\n-------------------------------\n> This is an input box.\n</code></pre>\n\n<p>That way you just send the value of the input box to the server for processing, and append the result to the console messages div.</p>\n"
},
{
"answer_id": 6345384,
"author": "eric",
"author_id": 797867,
"author_profile": "https://Stackoverflow.com/users/797867",
"pm_score": 3,
"selected": false,
"text": "<p>Methinks the word \"console\" is causing the confusion.</p>\n\n<p>If you want to emulate an old-style full/half duplex console, you'd use something like this:</p>\n\n<pre><code>$('console').keyup(function(event){\n $.get(\"url\", { keyCode: event.which }, ... );\n return true;\n});\n</code></pre>\n\n<p>event.which has the key that was pressed. For backspace handling, event.which === 8.</p>\n"
},
{
"answer_id": 24203284,
"author": "Thomas Koelle",
"author_id": 2854001,
"author_profile": "https://Stackoverflow.com/users/2854001",
"pm_score": 6,
"selected": false,
"text": "<p>Where it is often the text function you use (e.g. in divs etc) then for text area it is val</p>\n\n<p>get:</p>\n\n<pre><code>$('#myTextBox').val();\n</code></pre>\n\n<p>set:</p>\n\n<pre><code>$('#myTextBox').val('new value');\n</code></pre>\n"
},
{
"answer_id": 47488417,
"author": "Abolfazl Miadian",
"author_id": 6263091,
"author_profile": "https://Stackoverflow.com/users/6263091",
"pm_score": 2,
"selected": false,
"text": "<p>the best way: \n $('#myTextBox').val('new value').trim();</p>\n"
},
{
"answer_id": 55601204,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "<p>Read textarea value and code-char conversion:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function keys(e) {\n msg.innerHTML = `last key: ${String.fromCharCode(e.keyCode)}`\n \n if(e.key == 'Enter') {\n console.log('send: ', mycon.value);\n mycon.value='';\n e.preventDefault();\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Push enter to 'send'<br>\n<textarea id='mycon' onkeydown=\"keys(event)\"></textarea>\n\n<div id=\"msg\"></div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>And below nice <strong>Quake like</strong> console on div-s only :)</p>\n<p><a href=\"https://i.stack.imgur.com/qIIKc.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qIIKc.png\" alt=\"enter image description here\" /></a></p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>document.addEventListener('keyup', keys);\n\nlet conShow = false\n\nfunction keys(e) {\n if (e.code == 'Backquote') {\n conShow = !conShow;\n mycon.classList.toggle(\"showcon\");\n } else {\n if (conShow) {\n if (e.code == \"Enter\") {\n conTextOld.innerHTML+= '<br>' + conText.innerHTML;\n let command=conText.innerHTML.replace(/&nbsp;/g,' ');\n conText.innerHTML='';\n console.log('Send to server:', command); \n } \n else if (e.code == \"Backspace\") {\n conText.innerHTML = conText.innerText.slice(0, -1);\n } else if (e.code == \"Space\") {\n conText.innerHTML = conText.innerText + '&nbsp;'\n } else {\n conText.innerHTML = conText.innerText + e.key;\n }\n\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n margin: 0\n}\n\n.con {\n display: flex;\n flex-direction: column;\n justify-content: flex-end;\n align-items: flex-start;\n width: 100%;\n height: 90px;\n background: rgba(255, 0, 0, 0.4);\n position: fixed;\n top: -90px;\n transition: top 0.5s ease-out 0.2s;\n font-family: monospace;\n}\n\n.showcon {\n top: 0px;\n}\n\n.conTextOld {\n color: white;\n}\n\n.line {\n display: flex;\n flex-direction: row;\n}\n\n.conText{ color: yellow; }\n\n.carret {\n height: 20px;\n width: 10px;\n background: red;\n margin-left: 1px;\n}\n\n.start { color: red; margin-right: 2px}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>Click here and Press tilde ` (and Enter for \"send\")\n\n<div id=\"mycon\" class=\"con\">\n <div id='conTextOld' class='conTextOld'>Hello!</div>\n <div class=\"line\">\n <div class='start'> > </div>\n <div id='conText' class=\"conText\"></div>\n <div class='carret'></div>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 62113839,
"author": "user889030",
"author_id": 889030,
"author_profile": "https://Stackoverflow.com/users/889030",
"pm_score": 2,
"selected": false,
"text": "<p>you can get textarea data by name and id</p>\n\n<pre><code>// by name\n<textarea name=\"comment\"></textarea>\nlet text_area_data = $('textarea[name=\"comment\"]').val();\n\n// by id\n<textarea id=\"comment\" name=\"comment\"></textarea>\nlet text_area_data = $('textarea#comment').val();\n</code></pre>\n"
}
]
| 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 \"${opt}\" in\n 1) echo \"Worked!\";;\n *) exit 1;\n esac\ndone\n\nOPTIND=1\nset -- -2\nwhile getopts 2 opt; do\n case \"${opt}\" in\n 2) echo \"Worked!\";;\n *) exit 1;\n esac\ndone\n</code></pre>\n"
},
{
"answer_id": 144915,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 2,
"selected": false,
"text": "<p>getopts does not modify the original arguments, as opposed to the older getopt standalone executable. You can use the bash built-in getopts over and over without modifying your original input.</p>\n\n<p>See the bash man page for more info.</p>\n\n<p>HTH.</p>\n\n<p>cheers,</p>\n\n<p>Rob</p>\n"
}
]
| 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 sources such as xml or from a remote server. <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute\" rel=\"nofollow noreferrer\">More about it here.</a></p>\n"
},
{
"answer_id": 144847,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.flagsattribute\" rel=\"noreferrer\"><code>[Flags]</code></a> is pretty handy. Syntactic sugar to be sure, but still rather nice.</p>\n\n<pre><code>[Flags] \nenum SandwichStuff\n{\n Cheese = 1,\n Pickles = 2,\n Chips = 4,\n Ham = 8,\n Eggs = 16,\n PeanutButter = 32,\n Jam = 64\n};\n\npublic Sandwich MakeSandwich(SandwichStuff stuff)\n{\n Console.WriteLine(stuff.ToString());\n // ...\n}\n\n// ...\n\nMakeSandwich(SandwichStuff.Cheese \n | SandwichStuff.Ham \n | SandwichStuff.PeanutButter);\n// produces console output: \"Cheese, Ham, PeanutButter\"\n</code></pre>\n\n<hr>\n\n<p><strong>Leppie</strong> points out something I hadn't realized, and which rather dampens my enthusiasm for this attribute: it does <strong>not</strong> instruct the compiler to allow bit combinations as valid values for enumeration variables, the compiler allows this for enumerations regardless. My C++ background showing through... <em>sigh</em></p>\n"
},
{
"answer_id": 144849,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": false,
"text": "<p>If I were to do a code coverage crawl, I think these two would be top:</p>\n\n<pre><code> [Serializable]\n [WebMethod]\n</code></pre>\n"
},
{
"answer_id": 144850,
"author": "Chris Wenham",
"author_id": 5548,
"author_profile": "https://Stackoverflow.com/users/5548",
"pm_score": 6,
"selected": false,
"text": "<p>In Hofstadtian spirit, the <code>[Attribute]</code> attribute is very useful, since it's how you create your own attributes. I've used attributes instead of interfaces to implement plugin systems, add descriptions to Enums, simulate multiple dispatch and other tricks.</p>\n"
},
{
"answer_id": 144851,
"author": "Dan Herbert",
"author_id": 392,
"author_profile": "https://Stackoverflow.com/users/392",
"pm_score": 8,
"selected": false,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.obsoleteattribute\" rel=\"noreferrer\"><code>System.Obsolete</code></a> is one of the most useful attributes in the framework, in my opinion. The ability to raise a warning about code that should no longer be used is very useful. I love having a way to tell developers that something should no longer be used, as well as having a way to explain why and point to the better/new way of doing something.</p>\n\n<p>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute\" rel=\"noreferrer\"><code>Conditional attribute</code></a> is pretty handy too for debug usage. It allows you to add methods in your code for debug purposes that won't get compiled when you build your solution for release.</p>\n\n<p>Then there are a lot of attributes specific to Web Controls that I find useful, but those are more specific and don't have any uses outside of the development of server controls from what I've found.</p>\n"
},
{
"answer_id": 144870,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 7,
"selected": false,
"text": "<p>For what it's worth, here's <a href=\"http://msdn.microsoft.com/en-us/library/system.attribute.aspx#inheritanceContinued\" rel=\"noreferrer\">a list of all .NET attributes</a>. There are several hundred.</p>\n\n<p>I don't know about anyone else but I have some serious RTFM to do!</p>\n"
},
{
"answer_id": 144909,
"author": "Redwood",
"author_id": 1512,
"author_profile": "https://Stackoverflow.com/users/1512",
"pm_score": 5,
"selected": false,
"text": "<p>I've found <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.defaultvalueattribute\" rel=\"nofollow noreferrer\"><code>[DefaultValue]</code></a> to be quite useful.</p>\n"
},
{
"answer_id": 144929,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 9,
"selected": false,
"text": "<p><code>[DebuggerDisplay]</code> can be really helpful to quickly see customized output of a Type when you mouse over the instance of the Type during debugging. example:</p>\n\n<pre><code>[DebuggerDisplay(\"FirstName={FirstName}, LastName={LastName}\")]\nclass Customer\n{\n public string FirstName;\n public string LastName;\n}\n</code></pre>\n\n<p>This is how it should look in the debugger:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qEZNZ.jpg\" alt=\"alt text\"></p>\n\n<p>Also, it is worth mentioning that <code>[WebMethod]</code> attribute with <code>CacheDuration</code> property set can avoid unnecessary execution of the web service method. </p>\n"
},
{
"answer_id": 144934,
"author": "Adrian Wible",
"author_id": 23105,
"author_profile": "https://Stackoverflow.com/users/23105",
"pm_score": 5,
"selected": false,
"text": "<p>I'd suggest <code>[TestFixture]</code> and <code>[Test]</code> - from the <a href=\"https://nunit.org/\" rel=\"nofollow noreferrer\">nUnit</a> library.</p>\n\n<p>Unit tests in your code provide safety in refactoring and codified documentation. </p>\n"
},
{
"answer_id": 144939,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": false,
"text": "<p>I like <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerstepthroughattribute\" rel=\"nofollow noreferrer\"><code>[DebuggerStepThrough]</code> from System.Diagnostics</a>. </p>\n\n<p>It's very handy for avoiding stepping into those one-line do-nothing methods or properties (if you're forced to work in an early .Net without automatic properties). Put the attribute on a short method or the getter or setter of a property, and you'll fly right by even when hitting \"step into\" in the debugger.</p>\n"
},
{
"answer_id": 144942,
"author": "ElGringoGrande",
"author_id": 23100,
"author_profile": "https://Stackoverflow.com/users/23100",
"pm_score": 3,
"selected": false,
"text": "<p>Being a middle tier developer I like</p>\n\n<p><code>System.ComponentModel.EditorBrowsableAttribute</code> Allows me to hide properties so that the UI developer is not overwhelmed with properties that they don't need to see.</p>\n\n<p><code>System.ComponentModel.BindableAttribute</code> Some things don't need to be databound. Again, lessens the work the UI developers need to do.</p>\n\n<p>I also like the <code>DefaultValue</code> that Lawrence Johnston mentioned.</p>\n\n<p><code>System.ComponentModel.BrowsableAttribute</code> and the <code>Flags</code> are used regularly.</p>\n\n<p>I use \n<code>System.STAThreadAttribute\n System.ThreadStaticAttribute</code>\nwhen needed.</p>\n\n<p>By the way. I these are just as valuable for all the .Net framework developers.</p>\n"
},
{
"answer_id": 145204,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": false,
"text": "<p>The attributes I use the most are the ones related to XML Serialization.</p>\n\n<p><code>XmlRoot</code></p>\n\n<p><code>XmlElement</code></p>\n\n<p><code>XmlAttribute</code></p>\n\n<p>etc...</p>\n\n<p>Extremely useful when doing any quick and dirty XML parsing or serializing.</p>\n"
},
{
"answer_id": 147792,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "<p>Only a few attributes get compiler support, but one very interesting use of attributes is in AOP: <a href=\"http://www.postsharp.org/\" rel=\"noreferrer\">PostSharp</a> uses your bespoke attributes to inject IL into methods, allowing all manner of abilities... log/trace being trivial examples - but some other good examples are things like automatic INotifyPropertyChanged implementation (<a href=\"http://code.google.com/p/postsharp-user-samples/wiki/DataBindingSupport\" rel=\"noreferrer\">here</a>).</p>\n\n<p>Some that occur and <em>impact the compiler or runtime directly</em>:</p>\n\n<ul>\n<li><code>[Conditional(\"FOO\")]</code> - calls to this method (including argument evaluation) only occur if the \"FOO\" symbol is defined during build</li>\n<li><code>[MethodImpl(...)]</code> - used to indicate a few thing like synchronization, inlining</li>\n<li><code>[PrincipalPermission(...)]</code> - used to inject security checks into the code automatically</li>\n<li><code>[TypeForwardedTo(...)]</code> - used to move types between assemblies <em>without rebuilding the callers</em></li>\n</ul>\n\n<p>For things that are checked manually via reflection - I'm a big fan of the <code>System.ComponentModel</code> attributes; things like <code>[TypeDescriptionProvider(...)]</code>, <code>[TypeConverter(...)]</code>, and <code>[Editor(...)]</code> which can completely change the behavior of types in data-binding scenarios (i.e. dynamic properties etc).</p>\n"
},
{
"answer_id": 197063,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 4,
"selected": false,
"text": "<pre><code>[TypeConverter(typeof(ExpandableObjectConverter))]\n</code></pre>\n\n<p>Tells the designer to expand the properties which are classes (of your control)</p>\n\n<pre><code>[Obfuscation]\n</code></pre>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.reflection.obfuscationattribute\" rel=\"nofollow noreferrer\">Instructs obfuscation tools to take the specified actions for an assembly, type, or member.</a> (Although typically you use an Assembly level <code>[assembly:ObfuscateAssemblyAttribute(true)]</code></p>\n"
},
{
"answer_id": 204958,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<pre><code>[XmlIgnore]\n</code></pre>\n\n<p>as this allows you to ignore (in any xml serialisation) 'parent' objects that would otherwise cause exceptions when saving.</p>\n"
},
{
"answer_id": 205078,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// on configuration sections\n[ConfigurationProperty] \n\n// in asp.net\n[NotifyParentProperty(true)]\n</code></pre>\n"
},
{
"answer_id": 205416,
"author": "wusher",
"author_id": 1632,
"author_profile": "https://Stackoverflow.com/users/1632",
"pm_score": 4,
"selected": false,
"text": "<p>I have been using the <code>[DataObjectMethod]</code> lately. It describes the method so you can use your class with the ObjectDataSource ( or other controls).</p>\n\n<pre><code>[DataObjectMethod(DataObjectMethodType.Select)] \n[DataObjectMethod(DataObjectMethodType.Delete)] \n[DataObjectMethod(DataObjectMethodType.Update)] \n[DataObjectMethod(DataObjectMethodType.Insert)] \n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.dataobjectmethodattribute(VS.80).aspx\" rel=\"noreferrer\">More info</a></p>\n"
},
{
"answer_id": 225964,
"author": "Ahmed Atia",
"author_id": 14118,
"author_profile": "https://Stackoverflow.com/users/14118",
"pm_score": 4,
"selected": false,
"text": "<p>In our current project, we use</p>\n\n<pre><code>[ComVisible(false)]\n</code></pre>\n\n<p>It controls accessibility of an individual managed type or member, or of all types within an assembly, to COM.</p>\n\n<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.comvisibleattribute\" rel=\"nofollow noreferrer\">More Info</a></p>\n"
},
{
"answer_id": 329878,
"author": "Ajaxx",
"author_id": 25228,
"author_profile": "https://Stackoverflow.com/users/25228",
"pm_score": 5,
"selected": false,
"text": "<p>I like using the <code>[ThreadStatic]</code> attribute in combination with thread and stack based programming. For example, if I want a value that I want to share with the rest of a call sequence, but I want to do it out of band (i.e. outside of the call parameters), I might employ something like this.</p>\n\n<pre><code>class MyContextInformation : IDisposable {\n [ThreadStatic] private static MyContextInformation current;\n\n public static MyContextInformation Current {\n get { return current; }\n }\n\n private MyContextInformation previous;\n\n\n public MyContextInformation(Object myData) {\n this.myData = myData;\n previous = current;\n current = this;\n }\n\n public void Dispose() {\n current = previous;\n }\n}\n</code></pre>\n\n<p>Later in my code, I can use this to provide contextual information out of band to people downstream from my code. Example:</p>\n\n<pre><code>using(new MyContextInformation(someInfoInContext)) {\n ...\n}\n</code></pre>\n\n<p>The ThreadStatic attribute allows me to scope the call only to the thread in question avoiding the messy problem of data access across threads.</p>\n"
},
{
"answer_id": 411535,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.designerserializationvisibilityattribute\" rel=\"nofollow noreferrer\"><code>DesignerSerializationVisibilityAttribute</code></a> is very useful. When you put a runtime property on a control or component, and you don't want the designer to serialize it, you use it like this:</p>\n\n<pre><code>[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]\npublic Foo Bar {\n get { return baz; }\n set { baz = value; }\n}\n</code></pre>\n"
},
{
"answer_id": 637195,
"author": "Anthony Brien",
"author_id": 76939,
"author_profile": "https://Stackoverflow.com/users/76939",
"pm_score": 7,
"selected": false,
"text": "<p>I always use the <code>DisplayName</code>, <code>Description</code> and <code>DefaultValue</code> attributes over public properties of my user controls, custom controls or any class I'll edit through a property grid. These tags are used by the .NET PropertyGrid to format the name, the description panel, and bolds values that are not set to the default values.</p>\n\n<pre><code>[DisplayName(\"Error color\")]\n[Description(\"The color used on nodes containing errors.\")]\n[DefaultValue(Color.Red)]\npublic Color ErrorColor\n{\n ...\n} \n</code></pre>\n\n<p>I just wish Visual Studio's IntelliSense would take the <code>Description</code> attribute into account if no XML comment are found. It would avoid having to repeat the same sentence twice.</p>\n"
},
{
"answer_id": 801499,
"author": "CSharper",
"author_id": 70799,
"author_profile": "https://Stackoverflow.com/users/70799",
"pm_score": 3,
"selected": false,
"text": "<p><code>[System.Security.Permissions.PermissionSetAttribute]</code> allows security actions for a PermissionSet to be applied to code using declarative security.</p>\n\n<pre><code>// usage:\npublic class FullConditionUITypeEditor : UITypeEditor\n{\n // The immediate caller is required to have been granted the FullTrust permission.\n [PermissionSetAttribute(SecurityAction.LinkDemand, Name = \"FullTrust\")]\n public FullConditionUITypeEditor() { }\n}\n</code></pre>\n"
},
{
"answer_id": 814806,
"author": "xrost",
"author_id": 51407,
"author_profile": "https://Stackoverflow.com/users/51407",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/q/51950\">Here</a> is the post about interesting attribute <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.internalsvisibletoattribute\" rel=\"nofollow noreferrer\">InternalsVisibleTo</a>. Basically what it does it mimics C++ friends access functionality. It comes very handy for unit testing.</p>\n"
},
{
"answer_id": 892654,
"author": "Steve Cooper",
"author_id": 6722,
"author_profile": "https://Stackoverflow.com/users/6722",
"pm_score": 7,
"selected": false,
"text": "<p>My vote would be for <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.conditionalattribute\" rel=\"nofollow noreferrer\"><code>Conditional</code></a></p>\n\n<pre><code>[Conditional(\"DEBUG\")]\npublic void DebugOnlyFunction()\n{\n // your code here\n}\n</code></pre>\n\n<p>You can use this to add a function with advanced debugging features; like <code>Debug.Write</code>, it is only called in debug builds, and so allows you to encapsulate complex debug logic outside the main flow of your program.</p>\n"
},
{
"answer_id": 971286,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 5,
"selected": false,
"text": "<p>It's not well-named, not well-supported in the framework, and shouldn't require a parameter, but this attribute is a useful marker for immutable classes:</p>\n\n<pre><code>[ImmutableObject(true)]\n</code></pre>\n"
},
{
"answer_id": 1432920,
"author": "Kevin Driedger",
"author_id": 9587,
"author_profile": "https://Stackoverflow.com/users/9587",
"pm_score": 3,
"selected": false,
"text": "<p><code>[DeploymentItem(\"myFile1.txt\")]</code>\n<a href=\"https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.testtools.unittesting.deploymentitemattribute\" rel=\"nofollow noreferrer\">MSDN Doc on DeploymentItem</a></p>\n\n<p>This is really useful if you are testing against a file or using the file as input to your test. </p>\n"
},
{
"answer_id": 8220547,
"author": "Ming Yeh",
"author_id": 946092,
"author_profile": "https://Stackoverflow.com/users/946092",
"pm_score": 3,
"selected": false,
"text": "<p>I generates data entity class via CodeSmith and I use attributes for some validation routine. Here is an example:</p>\n\n<pre><code>/// <summary>\n/// Firm ID\n/// </summary>\n[ChineseDescription(\"送样单位编号\")]\n[ValidRequired()]\npublic string FirmGUID\n{\n get { return _firmGUID; }\n set { _firmGUID = value; }\n}\n</code></pre>\n\n<p>And I got an utility class to do the validation based on the attributes attached to the data entity class. Here is the code:</p>\n\n<pre><code>namespace Reform.Water.Business.Common\n{\n/// <summary>\n/// Validation Utility\n/// </summary>\npublic static class ValidationUtility\n{\n /// <summary>\n /// Data entity validation\n /// </summary>\n /// <param name=\"data\">Data entity object</param>\n /// <returns>return true if the object is valid, otherwise return false</returns>\n public static bool Validate(object data)\n {\n bool result = true;\n PropertyInfo[] properties = data.GetType().GetProperties();\n foreach (PropertyInfo p in properties)\n {\n //Length validatioin\n Attribute attribute = Attribute.GetCustomAttribute(p,typeof(ValidLengthAttribute), false);\n if (attribute != null)\n {\n ValidLengthAttribute validLengthAttribute = attribute as ValidLengthAttribute;\n if (validLengthAttribute != null)\n {\n int maxLength = validLengthAttribute.MaxLength;\n int minLength = validLengthAttribute.MinLength;\n string stringValue = p.GetValue(data, null).ToString();\n if (stringValue.Length < minLength || stringValue.Length > maxLength)\n {\n return false;\n }\n }\n }\n //Range validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRangeAttribute), false);\n if (attribute != null)\n {\n ValidRangeAttribute validRangeAttribute = attribute as ValidRangeAttribute;\n if (validRangeAttribute != null)\n {\n decimal maxValue = decimal.MaxValue;\n decimal minValue = decimal.MinValue;\n decimal.TryParse(validRangeAttribute.MaxValueString, out maxValue);\n decimal.TryParse(validRangeAttribute.MinValueString, out minValue);\n decimal decimalValue = 0;\n decimal.TryParse(p.GetValue(data, null).ToString(), out decimalValue);\n if (decimalValue < minValue || decimalValue > maxValue)\n {\n return false;\n }\n }\n }\n //Regex validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRegExAttribute), false);\n if (attribute != null)\n {\n ValidRegExAttribute validRegExAttribute = attribute as ValidRegExAttribute;\n if (validRegExAttribute != null)\n {\n string objectStringValue = p.GetValue(data, null).ToString();\n string regExString = validRegExAttribute.RegExString;\n Regex regEx = new Regex(regExString);\n if (regEx.Match(objectStringValue) == null)\n {\n return false;\n }\n }\n }\n //Required field validation\n attribute = Attribute.GetCustomAttribute(p,typeof(ValidRequiredAttribute), false);\n if (attribute != null)\n {\n ValidRequiredAttribute validRequiredAttribute = attribute as ValidRequiredAttribute;\n if (validRequiredAttribute != null)\n {\n object requiredPropertyValue = p.GetValue(data, null);\n if (requiredPropertyValue == null || string.IsNullOrEmpty(requiredPropertyValue.ToString()))\n {\n return false;\n }\n }\n }\n }\n return result;\n }\n}\n}\n</code></pre>\n"
},
{
"answer_id": 9654780,
"author": "Eldritch Conundrum",
"author_id": 278044,
"author_profile": "https://Stackoverflow.com/users/278044",
"pm_score": 3,
"selected": false,
"text": "<p>Off the top of my head, here is a quick list, roughly sorted by frequency of use, of predefined attributes I actually use in a big project (~500k LoCs):</p>\n\n<p>Flags, Serializable, WebMethod, COMVisible, TypeConverter, Conditional, ThreadStatic, Obsolete, InternalsVisibleTo, DebuggerStepThrough.</p>\n"
},
{
"answer_id": 10949381,
"author": "smdrager",
"author_id": 356550,
"author_profile": "https://Stackoverflow.com/users/356550",
"pm_score": 3,
"selected": false,
"text": "<p><code>[EditorBrowsable(EditorBrowsableState.Never)]</code> allows you to hide properties and methods from IntelliSense if the project is not in your solution. Very helpful for hiding invalid flows for fluent interfaces. How often do you want to GetHashCode() or Equals()?</p>\n\n<p>For MVC <code>[ActionName(\"Name\")]</code> allows you to have a Get action and Post action with the same method signature, or to use dashes in the action name, which otherwise would not be possible without creating a route for it.</p>\n"
},
{
"answer_id": 12457425,
"author": "Sujit",
"author_id": 792713,
"author_profile": "https://Stackoverflow.com/users/792713",
"pm_score": 2,
"selected": false,
"text": "<p>I always use attributes,\n<code>[Serializable]</code>, <code>[WebMethod]</code>, <code>[DefaultValue]</code>, <code>[Description(\"description here\")]</code>.</p>\n\n<p>but beside that there is a <a href=\"http://msdn.microsoft.com/en-us/library/284c1c4s%28v=vs.71%29.aspx\" rel=\"nofollow\">Global Attributes</a> in c#.</p>\n\n<pre><code>[assembly: System.CLSCompliant(true)]\n[assembly: AssemblyCulture(\"\")]\n[assembly: AssemblyDescription(\"\")]\n</code></pre>\n"
},
{
"answer_id": 12903824,
"author": "Eric Javier Hernandez Saura",
"author_id": 1499972,
"author_profile": "https://Stackoverflow.com/users/1499972",
"pm_score": 3,
"selected": false,
"text": "<p>I consider that is important to mention here that the following attributes are also very important:</p>\n\n<pre><code>STAThreadAttribute \n</code></pre>\n\n<p>Indicates that the COM threading model for an application is single-threaded apartment (STA). </p>\n\n<p>For example this attribute is used in Windows Forms Applications:</p>\n\n<pre><code>static class Program\n{\n /// <summary>\n /// The main entry point for the application.\n /// </summary>\n [STAThread]\n static void Main()\n {\n Application.EnableVisualStyles();\n Application.SetCompatibleTextRenderingDefault(false);\n Application.Run(new Form1());\n }\n}\n</code></pre>\n\n<p>And also ...</p>\n\n<pre><code>SuppressMessageAttribute\n</code></pre>\n\n<p>Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.</p>\n\n<p>For example:</p>\n\n<pre><code>[SuppressMessage(\"Microsoft.Performance\", \"CA1801:ReviewUnusedParameters\", MessageId = \"isChecked\")]\n[SuppressMessage(\"Microsoft.Performance\", \"CA1804:RemoveUnusedLocals\", MessageId = \"fileIdentifier\")]\nstatic void FileNode(string name, bool isChecked)\n{\n string fileIdentifier = name;\n string fileName = name;\n string version = String.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 13726796,
"author": "Felix K.",
"author_id": 739912,
"author_profile": "https://Stackoverflow.com/users/739912",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debuggerhiddenattribute\" rel=\"nofollow noreferrer\">DebuggerHiddenAttribute</a> which allows to avoiding step into code which should not be debugged.</p>\n\n<pre><code>public static class CustomDebug\n{\n [DebuggerHidden]\n public static void Assert(Boolean condition, Func<Exception> exceptionCreator) { ... }\n}\n\n...\n\n// The following assert fails, and because of the attribute the exception is shown at this line\n// Isn't affecting the stack trace\nCustomDebug.Assert(false, () => new Exception()); \n</code></pre>\n\n<p>Also it prevents from showing methods in stack trace, useful when having a method which just wraps another method:</p>\n\n<pre><code>[DebuggerHidden]\npublic Element GetElementAt(Vector2 position)\n{\n return GetElementAt(position.X, position.Y);\n}\n\npublic Element GetElementAt(Single x, Single y) { ... }\n</code></pre>\n\n<p>If you now call <code>GetElementAt(new Vector2(10, 10))</code> and a error occurs at the wrapped method, the call stack is not showing the method which is calling the method which throws the error.</p>\n"
}
]
| 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 more of an array for finding rows and columns.</p>\n"
},
{
"answer_id": 144924,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I believe the columns names are stored in a Hashtable. Should be O(1) or constant lookup for case-sensitive lookups. If it had to look through each, then of course it would be O(n).</p>\n"
},
{
"answer_id": 145299,
"author": "faulty",
"author_id": 20007,
"author_profile": "https://Stackoverflow.com/users/20007",
"pm_score": 2,
"selected": false,
"text": "<p>Actually it's advisable to use integer when referencing column, which can improve a lot in terms of performance. To keep things manageable, you could declare constant integer. So instead of what you did, you could do </p>\n\n<pre><code>const int SomeTable_SomeColumn = 0;\n\nDataTable dt = new DataTable();\nif(dt.Columns.Contains(SomeTable_SomeColumn))\n{\n object o = dt.Rows[0][SomeTable_SomeColumn];\n}\n</code></pre>\n"
},
{
"answer_id": 247878,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 3,
"selected": true,
"text": "<p>Via <a href=\"http://www.red-gate.com/products/reflector/\" rel=\"nofollow noreferrer\">Reflector</a> the steps for DataRow[\"ColumnName\"] are:</p>\n\n<ol>\n<li>Get the DataColumn from ColumnName. Uses the row's DataColumnCollection[\"ColumnName\"]. Internally, DataColumnCollection stores its DataColumns in a Hastable. O(1)</li>\n<li>Get the DataRow's row index. The index is stored in an internal member. O(1)</li>\n<li><p>Get the DataColumn's value at the index using DataColumn[index]. DataColumn stores its data in a System.Data.Common.DataStorage (internal, abstract) member:</p>\n\n<p>return dataColumnInstance._storage.Get(recordIndex);</p>\n\n<p>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)</p></li>\n</ol>\n\n<p>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.</p>\n\n<p>Interesting that DataStorage uses an array for values. Can't imagine that's easy to rebuild when you add or remove rows.</p>\n"
}
]
| 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. However, I recall reading on MSDN that it's not appropriate for large scale processing of this nature.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n"
},
{
"answer_id": 144996,
"author": "Peter Meyer",
"author_id": 1875,
"author_profile": "https://Stackoverflow.com/users/1875",
"pm_score": 0,
"selected": false,
"text": "<p>I would be concerned about performance here. You indicated that the database may give it 20-30 items per second and an item could take up to a few seconds to be validated. That could be quite a large number of threads -- using your metrics, worst case 60-90 threads! I think you need to reconsider the design here. Michael mentioned a nice pattern. The use of the queue really helps keep things under control and organized. A semaphore could also be employed to control number of threads created -- i.e. you could have a maximum number of threads allowed, but under smaller loads, you wouldn't necessarily have to create the maximum number if fewer ended up getting the job done -- i.e. your own pool size could be dynamic with a cap.</p>\n\n<p>When using the thread-pool, I also find it more difficult to monitor the execution of threads from the pool in their performing the work. So, unless it's fire and forget, I am in favor of more controlled execution. I know you mentioned that your app exits after the 65K items are all completed. How are you monitoring you threads to determine if they have completed their work -- i.e. all queued workers are done. Are you monitoring the status of all items in the HashSets? I think by queuing your items up and having your own worker threads consume off that queue, you can gain more control. Albeit, this can come at the cost of more overhead in terms of signaling between threads to indicate when all items have been queued allowing them to exit.</p>\n"
},
{
"answer_id": 145028,
"author": "Mauricio Scheffer",
"author_id": 21239,
"author_profile": "https://Stackoverflow.com/users/21239",
"pm_score": 1,
"selected": false,
"text": "<p>Be careful, QueueUserWorkItem <a href=\"http://weblogs.asp.net/omagnusson/archive/2007/01/02/threadpool-queueuserworkitem-traps.aspx\" rel=\"nofollow noreferrer\">might fail</a></p>\n"
},
{
"answer_id": 145087,
"author": "Ted Elliott",
"author_id": 16501,
"author_profile": "https://Stackoverflow.com/users/16501",
"pm_score": 2,
"selected": false,
"text": "<p>I second the idea of using a blocking queue and worker threads. Here is a blocking queue implementation that I've used in the past with good results:\n<a href=\"https://www.codeproject.com/Articles/8018/Bounded-Blocking-Queue-One-Lock\" rel=\"nofollow noreferrer\">https://www.codeproject.com/Articles/8018/Bounded-Blocking-Queue-One-Lock</a></p>\n\n<p>What's involved in your validation logic? If its mainly CPU bound then I would create no more than 1 worker thread per processor/core on the box. This will tell you the number of processors:\n <code>Environment.ProcessorCount</code></p>\n\n<p>If your validation involves I/O such as File Access or database access then you could use a few more threads than the number of processors.</p>\n"
},
{
"answer_id": 145089,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "<p>There is a possible logic error in the code posted with the question, depending on where the item id in <code>ValidateItem(int id)</code> comes from. Why? Because although you correctly lock your validatingItems and validatedItems queues before queing a work item, you do not add the item to the validatingItems queue until the new thread spins up. That means there could be a time gap where another thread calls <code>ValidateItem(id)</code> with the same id (unless this is running on a single main thread).</p>\n\n<p>I would add item to the validatingItems queue just before queuing the item, inside the lock.</p>\n\n<p>Edit: also <code>QueueUserWorkItem()</code> returns a bool so you should use the return value to make sure the item was queued and THEN add it to the validatingItems queue.</p>\n"
},
{
"answer_id": 146706,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 1,
"selected": false,
"text": "<p>ThreadPool may not be optimal for jamming so much at once into it. You may want to research the upper limits of its capabilities and/or roll your own.</p>\n\n<p>Also, there is a race condition that exists in your code, if you expect no duplicate validations. The call to</p>\n\n<pre><code>this.validatingItems.Add(itemId);\n</code></pre>\n\n<p>needs to happen in the main thread (ValidateItem), not in the thread pool thread (Validate method). This call should occur a line before the queueing of the work item to the pool. </p>\n\n<p>A worse bug is found by not checking the return of QueueUserWorkItem. Queueing can fail, and why it doesn't throw an exception is a mystery to us all. If it returns false, you need to remove the item that was added to the validatingItems list, and handle the error (throw exeception probably).</p>\n"
},
{
"answer_id": 147244,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You could also try using the CCR - Concurrency and Coordination Runtime. It's buried inside Microsoft Robotics Studio, but provides an excellent API for doing this sort of thing.</p>\n\n<p>You'd just need to create a \"Port\" (essentially a queue), hook up a receiver (method that gets called when something is posted to it), and then post work items to it. The CCR handles the queue and the worker thread to run it on.</p>\n\n<p><a href=\"http://channel9.msdn.com/shows/Going+Deep/CCR-Programming-Jeffrey-Richter-and-George-Chrysanthakopoulos/\" rel=\"nofollow noreferrer\">Here's a video on Channel9 about the CCR.</a></p>\n\n<p>It's very high-performance and is even being used for non-Robotics stuff (Myspace.com uses it behind the scenese for their content-delivery network).</p>\n"
},
{
"answer_id": 58311502,
"author": "Nandan",
"author_id": 4268162,
"author_profile": "https://Stackoverflow.com/users/4268162",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend looking into <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library\" rel=\"nofollow noreferrer\">MSDN: Task Parallel Library - DataFlow</a>. You can find examples of implementing <code>Producer-Consumer</code> in your case would be the database <code>producing</code> items to validate and the validation routine becomes the <code>consumer</code>. </p>\n\n<p>Also recommend using <code>ConcurrentDictionary<TKey, TValue></code> as a \"Concurrent\" hash set where you just populate the keys with no values :). You can potentially make your code <code>lock-free</code>. </p>\n"
}
]
| 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-area-message t)\n</pre>\n"
},
{
"answer_id": 144986,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 5,
"selected": false,
"text": "<p>Emacs has a couple of variables which inhibit these actions. If you edit your emacs control file (.emacs) and insert the following:</p>\n\n<pre><code>;; inhibit-startup-echo-area-message MUST be set to a hardcoded \n;; string of your login name \n(setq inhibit-startup-echo-area-message \"USERNAME\")\n(setq inhibit-startup-message t)\n</code></pre>\n\n<p>that should solve your problem. They basically set the inhibit parameters to true to prevent the behavior you want to get rid of.</p>\n"
},
{
"answer_id": 208850,
"author": "Vebjorn Ljosa",
"author_id": 17498,
"author_profile": "https://Stackoverflow.com/users/17498",
"pm_score": 2,
"selected": false,
"text": "<p>Put the following in your personal init file (ususally <code>~/.emacs.el</code>):</p>\n\n<pre><code>(setq inhibit-startup-message t)\n</code></pre>\n\n<p>(Or <code>(setq inhibit-startup-screen t)</code> in with older Emacs versions.)</p>\n\n<p>You can also turn off the message \"For information about GNU Emacs and the GNU system, type C-h C-a.\" in the echo with the variable <code>inhibit-startup-echo-area-message</code>, but it is not enough to set it to <code>t</code>; you must set it to your username. See the documentation for <code>inhibit-startup-echo-area-message</code>.</p>\n"
},
{
"answer_id": 28530989,
"author": "rgtk",
"author_id": 1106189,
"author_profile": "https://Stackoverflow.com/users/1106189",
"pm_score": 2,
"selected": false,
"text": "<p>You can customize message in minibuffer therefore remove fanfare:</p>\n\n<pre><code>;; Hide advertisement from minibuffer\n(defun display-startup-echo-area-message ()\n (message \"\"))\n</code></pre>\n"
},
{
"answer_id": 44552601,
"author": "dodona",
"author_id": 5758211,
"author_profile": "https://Stackoverflow.com/users/5758211",
"pm_score": 0,
"selected": false,
"text": "<p>If your init file is byte-compiled, use the following form instead:</p>\n\n<pre><code>(eval '(setq inhibit-startup-echo-area-message \"YOUR-USER-NAME\"))\n</code></pre>\n"
},
{
"answer_id": 51551825,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Add the below to your init file</p>\n\n<pre><code>(setq inhibit-startup-message t\ninhibit-startup-echo-area-message t) \n</code></pre>\n"
}
]
| 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>This is likely if you're running on Windows (and you probably are, given that your file name starts with <code>\"c:\\\"</code>).</p>\n\n<p>If you open the file in <code>\"wb\"</code> mode, I suspect you'll find the numbers are identical:</p>\n\n<pre><code>FILE* test = fopen(\"C:\\\\core.u\", \"wb\");\n</code></pre>\n\n<p>The C99 standard has this to say in <code>7.19.5.3 The fopen function</code>:</p>\n\n<blockquote>\n <p>The argument mode points to a string. If the string is one of the following, the file is\n open in the indicated mode. Otherwise, the behaviour is undefined.</p>\n \n <p><code>r</code> open text file for reading<br>\n <code>w</code> truncate to zero length or create text file for writing<br>\n <code>a</code> append; open or create text file for writing at end-of-file<br>\n <code>rb</code> open binary file for reading<br>\n <code>wb</code> truncate to zero length or create binary file for writing<br>\n <code>ab</code> append; open or create binary file for writing at end-of-file<br>\n <code>r+</code> open text file for update (reading and writing)<br>\n <code>w+</code> truncate to zero length or create text file for update<br>\n <code>a+</code> append; open or create text file for update, writing at end-of-file<br>\n <code>r+b</code> or <code>rb+</code> open binary file for update (reading and writing)<br>\n <code>w+b</code> or <code>wb+</code> truncate to zero length or create binary file for update<br>\n <code>a+b</code> or <code>ab+</code> append; open or create binary file for update, writing at end-of-file</p>\n</blockquote>\n\n<p>You can see they distinguish between <code>w</code> and <code>wb</code>. I don't believe an implementation is <em>required</em> to treat the two differently but it's usually safer to use binary mode for binary data.</p>\n"
},
{
"answer_id": 147506,
"author": "DarenW",
"author_id": 10468,
"author_profile": "https://Stackoverflow.com/users/10468",
"pm_score": 0,
"selected": false,
"text": "<p>what does fwrite return? normally the return value should be the number of bytes written.\nAlso, what does the ftell() answer with right before the fseek?</p>\n\n<p>It might help to know what operating system, C compiler version and C library.</p>\n"
},
{
"answer_id": 148477,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 0,
"selected": false,
"text": "<p>A filepointer is a cookie. It has no value. The only thing you can use it for is to seek to the same place in a file. I'm not even sure if ISO C guarantees that ftell returns increasing values. If you don't believe this, please look at the different seek() modes. They exist precisely because the position is not a simple byte offset.</p>\n"
},
{
"answer_id": 2255873,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 0,
"selected": false,
"text": "<p>windows doesn't actually write all data out to the file without a flush and possibly an fsync. Maybe that's why</p>\n"
}
]
| 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 to unauthorized users.</p>\n\n<p>BTW, instead of using a home-grown authentication method (which I assume is what your CheckAccessPermission is), you might be able to hook up to WCF's out-of-the-box support for ASP.NET role providers. Once this is done, you perform authorization via OperationContext.Current.ServiceSecurityContext.PrimaryIdentity.IsInRole(). The PrimaryIdentity is an IPrincipal.</p>\n"
},
{
"answer_id": 146615,
"author": "TheSoftwareJedi",
"author_id": 18941,
"author_profile": "https://Stackoverflow.com/users/18941",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<p>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).</p>\n\n<p>Example (note, these shouldn't be in the same file or even DLL though!):</p>\n\n<pre><code>public abstract class MyServiceImpl\n{\n public void MyMethod(string entityId)\n {\n CheckPermissions(entityId);\n //move along...\n }\n protected abstract bool CheckPermissions(string entityId);\n}\n\npublic class MyServiceUnitTest\n{\n private bool CheckPermissions(string entityId)\n {\n return true;\n }\n}\n\npublic class MyServiceMyAuth\n{\n private bool CheckPermissions(string entityId)\n {\n //do some custom authentication\n return true;\n }\n}\n</code></pre>\n\n<p>Then your WCF deployment uses the class \"MyServiceMyAuth\", and you do your unit testing against the other.</p>\n"
},
{
"answer_id": 654545,
"author": "akmad",
"author_id": 1314,
"author_profile": "https://Stackoverflow.com/users/1314",
"pm_score": 3,
"selected": false,
"text": "<p>About question #2, I would do this using Dependency Injection and set up your service implementation something like this:</p>\n\n<pre><code>class MyService : IMyService\n{\n public MyService() : this(new UserAuthorization()) { }\n public MyService(IAuthorization auth) { _auth = auth; }\n\n private IAuthorization _auth;\n\n public EntityInfo GetEntityInfo(string entityId)\n {\n _auth.CheckAccessPermission(PermissionType.GetEntity, \n user, entityId);\n\n //Get the entity info\n }\n}\n</code></pre>\n\n<p>Note that IAuthorization is an interface that you would define. </p>\n\n<p>Because you are going to be testing the service type directly (that is, without running it inside the WCF hosting framework) you simply set up your service to use a dummy IAuthorization type that allows all calls. However, an even BETTER test is to mock the IAuthorization and test that it is called when and with the parameters that you expect. This allows you to test that your calls to the authorization methods are valid, along with the method itself.</p>\n\n<p>Separating the authorization into it's own type also allows you to more easily test that it is correct in isolation. In my (albeit limited) experience, using DI \"patterns\" give you vastly better separation of concerns and testability in your types as well as leading to a cleaner interface (this is obviously open to debate).</p>\n\n<p>My preferred mocking framework is <a href=\"http://ayende.com/projects/rhino-mocks.aspx\" rel=\"nofollow noreferrer\">RhinoMocks</a> which is free and has very nice fluent interface but there are lots of others out there. If you'd like to know more about DI here are some good primers and .Net frameworks:</p>\n\n<ul>\n<li><a href=\"http://www.martinfowler.com/articles/injection.html\" rel=\"nofollow noreferrer\">Martin Fowler on DI</a></li>\n<li><a href=\"http://codebetter.com/blogs/jeremy.miller/archive/2005/10/06/132825.aspx\" rel=\"nofollow noreferrer\">Jeremy Miller on DI</a></li>\n<li><a href=\"http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx\" rel=\"nofollow noreferrer\">Scott Hanselman's List of DI Containers</a></li>\n<li>My personal favorite DI container: <a href=\"http://www.castleproject.org/container/index.html\" rel=\"nofollow noreferrer\">The Castle Project Windsor Container</a></li>\n</ul>\n"
}
]
| 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 groovy.jar file) you can use Groovy's GString feature to do this quite nicely. </p>\n\n<p>Groovy example</p>\n\n<pre><code>foxtype = 'quick'\nfoxcolor = ['b', 'r', 'o', 'w', 'n']\nprintln \"The $foxtype ${foxcolor.join()} fox\"\n</code></pre>\n\n<p>Spring JDBC has a feature that I use to support named and nested named bind variables from beans like this:</p>\n\n<pre><code>public int countOfActors(Actor exampleActor) {\n\n // notice how the named parameters match the properties of the above 'Actor' class\n String sql = \"select count(0) from T_ACTOR where first_name = :firstName and last_name = :lastName\";\n\n SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(exampleActor);\n\n return this.namedParameterJdbcTemplate.queryForInt(sql, namedParameters);\n}\n</code></pre>\n"
},
{
"answer_id": 145173,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n\n<pre><code>import java.lang.reflect.InvocationTargetException;\nimport java.util.Map;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.apache.commons.beanutils.BeanUtils;\n\npublic class BeanUtilsReplacer\n{\n private static Pattern lookupPattern = Pattern.compile(\"\\\\$\\\\{([^\\\\}]+)\\\\}\");\n\n public static String replaceString(String input, Map<String, Object> context)\n throws IllegalAccessException, InvocationTargetException, NoSuchMethodException\n {\n int position = 0;\n StringBuffer result = new StringBuffer();\n\n Matcher m = lookupPattern.matcher(input);\n while (m.find())\n {\n result.append(input.substring(position, m.start()));\n result.append(BeanUtils.getNestedProperty(context, m.group(1)));\n position = m.end();\n }\n\n if (position == 0)\n {\n return input;\n }\n else\n {\n result.append(input.substring(position));\n return result.toString();\n }\n }\n}\n</code></pre>\n\n<p>Given the variables provided in your question:</p>\n\n<pre><code>Map<String, Object> context = new HashMap<String, Object>();\ncontext.put(\"user\", user);\nSystem.out.println(BeanUtilsReplacer.replaceString(s, context));\n</code></pre>\n"
},
{
"answer_id": 145477,
"author": "Tom",
"author_id": 22850,
"author_profile": "https://Stackoverflow.com/users/22850",
"pm_score": 1,
"selected": false,
"text": "<p>Your string example is a valid template in at least a few templating engines, like Velocity or Freemarker. These libraries offer a way to merge a template with a context containing some objects (like 'user' in your example).</p>\n\n<p>See <a href=\"http://velocity.apache.org/\" rel=\"nofollow noreferrer\">http://velocity.apache.org/</a> or <a href=\"http://www.freemarker.org/\" rel=\"nofollow noreferrer\">http://www.freemarker.org/</a></p>\n\n<p>Some example code (from the Freemarker site):</p>\n\n<pre><code> /* ------------------------------------------------------------------- */ \n /* You usually do it only once in the whole application life-cycle: */ \n\n /* Create and adjust the configuration */\n Configuration cfg = new Configuration();\n cfg.setDirectoryForTemplateLoading(\n new File(\"/where/you/store/templates\"));\n cfg.setObjectWrapper(new DefaultObjectWrapper());\n\n /* ------------------------------------------------------------------- */ \n /* You usually do these for many times in the application life-cycle: */ \n\n /* Get or create a template */\n Template temp = cfg.getTemplate(\"test.ftl\");\n\n /* Create a data-model */\n Map root = new HashMap();\n root.put(\"user\", \"Big Joe\");\n Map latest = new HashMap();\n root.put(\"latestProduct\", latest);\n latest.put(\"url\", \"products/greenmouse.html\");\n latest.put(\"name\", \"green mouse\");\n\n /* Merge data-model with template */\n Writer out = new OutputStreamWriter(System.out);\n temp.process(root, out);\n out.flush();\n</code></pre>\n"
}
]
| 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 it's tail-recursion optimizations. I am not sure how well OCaml will deal with the current implementation, <code>List.rev</code> is tail-recursive though. You'll notice that in <a href=\"http://caml.inria.fr/pub/old_caml_site/caml-list/2115.html\" rel=\"nofollow noreferrer\">this post</a> it is done like that.</p>\n<p>Also, you can make the resolution of the iteration be an optional argument like <code>?(epsilon=0.1)</code>.</p>\n<p>As an ocaml programmer I don't see much wrong here aside from that --as long as P1 and P2 are in fact constants. Compile it down and see what the difference in assembly is between moving List.rev inside or out of the tail-recursion.</p>\n"
},
{
"answer_id": 146000,
"author": "Thelema",
"author_id": 12874,
"author_profile": "https://Stackoverflow.com/users/12874",
"pm_score": 3,
"selected": true,
"text": "<p>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:</p>\n\n<pre><code>let b i = \n let t = i /. n in\n let tminus = (1.-.t) in\n (tminus *. tminus *. p0) +. (2. *. t *. tminus *. p1) +. (t *. t * p2)\nin\nList.map b ([generate list 1.0; 2.0; ... n.0])\n</code></pre>\n\n<p>A function to generate the list 1.0...n.0 could be: (for small n)</p>\n\n<pre><code>let rec count m n = if m > n then [] else m :: (count (m+.1.) n)\n</code></pre>\n"
}
]
| 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 in that there is no need to learn C separately. </p>\n\n<p>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.</p>\n\n<p><strong>Examples of why it is not a strict superset:</strong></p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/C%2B%2B\" rel=\"noreferrer\">This Wikipedia article</a> has a couple good examples of such a differences:</p>\n\n<blockquote>\n <p>One commonly encountered difference is\n that C allows implicit conversion from\n void* to other pointer types, but C++\n does not. So, the following is valid C\n code:</p>\n\n<pre><code>int *i = malloc(sizeof(int) * 5); \n</code></pre>\n \n <p>... but to make it work in both C and\n C++ one would need to use an explicit\n cast:</p>\n\n<pre><code>int *i = (int *) malloc(sizeof(int) * 5)\n</code></pre>\n \n <p>Another common portability issue is\n that C++ defines many new keywords,\n such as new and class, that may be\n used as identifiers (e.g. variable\n names) in a C program.</p>\n</blockquote>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B\" rel=\"noreferrer\">This wikipedia article</a> has further differences as well:</p>\n\n<blockquote>\n <p>C++ compilers prohibit goto from crossing an initialization, as in the following C99 code:</p>\n</blockquote>\n\n<pre><code> void fn(void)\n {\n goto flack;\n int i = 1;\n flack:\n ;\n }\n</code></pre>\n\n<p><strong>What should you learn first?</strong></p>\n\n<p>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++.</p>\n"
},
{
"answer_id": 145099,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>It is true that for most purposes, C++ contains everything that C does. Language lawyers will be quick to point out that there are some very special edge cases that are valid C but not valid C++.</p>\n\n<p>One such example might be the C declaration</p>\n\n<pre><code>int virtual;\n</code></pre>\n\n<p>which declares an integer named \"virtual\". Since \"virtual\" is a keyword in C++, this is not valid C++.</p>\n"
},
{
"answer_id": 145101,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 2,
"selected": false,
"text": "<p>I personally would disagree with your professor. </p>\n\n<p>Generally speaking, C++ is based on C and in that \"sense\" contains it and extends it.</p>\n\n<p>However, since traditionally people learned C and only then the extensions of C++, your professor's statement is incorrect since to use C++ correctly you would need to master the C origins. It is possible that when teaching you something, your professor or textbook will not specifically mention what came from which language.</p>\n\n<p>In addition, it is important to understand that despite the similarities, not every C program runs in the same way under C++. For example, C structs are interpreted differently (as classes with everything public) by the C++ compiler.</p>\n\n<p>When I teach, I teach the C core first, and then go to C++.</p>\n"
},
{
"answer_id": 145109,
"author": "orlando calresian",
"author_id": 21165,
"author_profile": "https://Stackoverflow.com/users/21165",
"pm_score": 2,
"selected": false,
"text": "<p>No C++ isn't really a superset of C. You can check this article for a more extensive list of the differences if you're interested:\n<a href=\"http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Compatibility_of_C_and_C%2B%2B</a></p>\n"
},
{
"answer_id": 145117,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 4,
"selected": false,
"text": "<p>While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.</p>\n\n<p>There was a term of art called using C++ as a better C. This meant using some C++ language features and tools to make C programming easier (e.g., declaring the index variable of a for loop within the for statement). But now, modern C++ development seems very different from C other than a great deal of the syntax and in those cases the C legacy often seems to be a burden rather than a benefit.</p>\n"
},
{
"answer_id": 145136,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 2,
"selected": false,
"text": "<p>There is a large common core of C (especially C89) and C++, but there are most certainly areas of difference between C and C++. Obviously, C++ has all the object-oriented features, plus the generic programming, plus exceptions, plus namespaces that C does not. However, there are also features of C that are not in C++, such as support for the (close to archaic) non-prototype notation for declaring and defining functions. In particular, the meaning of the following function declaration is different in C and C++:</p>\n\n<pre><code>extern void function();\n</code></pre>\n\n<p>In C++, that is a function that returns no value and takes no parameters (and, therefore, is called solely for its side-effects, whatever they are). In C, that is a function which returns no value but for which there is no information about the argument list. C still does not require a declaration in scope before a function is called (in general; you must have a declaration in scope if the function takes a variable list of arguments, so it is critical to <code>#include <stdio.h></code> before using <code>printf()</code>, etc).</p>\n\n<p>There are also differences:</p>\n\n<pre><code>sizeof('c')\n</code></pre>\n\n<p>In C++, the answer is 1; in C, the answer is normally 4 (32-bit systems with 8-bit characters) or even 8 (64-bit systems with 64-bit int).</p>\n\n<p>In general, you can write code that will compile under both C and C++ compilers without much difficulty - the majority of my code does that all the time. The exceptions are either a result of carelessness on my part, or because I've consciously exploited the good features of C99 that are not in C++ 98, such as designated initializers, or <code>long long</code>.</p>\n"
},
{
"answer_id": 145137,
"author": "Zathrus",
"author_id": 16220,
"author_profile": "https://Stackoverflow.com/users/16220",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://public.research.att.com/~bs/bs_faq.html#C-is-subset\" rel=\"nofollow noreferrer\">Not entirely true.</a></p>\n\n<p>The biggest \"gotcha\" is typing -- C++ is much more strongly typed than C is, and the preferred methods for solving this in C++ are simply not available in C. Namely, you can silently cast between types in C (particularly pointer types), but not in C++. And C++ <em>highly</em> recommends using the static_cast/reinterpret_cast/const_cast methods for resolving these issues.</p>\n\n<p>More importantly, if you learn C++ syntax and mannerisms, you'll probably find it difficult to deal with C (some may say this is good; and I prefer C++ myself, but sometimes it just isn't an option, or you have to deal with legacy code that's in C and not C++). Again, the most likely issues you'll encounter are dealing with pointers (particularly char*'s and general array usage; in C++ using std::string and std::vector or other collections is simply <strong>better</strong>).</p>\n\n<p>It's certainly possible to learn C++, and then learn the differences between C and C++ and be capable of programming in both. But the differences are far more than just skin deep.</p>\n"
},
{
"answer_id": 145248,
"author": "shoosh",
"author_id": 9611,
"author_profile": "https://Stackoverflow.com/users/9611",
"pm_score": 3,
"selected": false,
"text": "<p>It might be true that you don't need to learn the syntax of C if you know the syntax of C++ but you cetainly do need to learn of how coding practices are different in C than in C++.</p>\n\n<p>So your professor wasn't 100% right.<br>\nIn C you don't have the classes to arrange your code into logical modules and you don't have C++ polymorphism. Yet you still need to achieve these goals somehow.<br>\nalthough the syntax of C is to some extent a subset of C++, <strong>programming</strong> in C is not a subset of programming in C++. it is completely different.</p>\n"
},
{
"answer_id": 145333,
"author": "Thomas Padron-McCarthy",
"author_id": 15727,
"author_profile": "https://Stackoverflow.com/users/15727",
"pm_score": 3,
"selected": false,
"text": "<p>Yes and no.</p>\n\n<p>As others have already answered, the language C++ is a superset of the language C, with some small exceptions, for example that sizeof('x') gives a different value.</p>\n\n<p>But what I don't think has been very clearly stated is that when it comes to the <em>use</em> of these two languages, C++ is not a superset, but rather different. C++ contains new (it can be discussed if they are better) ways of doing the basic things, such as writing to the screen. The old C ways are still there, but you generally use the new ways. This means that a simple \"hello world\" program looks different in C and in C++. So it is not really true that the simple things are the same in C and C++, and then you just add more advanced stuff, such as support for object-oriented programming, in C++.</p>\n\n<p>So if you have learnt C++, you will need to re-learn quite a lot before you can program in C. (Well, it is possible to teach C++ as an extension to C, still using printf and malloc instead of iostreams and new, and then adding classes and other C++ things, but that way of using C++ is generally frowned upon.)</p>\n"
},
{
"answer_id": 1354264,
"author": "Steve Melnikoff",
"author_id": 45552,
"author_profile": "https://Stackoverflow.com/users/45552",
"pm_score": 0,
"selected": false,
"text": "<p>If any of the students in the class intend to become embedded software engineers, then they may have no choice but to program in C (see <a href=\"https://stackoverflow.com/questions/812717/is-there-any-reason-to-use-c-instead-of-c-for-embedded-development/815197#815197\">this question</a>, and <a href=\"https://stackoverflow.com/questions/1223710/we-have-to-use-c-for-performance-reasons\">this one</a>, among others).</p>\n\n<p>Of course, having learnt C++, it may be less of a transition for them than starting from scratch - but it still makes your professor's statement untrue!</p>\n"
},
{
"answer_id": 1453613,
"author": "Kensai",
"author_id": 108477,
"author_profile": "https://Stackoverflow.com/users/108477",
"pm_score": 2,
"selected": false,
"text": "<p><strong>Stroustrup</strong> himself <a href=\"http://www.research.att.com/~bs/bs_faq.html#prerequisite\" rel=\"nofollow noreferrer\">advices <em>against</em></a> learning C first. But then again, he (and many others of his generation) managed to become a C++ guru starting from C.</p>\n"
}
]
| 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 MySingleton\n\n+ (MySingleton *)sharedSingleton\n{\n static MySingleton *sharedSingleton;\n\n @synchronized(self)\n {\n if (!sharedSingleton)\n sharedSingleton = [[MySingleton alloc] init];\n\n return sharedSingleton;\n }\n}\n\n@end\n</code></pre>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Singleton_pattern#Objective-C\" rel=\"noreferrer\">[Source]</a></p>\n"
},
{
"answer_id": 145221,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<pre>\nstatic MyClass *sharedInst = nil;\n\n+ (id)sharedInstance\n{\n @synchronize( self ) {\n if ( sharedInst == nil ) {\n /* sharedInst set up in init */\n [[self alloc] init];\n }\n }\n return sharedInst;\n}\n\n- (id)init\n{\n if ( sharedInst != nil ) {\n [NSException raise:NSInternalInconsistencyException\n format:@\"[%@ %@] cannot be called; use +[%@ %@] instead\"],\n NSStringFromClass([self class]), NSStringFromSelector(_cmd), \n NSStringFromClass([self class]),\n NSStringFromSelector(@selector(sharedInstance)\"];\n } else if ( self = [super init] ) {\n sharedInst = self;\n /* Whatever class specific here */\n }\n return sharedInst;\n}\n\n/* These probably do nothing in\n a GC app. Keeps singleton\n as an actual singleton in a\n non CG app\n*/\n- (NSUInteger)retainCount\n{\n return NSUIntegerMax;\n}\n\n- (oneway void)release\n{\n}\n\n- (id)retain\n{\n return sharedInst;\n}\n\n- (id)autorelease\n{\n return sharedInst;\n}\n</pre>\n"
},
{
"answer_id": 145232,
"author": "lajos",
"author_id": 3740,
"author_profile": "https://Stackoverflow.com/users/3740",
"pm_score": 2,
"selected": false,
"text": "<p>This works in a non-garbage collected environment also.</p>\n\n<pre><code>@interface MySingleton : NSObject {\n}\n\n+(MySingleton *)sharedManager;\n\n@end\n\n\n@implementation MySingleton\n\nstatic MySingleton *sharedMySingleton = nil;\n\n+(MySingleton*)sharedManager {\n @synchronized(self) {\n if (sharedMySingleton == nil) {\n [[self alloc] init]; // assignment not done here\n }\n }\n return sharedMySingleton;\n}\n\n\n+(id)allocWithZone:(NSZone *)zone {\n @synchronized(self) {\n if (sharedMySingleton == nil) {\n sharedMySingleton = [super allocWithZone:zone];\n return sharedMySingleton; // assignment and return on first allocation\n }\n }\n return nil; //on subsequent allocation attempts return nil\n}\n\n\n-(void)dealloc {\n [super dealloc];\n}\n\n-(id)copyWithZone:(NSZone *)zone {\n return self;\n}\n\n\n-(id)retain {\n return self;\n}\n\n\n-(unsigned)retainCount {\n return UINT_MAX; //denotes an object that cannot be release\n}\n\n\n-(void)release {\n //do nothing \n}\n\n\n-(id)autorelease {\n return self; \n}\n\n\n-(id)init {\n self = [super init];\n sharedMySingleton = self;\n\n //initialize here\n\n return self;\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 145395,
"author": "Colin Barrett",
"author_id": 23106,
"author_profile": "https://Stackoverflow.com/users/23106",
"pm_score": 6,
"selected": false,
"text": "<p>Per my other answer below, I think you should be doing:</p>\n\n<pre><code>+ (id)sharedFoo\n{\n static dispatch_once_t once;\n static MyFoo *sharedFoo;\n dispatch_once(&once, ^ { sharedFoo = [[self alloc] init]; });\n return sharedFoo;\n}\n</code></pre>\n"
},
{
"answer_id": 343191,
"author": "Robbie Hanson",
"author_id": 43522,
"author_profile": "https://Stackoverflow.com/users/43522",
"pm_score": 9,
"selected": true,
"text": "<p>Another option is to use the <code>+(void)initialize</code> method. From the documentation:</p>\n\n<blockquote>\n <p>The runtime sends <code>initialize</code> 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 <code>initialize</code> message to classes in a thread-safe manner. Superclasses receive this message before their subclasses.</p>\n</blockquote>\n\n<p>So you could do something akin to this:</p>\n\n<pre><code>static MySingleton *sharedSingleton;\n\n+ (void)initialize\n{\n static BOOL initialized = NO;\n if(!initialized)\n {\n initialized = YES;\n sharedSingleton = [[MySingleton alloc] init];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1032127,
"author": "Matthieu Cormier",
"author_id": 90244,
"author_profile": "https://Stackoverflow.com/users/90244",
"pm_score": 3,
"selected": false,
"text": "<p>A thorough explanation of the Singleton macro code is on the blog Cocoa With Love</p>\n\n<p><a href=\"http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html\" rel=\"nofollow noreferrer\">http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html</a>.</p>\n"
},
{
"answer_id": 1036460,
"author": "Gregory Higley",
"author_id": 27779,
"author_profile": "https://Stackoverflow.com/users/27779",
"pm_score": -1,
"selected": false,
"text": "<p>I usually use code roughly similar to that in Ben Hoffstein's answer (which I also got out of Wikipedia). I use it for the reasons stated by Chris Hanson in his comment.</p>\n\n<p>However, sometimes I have a need to place a singleton into a NIB, and in that case I use the following:</p>\n\n<pre><code>@implementation Singleton\n\nstatic Singleton *singleton = nil;\n\n- (id)init {\n static BOOL initialized = NO;\n if (!initialized) {\n self = [super init];\n singleton = self;\n initialized = YES;\n }\n return self;\n}\n\n+ (id)allocWithZone:(NSZone*)zone {\n @synchronized (self) {\n if (!singleton)\n singleton = [super allocWithZone:zone]; \n }\n return singleton;\n}\n\n+ (Singleton*)sharedSingleton {\n if (!singleton)\n [[Singleton alloc] init];\n return singleton;\n}\n\n@end\n</code></pre>\n\n<p>I leave the implementation of <code>-retain</code> (etc.) to the reader, although the above code is all you need in a garbage collected environment.</p>\n"
},
{
"answer_id": 2060615,
"author": "Rob Dotson",
"author_id": 250263,
"author_profile": "https://Stackoverflow.com/users/250263",
"pm_score": 0,
"selected": false,
"text": "<p>You don't want to synchronize on self... Since the self object doesn't exist yet! You end up locking on a temporary id value. You want to ensure that no one else can run class methods ( sharedInstance, alloc, allocWithZone:, etc ), so you need to synchronize on the class object instead:</p>\n\n<pre><code>@implementation MYSingleton\n\nstatic MYSingleton * sharedInstance = nil;\n\n+( id )sharedInstance {\n @synchronized( [ MYSingleton class ] ) {\n if( sharedInstance == nil )\n sharedInstance = [ [ MYSingleton alloc ] init ];\n }\n\n return sharedInstance;\n}\n\n+( id )allocWithZone:( NSZone * )zone {\n @synchronized( [ MYSingleton class ] ) {\n if( sharedInstance == nil )\n sharedInstance = [ super allocWithZone:zone ];\n }\n\n return sharedInstance;\n}\n\n-( id )init {\n @synchronized( [ MYSingleton class ] ) {\n self = [ super init ];\n if( self != nil ) {\n // Insert initialization code here\n }\n\n return self;\n }\n}\n\n@end\n</code></pre>\n"
},
{
"answer_id": 2294440,
"author": "Kendall Helmstetter Gelner",
"author_id": 6330,
"author_profile": "https://Stackoverflow.com/users/6330",
"pm_score": 3,
"selected": false,
"text": "<p>I have an interesting variation on sharedInstance that is thread safe, but does not lock after the initialization. I am not yet sure enough of it to modify the top answer as requested, but I present it for further discussion:</p>\n\n<pre><code>// Volatile to make sure we are not foiled by CPU caches\nstatic volatile ALBackendRequestManager *sharedInstance;\n\n// There's no need to call this directly, as method swizzling in sharedInstance\n// means this will get called after the singleton is initialized.\n+ (MySingleton *)simpleSharedInstance\n{\n return (MySingleton *)sharedInstance;\n}\n\n+ (MySingleton*)sharedInstance\n{\n @synchronized(self)\n {\n if (sharedInstance == nil)\n {\n sharedInstance = [[MySingleton alloc] init];\n // Replace expensive thread-safe method \n // with the simpler one that just returns the allocated instance.\n SEL origSel = @selector(sharedInstance);\n SEL newSel = @selector(simpleSharedInstance);\n Method origMethod = class_getClassMethod(self, origSel);\n Method newMethod = class_getClassMethod(self, newSel);\n method_exchangeImplementations(origMethod, newMethod);\n }\n }\n return (MySingleton *)sharedInstance;\n}\n</code></pre>\n"
},
{
"answer_id": 2361280,
"author": "CJ Hanson",
"author_id": 150383,
"author_profile": "https://Stackoverflow.com/users/150383",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://github.com/cjhanson/Objective-C-Optimized-Singleton\" rel=\"nofollow noreferrer\">Here's a macro</a> that I put together:</p>\n\n<p><a href=\"http://github.com/cjhanson/Objective-C-Optimized-Singleton\" rel=\"nofollow noreferrer\">http://github.com/cjhanson/Objective-C-Optimized-Singleton</a></p>\n\n<p>It is based on <a href=\"http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html\" rel=\"nofollow noreferrer\">the work here by Matt Gallagher</a>\nBut changing the implementation to use <a href=\"http://googlemac.blogspot.com/2006/11/synchronized-swimming-part-2.html\" rel=\"nofollow noreferrer\">method swizzling as described here by Dave MacLachlan of Google</a>.</p>\n\n<p>I welcome comments / contributions.</p>\n"
},
{
"answer_id": 2449664,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 6,
"selected": false,
"text": "<p>Since <a href=\"https://stackoverflow.com/questions/145154/what-does-your-objective-c-singleton-look-like/2294440#2294440\">Kendall posted</a> a threadsafe singleton that attempts to avoid locking costs, I thought I would toss one up as well:</p>\n\n<pre><code>#import <libkern/OSAtomic.h>\n\nstatic void * volatile sharedInstance = nil; \n\n+ (className *) sharedInstance { \n while (!sharedInstance) { \n className *temp = [[self alloc] init]; \n if(!OSAtomicCompareAndSwapPtrBarrier(0x0, temp, &sharedInstance)) {\n [temp release]; \n } \n } \n return sharedInstance; \n}\n</code></pre>\n\n<p>Okay, let me explain how this works:</p>\n\n<ol>\n<li><p>Fast case: In normal execution <code>sharedInstance</code> has already been set, so the <code>while</code> loop is never executed and the function returns after simply testing for the variable's existence;</p></li>\n<li><p>Slow case: If <code>sharedInstance</code> doesn't exist, then an instance is allocated and copied into it using a Compare And Swap ('CAS');</p></li>\n<li><p>Contended case: If two threads both attempt to call <code>sharedInstance</code> at the same time <em>AND</em> <code>sharedInstance</code> doesn't exist at the same time then they will both initialize new instances of the singleton and attempt to CAS it into position. Whichever one wins the CAS returns immediately, whichever one loses releases the instance it just allocated and returns the (now set) <code>sharedInstance</code>. The single <code>OSAtomicCompareAndSwapPtrBarrier</code> acts as both a write barrier for the setting thread and a read barrier from the testing thread.</p></li>\n</ol>\n"
},
{
"answer_id": 2461717,
"author": "Jompe",
"author_id": 295600,
"author_profile": "https://Stackoverflow.com/users/295600",
"pm_score": 2,
"selected": false,
"text": "<p>Shouln't this be threadsafe and avoid the expensive locking after the first call?</p>\n\n<pre><code>+ (MySingleton*)sharedInstance\n{\n if (sharedInstance == nil) {\n @synchronized(self) {\n if (sharedInstance == nil) {\n sharedInstance = [[MySingleton alloc] init];\n }\n }\n }\n return (MySingleton *)sharedInstance;\n}\n</code></pre>\n"
},
{
"answer_id": 2886058,
"author": "Fred McCann",
"author_id": 347534,
"author_profile": "https://Stackoverflow.com/users/347534",
"pm_score": 2,
"selected": false,
"text": "<p>For an in-depth discussion of the singleton pattern in Objective-C, look here:</p>\n\n<p><a href=\"http://www.duckrowing.com/2010/05/21/using-the-singleton-pattern-in-objective-c\" rel=\"nofollow noreferrer\">Using the Singleton Pattern in Objective-C</a></p>\n"
},
{
"answer_id": 3068795,
"author": "user370199",
"author_id": 370199,
"author_profile": "https://Stackoverflow.com/users/370199",
"pm_score": 0,
"selected": false,
"text": "<pre><code>static mySingleton *obj=nil;\n\n@implementation mySingleton\n\n-(id) init {\n if(obj != nil){ \n [self release];\n return obj;\n } else if(self = [super init]) {\n obj = self;\n } \n return obj;\n}\n\n+(mySingleton*) getSharedInstance {\n @synchronized(self){\n if(obj == nil) {\n obj = [[mySingleton alloc] init];\n }\n }\n return obj;\n}\n\n- (id)retain {\n return self;\n}\n\n- (id)copy {\n return self;\n}\n\n- (unsigned)retainCount {\n return UINT_MAX; // denotes an object that cannot be released\n}\n\n- (void)release {\n if(obj != self){\n [super release];\n }\n //do nothing\n}\n\n- (id)autorelease {\n return self;\n}\n\n-(void) dealloc {\n [super dealloc];\n}\n@end\n</code></pre>\n"
},
{
"answer_id": 4312421,
"author": "obscenum",
"author_id": 524927,
"author_profile": "https://Stackoverflow.com/users/524927",
"pm_score": 3,
"selected": false,
"text": "<p>I've rolled singleton into a class, so other classes can inherit singleton properties.</p>\n\n<p>Singleton.h :</p>\n\n<pre><code>static id sharedInstance = nil;\n\n#define DEFINE_SHARED_INSTANCE + (id) sharedInstance { return [self sharedInstance:&sharedInstance]; } \\\n + (id) allocWithZone:(NSZone *)zone { return [self allocWithZone:zone forInstance:&sharedInstance]; }\n\n@interface Singleton : NSObject {\n\n}\n\n+ (id) sharedInstance;\n+ (id) sharedInstance:(id*)inst;\n\n+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst;\n\n@end\n</code></pre>\n\n<p>Singleton.m :</p>\n\n<pre><code>#import \"Singleton.h\"\n\n\n@implementation Singleton\n\n\n+ (id) sharedInstance { \n return [self sharedInstance:&sharedInstance];\n}\n\n+ (id) sharedInstance:(id*)inst {\n @synchronized(self)\n {\n if (*inst == nil)\n *inst = [[self alloc] init];\n }\n return *inst;\n}\n\n+ (id) allocWithZone:(NSZone *)zone forInstance:(id*)inst {\n @synchronized(self) {\n if (*inst == nil) {\n *inst = [super allocWithZone:zone];\n return *inst; // assignment and return on first allocation\n }\n }\n return nil; // on subsequent allocation attempts return nil\n}\n\n- (id)copyWithZone:(NSZone *)zone {\n return self;\n}\n\n- (id)retain {\n return self;\n}\n\n- (unsigned)retainCount {\n return UINT_MAX; // denotes an object that cannot be released\n}\n\n- (void)release {\n //do nothing\n}\n\n- (id)autorelease {\n return self;\n}\n\n\n@end\n</code></pre>\n\n<p>And here is an example of some class, that you want to become singleton.</p>\n\n<pre><code>#import \"Singleton.h\"\n\n@interface SomeClass : Singleton {\n\n}\n\n@end\n\n@implementation SomeClass \n\nDEFINE_SHARED_INSTANCE;\n\n@end\n</code></pre>\n\n<p>The only limitation about Singleton class, is that it is NSObject subclass. But most time I use singletons in my code they are in fact NSObject subclasses, so this class really ease my life and make code cleaner.</p>\n"
},
{
"answer_id": 4708837,
"author": "Dan Rosenstark",
"author_id": 8047,
"author_profile": "https://Stackoverflow.com/users/8047",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to leave this here so I don't lose it. The advantage to this one is that it's usable in InterfaceBuilder, which is a HUGE advantage. <a href=\"https://stackoverflow.com/questions/4609609/use-singleton-in-interface-builder\">This is taken from another question that I asked</a>:</p>\n\n<pre><code>static Server *instance;\n\n+ (Server *)instance { return instance; }\n\n+ (id)hiddenAlloc\n{\n return [super alloc];\n}\n\n+ (id)alloc\n{\n return [[self instance] retain];\n}\n\n\n+ (void)initialize\n{\n static BOOL initialized = NO;\n if(!initialized)\n {\n initialized = YES;\n instance = [[Server hiddenAlloc] init];\n }\n}\n\n- (id) init\n{\n if (instance)\n return self;\n self = [super init];\n if (self != nil) {\n // whatever\n }\n return self;\n}\n</code></pre>\n"
},
{
"answer_id": 4777258,
"author": "deleted_user",
"author_id": 490696,
"author_profile": "https://Stackoverflow.com/users/490696",
"pm_score": -1,
"selected": false,
"text": "<p>The accepted answer, although it compiles, is incorrect.</p>\n\n<pre><code>+ (MySingleton*)sharedInstance\n{\n @synchronized(self) <-------- self does not exist at class scope\n {\n if (sharedInstance == nil)\n sharedInstance = [[MySingleton alloc] init];\n }\n return sharedInstance;\n}\n</code></pre>\n\n<p>Per Apple documentation:</p>\n\n<p>... You can take a similar approach to synchronize the class methods of the associated class, using the Class object instead of self.</p>\n\n<p>Even if using self works, it shouldn't and this looks like a copy and paste mistake to me.\nThe correct implementation for a class factory method would be:</p>\n\n<pre><code>+ (MySingleton*)getInstance\n{\n @synchronized([MySingleton class]) \n {\n if (sharedInstance == nil)\n sharedInstance = [[MySingleton alloc] init];\n }\n return sharedInstance;\n}\n</code></pre>\n"
},
{
"answer_id": 6271064,
"author": "lorean",
"author_id": 717439,
"author_profile": "https://Stackoverflow.com/users/717439",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Edit: This implementation obsoleted with ARC. Please have a look at <a href=\"https://stackoverflow.com/questions/7568935/how-do-i-implement-an-objective-c-singleton-that-is-compatible-with-arc\">How do I implement an Objective-C singleton that is compatible with ARC?</a> for correct implementation.</strong></p>\n\n<p>All the implementations of initialize I've read in other answers share a common error.</p>\n\n<pre><code>+ (void) initialize {\n _instance = [[MySingletonClass alloc] init] // <----- Wrong!\n}\n\n+ (void) initialize {\n if (self == [MySingletonClass class]){ // <----- Correct!\n _instance = [[MySingletonClass alloc] init] \n }\n}\n</code></pre>\n\n<p>The Apple documentation recommend you check the class type in your initialize block. Because subclasses call the initialize by default. There exists a non-obvious case where subclasses may be created indirectly through KVO. For if you add the following line in another class:</p>\n\n<pre><code>[[MySingletonClass getInstance] addObserver:self forKeyPath:@\"foo\" options:0 context:nil]\n</code></pre>\n\n<p>Objective-C will implicitly create a subclass of MySingletonClass resulting in a second triggering of <code>+initialize</code>.</p>\n\n<p>You may think that you should implicitly check for duplicate initialization in your init block as such:</p>\n\n<pre><code>- (id) init { <----- Wrong!\n if (_instance != nil) {\n // Some hack\n }\n else {\n // Do stuff\n }\n return self;\n}\n</code></pre>\n\n<p>But you will shoot yourself in the foot; or worse give another developer the opportunity to shoot themselves in the foot.</p>\n\n<pre><code>- (id) init { <----- Correct!\n NSAssert(_instance == nil, @\"Duplication initialization of singleton\");\n self = [super init];\n if (self){\n // Do stuff\n }\n return self;\n}\n</code></pre>\n\n<p><strong>TL;DR, here's my implementation</strong></p>\n\n<pre><code>@implementation MySingletonClass\nstatic MySingletonClass * _instance;\n+ (void) initialize {\n if (self == [MySingletonClass class]){\n _instance = [[MySingletonClass alloc] init];\n }\n}\n\n- (id) init {\n ZAssert (_instance == nil, @\"Duplication initialization of singleton\");\n self = [super init];\n if (self) {\n // Initialization\n }\n return self;\n}\n\n+ (id) getInstance {\n return _instance;\n}\n@end\n</code></pre>\n\n<p>(Replace ZAssert with our own assertion macro; or just NSAssert.)</p>\n"
},
{
"answer_id": 8232992,
"author": "Nate",
"author_id": 761771,
"author_profile": "https://Stackoverflow.com/users/761771",
"pm_score": 0,
"selected": false,
"text": "<p>I know there are a lot of comments on this \"question\", but I don't see many people suggesting using a macro to define the singleton. It's such a common pattern and a macro greatly simplifies the singleton.</p>\n\n<p>Here are the macros I wrote based on several Objc implementations I've seen.</p>\n\n<p><code>Singeton.h</code></p>\n\n<pre><code>/**\n @abstract Helps define the interface of a singleton.\n @param TYPE The type of this singleton.\n @param NAME The name of the singleton accessor. Must match the name used in the implementation.\n @discussion\n Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.\n */\n#define SingletonInterface(TYPE, NAME) \\\n+ (TYPE *)NAME;\n\n\n/**\n @abstract Helps define the implementation of a singleton.\n @param TYPE The type of this singleton.\n @param NAME The name of the singleton accessor. Must match the name used in the interface.\n @discussion\n Typcially the NAME is something like 'sharedThing' where 'Thing' is the prefix-removed type name of the class.\n */\n#define SingletonImplementation(TYPE, NAME) \\\nstatic TYPE *__ ## NAME; \\\n\\\n\\\n+ (void)initialize \\\n{ \\\n static BOOL initialized = NO; \\\n if(!initialized) \\\n { \\\n initialized = YES; \\\n __ ## NAME = [[TYPE alloc] init]; \\\n } \\\n} \\\n\\\n\\\n+ (TYPE *)NAME \\\n{ \\\n return __ ## NAME; \\\n}\n</code></pre>\n\n<p>Example of use:</p>\n\n<p><code>MyManager.h</code></p>\n\n<pre><code>@interface MyManager\n\nSingletonInterface(MyManager, sharedManager);\n\n// ...\n\n@end\n</code></pre>\n\n<p><code>MyManager.m</code></p>\n\n<pre><code>@implementation MyManager\n\n- (id)init\n{\n self = [super init];\n if (self) {\n // Initialization code here.\n }\n\n return self;\n}\n\nSingletonImplementation(MyManager, sharedManager);\n\n// ...\n\n@end\n</code></pre>\n\n<p>Why a interface macro when it's nearly empty? Code consistency between the header and code files; maintainability in case you want to add more automatic methods or change it around.</p>\n\n<p>I'm using the initialize method to create the singleton as is used in the most popular answer here (at time of writing).</p>\n"
},
{
"answer_id": 8671831,
"author": "Tony",
"author_id": 692499,
"author_profile": "https://Stackoverflow.com/users/692499",
"pm_score": 2,
"selected": false,
"text": "<p>How about </p>\n\n<pre><code>static MyClass *gInstance = NULL;\n\n+ (MyClass *)instance\n{\n if (gInstance == NULL) {\n @synchronized(self)\n {\n if (gInstance == NULL)\n gInstance = [[self alloc] init];\n }\n }\n\n return(gInstance);\n}\n</code></pre>\n\n<p>So you avoid the synchronization cost after initialization?</p>\n"
},
{
"answer_id": 9187363,
"author": "quellish",
"author_id": 1059025,
"author_profile": "https://Stackoverflow.com/users/1059025",
"pm_score": 3,
"selected": false,
"text": "<p>Short answer: Fabulous.</p>\n\n<p>Long answer: Something like....</p>\n\n<pre><code>static SomeSingleton *instance = NULL;\n\n@implementation SomeSingleton\n\n+ (id) instance {\n static dispatch_once_t onceToken;\n dispatch_once(&onceToken, ^{\n if (instance == NULL){\n instance = [[super allocWithZone:NULL] init];\n }\n });\n return instance;\n}\n\n+ (id) allocWithZone:(NSZone *)paramZone {\n return [[self instance] retain];\n}\n\n- (id) copyWithZone:(NSZone *)paramZone {\n return self;\n}\n\n- (id) autorelease {\n return self;\n}\n\n- (NSUInteger) retainCount {\n return NSUIntegerMax;\n}\n\n- (id) retain {\n return self;\n}\n\n@end\n</code></pre>\n\n<p>Be sure to read the <a href=\"http://opensource.apple.com/source/libdispatch/libdispatch-84.5/src/once.h\">dispatch/once.h header</a> to understand what's going on. In this case the header comments are more applicable than the docs or man page.</p>\n"
},
{
"answer_id": 9235774,
"author": "chunkyguy",
"author_id": 286094,
"author_profile": "https://Stackoverflow.com/users/286094",
"pm_score": 0,
"selected": false,
"text": "<p>With Objective C class methods, we can just avoid using the singleton pattern the usual way, from:</p>\n\n<pre><code>[[Librarian sharedInstance] openLibrary]\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>[Librarian openLibrary]\n</code></pre>\n\n<p>by wrapping the class inside another class that just has <strong>Class Methods</strong>, that way there is no chance of accidentally creating duplicate instances, as we're not creating any instance!</p>\n\n<p>I wrote a more detailed blog <a href=\"http://whackylabs.com/blog/?p=444\" rel=\"nofollow\">here</a> :)</p>\n"
},
{
"answer_id": 9826878,
"author": "JJD",
"author_id": 356895,
"author_profile": "https://Stackoverflow.com/users/356895",
"pm_score": 0,
"selected": false,
"text": "<p>To extend the example from @robbie-hanson ...</p>\n\n<pre><code>static MySingleton* sharedSingleton = nil;\n\n+ (void)initialize {\n static BOOL initialized = NO;\n if (!initialized) {\n initialized = YES;\n sharedSingleton = [[self alloc] init];\n }\n}\n\n- (id)init {\n self = [super init];\n if (self) {\n // Member initialization here.\n }\n return self;\n}\n</code></pre>\n"
},
{
"answer_id": 10439812,
"author": "kevinlawler",
"author_id": 365478,
"author_profile": "https://Stackoverflow.com/users/365478",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>KLSingleton is:</p>\n \n <ol>\n <li>Subclassible (to the n-th degree)</li>\n <li>ARC compatible</li>\n <li>Safe with <code>alloc</code> and <code>init</code></li>\n <li>Loaded lazily</li>\n <li>Thread-safe</li>\n <li>Lock-free (uses +initialize, not @synchronize)</li>\n <li>Macro-free</li>\n <li>Swizzle-free</li>\n <li>Simple</li>\n </ol>\n</blockquote>\n\n<p><a href=\"https://github.com/kevinlawler/KLSingleton\" rel=\"nofollow\">KLSingleton</a></p>\n"
},
{
"answer_id": 14015047,
"author": "TienDC",
"author_id": 1266274,
"author_profile": "https://Stackoverflow.com/users/1266274",
"pm_score": 0,
"selected": false,
"text": "<p>My way is simple like this:</p>\n\n<pre><code>static id instanceOfXXX = nil;\n\n+ (id) sharedXXX\n{\n static volatile BOOL initialized = NO;\n\n if (!initialized)\n {\n @synchronized([XXX class])\n {\n if (!initialized)\n {\n instanceOfXXX = [[XXX alloc] init];\n initialized = YES;\n }\n }\n }\n\n return instanceOfXXX;\n}\n</code></pre>\n\n<p>If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.</p>\n"
},
{
"answer_id": 14949104,
"author": "Zolt",
"author_id": 884625,
"author_profile": "https://Stackoverflow.com/users/884625",
"pm_score": 0,
"selected": false,
"text": "<p>I've not read through all the solutions, so forgive if this code is redundant. </p>\n\n<p>This is the most thread safe implementation in my opinion. </p>\n\n<pre><code>+(SingletonObject *) sharedManager\n{\n static SingletonObject * sharedResourcesObj = nil;\n\n @synchronized(self)\n {\n if (!sharedResourcesObj)\n {\n sharedResourcesObj = [[SingletonObject alloc] init];\n }\n }\n\n return sharedResourcesObj;\n}\n</code></pre>\n"
}
]
| 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 variable. I've seen a bunch of articles advocating the use of \"<code>User.current_user</code>\", but since classes are cached across requests, this can cause session tainting.</p>\n"
},
{
"answer_id": 147576,
"author": "Ryan Bigg",
"author_id": 15245,
"author_profile": "https://Stackoverflow.com/users/15245",
"pm_score": 0,
"selected": false,
"text": "<p>Is this site remote? Are you logging into it onto two separate computers on the same network?</p>\n"
},
{
"answer_id": 185821,
"author": "Jared",
"author_id": 23128,
"author_profile": "https://Stackoverflow.com/users/23128",
"pm_score": 3,
"selected": true,
"text": "<p>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.</p>\n"
}
]
| 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": 145212,
"author": "Kyle Burton",
"author_id": 19784,
"author_profile": "https://Stackoverflow.com/users/19784",
"pm_score": 1,
"selected": false,
"text": "<p>Well, if you're really interested in a literal REPL for emacs it is possible to write one using the -batch mode of emacs:</p>\n\n<pre><code>(require 'cl)\n\n(defun read-expression ()\n (condition-case\n err\n (read-string \"> \")\n (error\n (message \"Error reading '%s'\" form)\n (message (format \"%s\" err)))))\n\n(defun read-expression-from-string (str)\n (condition-case\n err\n (read-from-string str)\n (error\n (message \"Error parsing '%s'\" str)\n (message (format \"%s\" err))\n nil)))\n\n(defun repl ()\n (loop for expr = (read-string \"> \") then (read-expression)\n do\n (let ((form (car (read-expression-from-string expr))))\n (condition-case\n err\n (message \" => %s\" (eval form))\n (error\n (message \"Error evaluating '%s'\" form)\n (message (format \"%s\" err)))))))\n\n(repl)\n</code></pre>\n\n<p>You can call this from the command line, or, as you seem to want, from within an emacs buffer running a shell:</p>\n\n<pre><code>kburton@hypothesis:~/projects/elisp$ emacs -batch -l test.el\nLoading 00debian-vars...\n> (defvar x '(lambda (y) (* y 100)))\n => x\n> (funcall x 0.25)\n => 25.0\n> \nkburton@hypothesis:~/projects/elisp$\n</code></pre>\n"
},
{
"answer_id": 145218,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 3,
"selected": false,
"text": "<p>Your best bet is the <code>*scratch*</code> buffer. You can make it more like a REPL by first turning on the debugger:</p>\n\n<pre><code>M-x set-variable debug-on-error t\n</code></pre>\n\n<p>Then use <code>C-j</code> instead of <code>C-x C-e</code>, which will insert the result of evaluating the expression into the buffer on the line after the expression. Instead of things like command history, <code>* * *</code> and so forth, you just move around the <code>*scratch*</code> buffer and edit.</p>\n\n<p>If you want things like <code>* * *</code> to work, more like a usual REPL, try <code>ielm</code>.</p>\n\n<pre><code>M-x ielm\n</code></pre>\n"
},
{
"answer_id": 146251,
"author": "Greg Mattes",
"author_id": 13940,
"author_profile": "https://Stackoverflow.com/users/13940",
"pm_score": 7,
"selected": true,
"text": "<p>It's easy to evaluate Lisp expressions in Inferior Emacs-Lisp Mode:</p>\n\n<pre><code>M-x ielm\n</code></pre>\n\n<p>You can read more about this feature in the <a href=\"http://www.gnu.org/software/emacs/manual/html_mono/emacs.html#Lisp-Interaction\" rel=\"noreferrer\">Emacs manual section on \"Lisp Interaction\"</a> </p>\n"
},
{
"answer_id": 261285,
"author": "Alex Ott",
"author_id": 18627,
"author_profile": "https://Stackoverflow.com/users/18627",
"pm_score": 2,
"selected": false,
"text": "<p>To run just one elisp expression you can use M-: shortcut and enter expression in mini-buffer. For other cases you can use <em>scratch</em> buffer </p>\n"
},
{
"answer_id": 2090294,
"author": "Ray",
"author_id": 4872,
"author_profile": "https://Stackoverflow.com/users/4872",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://www.gnu.org/software/emacs/manual/html_mono/eshell.html#Top\" rel=\"noreferrer\">Eshell</a> is another option for an interactive Elisp interpreter. </p>\n\n<pre><code>M-x eshell\n</code></pre>\n\n<p>Not only is it a command shell like bash (or cmd.exe if on Windows) but you can also interactively write and execute Elisp code.</p>\n\n<pre><code>~ $ ls\nfoo.txt\nbar.txt\n~ $ (+ 1 1)\n2\n</code></pre>\n"
}
]
| 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 \"mount -t ntfs /dev/sdX1 /mnt/tmp\" you need to know what drive the external disk is identified as (check dmesg) and you need to make a mount point.</p>\n\n<p>To mount automatically everytime put a line in /etc/fstab, use one of the existing lines as an example - you will have to be root to do this.</p>\n"
},
{
"answer_id": 145219,
"author": "PostMan",
"author_id": 18405,
"author_profile": "https://Stackoverflow.com/users/18405",
"pm_score": 3,
"selected": false,
"text": "<p>first do a </p>\n\n<pre><code>fdisk -l\n</code></pre>\n\n<p>get the harddrive partition, ie /dev/sda2</p>\n\n<p>then </p>\n\n<pre><code>mount /dev/sda2 /mnt/windows\n</code></pre>\n\n<p>if this fails, try a </p>\n\n<pre><code>yum install ntfs-3g\n</code></pre>\n\n<p>* Just noted this is not included by default, so you can check out <a href=\"http://www.ntfs-3g.org/\" rel=\"noreferrer\">NTFS-3g</a> here, and find a suitable package for your system.</p>\n\n<p>to auto mount this, add a line to /etc/fstab saying </p>\n\n<pre><code>/dev/sda2 /mnt/temp ntfs defaults 0 0\n</code></pre>\n\n<p>and this should auto mount on a reboot</p>\n"
},
{
"answer_id": 145237,
"author": "DV.",
"author_id": 18406,
"author_profile": "https://Stackoverflow.com/users/18406",
"pm_score": 4,
"selected": true,
"text": "<p>To answer my own question: PostMan and mgb led me to the right path, but their answers did not contain complete solution.</p>\n\n<p>Note: A short manual/wiki on this question is here: <a href=\"http://wiki.centos.org/TipsAndTricks/NTFSPartitions\" rel=\"noreferrer\">http://wiki.centos.org/TipsAndTricks/NTFSPartitions</a></p>\n\n<p>So, I am using a fresh, bare install of CentOS 5.2 with latest updates. First of all, I ran the <code>su</code> command to avoid any permission issues.</p>\n\n<p>I created mount points for a couple of external NTFS drives:</p>\n\n<pre><code>mkdir /mnt/iomega80\nmkdir /mnt/iogear250\n</code></pre>\n\n<p>I had to use the fdisk command, but it wasn't in my system. Here's what installs it:</p>\n\n<pre><code>yum install util-linux\n</code></pre>\n\n<p>Then I ran <code>/sbin/fdisk -l</code> and found the device names:</p>\n\n<pre><code>Disk /dev/sdc: 250.0 GB, 250059350016 bytes\n255 heads, 63 sectors/track, 30401 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\n\n Device Boot Start End Blocks Id System\n**/dev/sdc1** * 1 30401 244196001 7 HPFS/NTFS\n\nDisk /dev/sdd: 82.3 GB, 82348278272 bytes\n255 heads, 63 sectors/track, 10011 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\n\n Device Boot Start End Blocks Id System\n**/dev/sdd1** * 1 10011 80413326 7 HPFS/NTFS\n</code></pre>\n\n<p>For me, they are <code>/dev/sdc1</code> and <code>/dev/sdd1</code>.</p>\n\n<p>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. </p>\n\n<p>To include RPMFORGE in YUM repository list, I used these instructions: <a href=\"http://rpmrepo.org/RPMforge/Using\" rel=\"noreferrer\">http://rpmrepo.org/RPMforge/Using</a>. For my system, the two commands I had to run were:</p>\n\n<pre><code>wget http://packages.sw.be/rpmforge-release/rpmforge-release-0.3.6-1.el5.rf.i386.rpm\nrpm -Uhv rpmforge-release-0.3.6-1.el5.rf.i386.rpm \n</code></pre>\n\n<p>Finally, I installed NTFS-3G using this YUM command:</p>\n\n<pre><code>yum install fuse fuse-ntfs-3g dkms dkms-fuse\n</code></pre>\n\n<p>At last, I could use the mount command to mount the filesystems:</p>\n\n<pre><code>mount -t ntfs-3g /dev/sdc1 /mnt/iogear250\nmount -t ntfs-3g /dev/sdd1 /mnt/iomega80\n</code></pre>\n\n<p>By adding these two lines to <code>/etc/fstab</code>, like previous answers suggested, I got the drives to mount upon boot-up:</p>\n\n<pre><code>/dev/sdc1 /mnt/iogear250 ntfs-3g rw,umask=0000,defaults 0 0\n/dev/sdd1 /mnt/iomega80 ntfs-3g rw,umask=0000,defaults 0 0\n</code></pre>\n"
},
{
"answer_id": 219405,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You forgot to mention that you need to do a reboot after installing fuse, etc.</p>\n"
},
{
"answer_id": 42056904,
"author": "Esther",
"author_id": 948935,
"author_profile": "https://Stackoverflow.com/users/948935",
"pm_score": 0,
"selected": false,
"text": "<p>First enable the repository Epel</p>\n\n<pre><code>yum install epel-release\n</code></pre>\n\n<p>Then install ntfs</p>\n\n<pre><code>yum install ntfs-3g\n</code></pre>\n"
},
{
"answer_id": 44286673,
"author": "Saddam ZEMMALI",
"author_id": 7875512,
"author_profile": "https://Stackoverflow.com/users/7875512",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li><p><strong>Enable the EPEL repository</strong></p></li>\n</ul>\n\n<p>yum -y install epel-release</p>\n\n<ul>\n<li><p><strong>Install ntfs-3g</strong></p></li>\n</ul>\n\n<p>yum -y install ntfs-3g</p>\n\n<ul>\n<li><p><strong>Update Grub</strong></p></li>\n</ul>\n\n<p>grub2-mkconfig -o /boot/grub2/grub.cfg</p>\n"
}
]
| 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(i){ this.value=i+1; });\n</code></pre>\n\n<p>The $().each() function's info is here: <a href=\"http://docs.jquery.com/Core/each\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Core/each</a></p>\n"
},
{
"answer_id": 145388,
"author": "Josh Hunt",
"author_id": 2592,
"author_profile": "https://Stackoverflow.com/users/2592",
"pm_score": 2,
"selected": true,
"text": "<p>Hardnrg in #jquery ended up solving it for me.</p>\n\n<p>It involved adding an id=\"\" to each input:</p>\n\n<pre><code><form name=\"productform\">\n <table cellspacing=\"0\" id=\"table-2\" name=\"productform\"> \n <thead>\n <tr><td>Product</td> <td>Order</td></tr> \n </thead>\n\n <tbody>\n <tr class=\"row1\" id=\"Pol\"> <td><a href=\"1/\">Pol</a></td> <td><input id=\"Pol_field\" type=\"textbox\" name=\"sort1\"/></td> </tr>\n <tr class=\"row2\" id=\"Evo\"> <td><a href=\"2/\">Evo</a></td> <td><input id=\"Evo_field\" type=\"textbox\" name=\"sort2\"/></td> </tr>\n <tr class=\"row3\" id=\"Kal\"> <td><a href=\"3/\">Kal</a></td> <td><input id=\"Kal_field\" type=\"textbox\" name=\"sort3\"/></td> </tr>\n <tr class=\"row4\" id=\"Lok\"> <td><a href=\"4/\">Lok</a></td> <td><input id=\"Lok_field\" type=\"textbox\" name=\"sort4\"/></td> </tr>\n </tbody> \n </table>\n</form>\n</code></pre>\n\n<p>And add this js to the OnDrop event:</p>\n\n<pre><code>for (var i=0; i < rows.length; i++) {\n $('#' + rows[i].id + \"_field\").val(i+1);\n}\n</code></pre>\n\n<p>Easy peasy!</p>\n"
}
]
| 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! |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.