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
|
---|---|---|---|---|---|---|
58,280 | <p>Is it possible to use an UnhandledException Handler in a Windows Service?</p>
<p>Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:</p>
<pre>
<code>
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
MyServiceComponent.Start()
Catch ex As Exception
'call into our exception handler
MyExceptionHandlingComponent.ManuallyHandleException (ex)
'zero is the default ExitCode for a successfull exit, so if we set it to non-zero
ExitCode = -1
'So, we use Environment.Exit, it seems to be the most appropriate thing to use
'we pass an exit code here as well, just in case.
System.Environment.Exit(-1)
End Try
End Sub
</code>
</pre>
<p>Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing?</p>
| [
{
"answer_id": 58408,
"author": "Garo Yeriazarian",
"author_id": 2655,
"author_profile": "https://Stackoverflow.com/users/2655",
"pm_score": 2,
"selected": false,
"text": "<p>You can subscribe to the <a href=\"http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx\" rel=\"nofollow noreferrer\">AppDomain.UnhandledException event</a>. If you have a message loop, you can tie to the <a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx\" rel=\"nofollow noreferrer\">Application.ThreadException event</a>.</p>\n"
},
{
"answer_id": 58450,
"author": "Scott",
"author_id": 6042,
"author_profile": "https://Stackoverflow.com/users/6042",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, I’ve done a little more research into this now.\nWhen you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to. \nThese methods are invoked from within the base class so I did a little poking around with reflector.\nOnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine \"System.ServiceProcess, Version=2.0.0.0\" decompiles like this:</p>\n\n<pre>\n<code>\nPrivate Sub ServiceQueuedMainCallback(ByVal state As Object)\n Dim args As String() = DirectCast(state, String())\n Try \n Me.OnStart(args)\n Me.WriteEventLogEntry(Res.GetString(\"StartSuccessful\"))\n Me.status.checkPoint = 0\n Me.status.waitHint = 0\n Me.status.currentState = 4\n Catch exception As Exception\n Me.WriteEventLogEntry(Res.GetString(\"StartFailed\", New Object() { exception.ToString }), EventLogEntryType.Error)\n Me.status.currentState = 1\n Catch obj1 As Object\n Me.WriteEventLogEntry(Res.GetString(\"StartFailed\", New Object() { String.Empty }), EventLogEntryType.Error)\n Me.status.currentState = 1\n End Try\n Me.startCompletedSignal.Set\nEnd Sub\n</code>\n</pre>\n\n<p>So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine. \nThe other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way.</p>\n\n<p>So I ‘think’ that explains why my Exception Handling component can’t catch UnhandledException on Start and Stop, but I’m not sure if it explains why timers that are setup in OnStart can’t cause an UnhandledException when they fire. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6042/"
]
| Is it possible to use an UnhandledException Handler in a Windows Service?
Normally I would use a custom built Exception Handling Component that does logging, phone home, etc. This component adds a handler to System.AppDomain.CurrentDomain.UnhandledException but as far as I can tell this doesn’t achieve anything win a Windows Service so I end up with this pattern in my 2 (or 4) Service entry points:
```
Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
Try
MyServiceComponent.Start()
Catch ex As Exception
'call into our exception handler
MyExceptionHandlingComponent.ManuallyHandleException (ex)
'zero is the default ExitCode for a successfull exit, so if we set it to non-zero
ExitCode = -1
'So, we use Environment.Exit, it seems to be the most appropriate thing to use
'we pass an exit code here as well, just in case.
System.Environment.Exit(-1)
End Try
End Sub
```
Is there a way my Custom Exception Handling component can deal with this better so I don't have to fill my OnStart with messy exception handling plumbing? | Ok, I’ve done a little more research into this now.
When you create a windows service in .Net, you create a class that inherits from System.ServiceProcess.ServiceBase (In VB this is hidden in the .Designer.vb file). You then override the OnStart and OnStop function, and OnPause and OnContinue if you choose to.
These methods are invoked from within the base class so I did a little poking around with reflector.
OnStart is invoked by a method in System.ServiceProcess.ServiceBase called ServiceQueuedMainCallback. The vesion on my machine "System.ServiceProcess, Version=2.0.0.0" decompiles like this:
```
Private Sub ServiceQueuedMainCallback(ByVal state As Object)
Dim args As String() = DirectCast(state, String())
Try
Me.OnStart(args)
Me.WriteEventLogEntry(Res.GetString("StartSuccessful"))
Me.status.checkPoint = 0
Me.status.waitHint = 0
Me.status.currentState = 4
Catch exception As Exception
Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { exception.ToString }), EventLogEntryType.Error)
Me.status.currentState = 1
Catch obj1 As Object
Me.WriteEventLogEntry(Res.GetString("StartFailed", New Object() { String.Empty }), EventLogEntryType.Error)
Me.status.currentState = 1
End Try
Me.startCompletedSignal.Set
End Sub
```
So because Me.OnStart(args) is called from within the Try portion of a Try Catch block I assume that anything that happens within the OnStart method is effectively wrapped by that Try Catch block and therefore any exceptions that occur aren't technically unhandled as they are actually handled in the ServiceQueuedMainCallback Try Catch. So CurrentDomain.UnhandledException never actually happens at least during the startup routine.
The other 3 entry points (OnStop, OnPause and OnContinue) are all called from the base class in a similar way.
So I ‘think’ that explains why my Exception Handling component can’t catch UnhandledException on Start and Stop, but I’m not sure if it explains why timers that are setup in OnStart can’t cause an UnhandledException when they fire. |
58,305 | <p>Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard?</p>
| [
{
"answer_id": 58326,
"author": "David Citron",
"author_id": 5309,
"author_profile": "https://Stackoverflow.com/users/5309",
"pm_score": 9,
"selected": true,
"text": "<p>Believe it or not, you can actually use <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)\" rel=\"noreferrer\"><code>java.awt.Robot</code></a> to \"create an image containing pixels read from the screen.\" You can then write that image to a file on disk.</p>\n\n<p>I just tried it, and the whole thing ends up like:</p>\n\n<pre><code>Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());\nBufferedImage capture = new Robot().createScreenCapture(screenRect);\nImageIO.write(capture, \"bmp\", new File(args[0]));\n</code></pre>\n\n<p>NOTE: This will only capture the primary monitor. See <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html\" rel=\"noreferrer\">GraphicsConfiguration</a> for multi-monitor support.</p>\n"
},
{
"answer_id": 10796047,
"author": "DejanLekic",
"author_id": 876497,
"author_profile": "https://Stackoverflow.com/users/876497",
"pm_score": 5,
"selected": false,
"text": "<p>I never liked using Robot, so I made my own simple method for making screenshots of JFrame objects:</p>\n\n<pre><code>public static final void makeScreenshot(JFrame argFrame) {\n Rectangle rec = argFrame.getBounds();\n BufferedImage bufferedImage = new BufferedImage(rec.width, rec.height, BufferedImage.TYPE_INT_ARGB);\n argFrame.paint(bufferedImage.getGraphics());\n\n try {\n // Create temp file\n File temp = File.createTempFile(\"screenshot\", \".png\");\n\n // Use the ImageIO API to write the bufferedImage to a temporary file\n ImageIO.write(bufferedImage, \"png\", temp);\n\n // Delete temp file when program exits\n temp.deleteOnExit();\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 17229248,
"author": "user2503881",
"author_id": 2503881,
"author_profile": "https://Stackoverflow.com/users/2503881",
"pm_score": 4,
"selected": false,
"text": "<pre><code>public void captureScreen(String fileName) throws Exception {\n Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();\n Rectangle screenRectangle = new Rectangle(screenSize);\n Robot robot = new Robot();\n BufferedImage image = robot.createScreenCapture(screenRectangle);\n ImageIO.write(image, \"png\", new File(fileName));\n}\n</code></pre>\n"
},
{
"answer_id": 18156495,
"author": "11101101b",
"author_id": 875305,
"author_profile": "https://Stackoverflow.com/users/875305",
"pm_score": 4,
"selected": false,
"text": "<p>If you'd like to capture all monitors, you can use the following code:</p>\n\n<pre><code>GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();\nGraphicsDevice[] screens = ge.getScreenDevices();\n\nRectangle allScreenBounds = new Rectangle();\nfor (GraphicsDevice screen : screens) {\n Rectangle screenBounds = screen.getDefaultConfiguration().getBounds();\n\n allScreenBounds.width += screenBounds.width;\n allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n}\n\nRobot robot = new Robot();\nBufferedImage screenShot = robot.createScreenCapture(allScreenBounds);\n</code></pre>\n"
},
{
"answer_id": 27603992,
"author": "Nilesh Jadav",
"author_id": 3966892,
"author_profile": "https://Stackoverflow.com/users/3966892",
"pm_score": 2,
"selected": false,
"text": "<pre><code>import java.awt.Color;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.event.ActionEvent;\nimport java.awt.event.ActionListener;\nimport java.awt.image.BufferedImage;\nimport java.io.File; \nimport javax.imageio.ImageIO;\nimport javax.swing.*; \n\npublic class HelloWorldFrame extends JFrame implements ActionListener {\n\nJButton b;\npublic HelloWorldFrame() {\n this.setVisible(true);\n this.setLayout(null);\n b = new JButton(\"Click Here\");\n b.setBounds(380, 290, 120, 60);\n b.setBackground(Color.red);\n b.setVisible(true);\n b.addActionListener(this);\n add(b);\n setSize(1000, 700);\n}\npublic void actionPerformed(ActionEvent e)\n{\n if (e.getSource() == b) \n {\n this.dispose();\n try {\n Thread.sleep(1000);\n Toolkit tk = Toolkit.getDefaultToolkit(); \n Dimension d = tk.getScreenSize();\n Rectangle rec = new Rectangle(0, 0, d.width, d.height); \n Robot ro = new Robot();\n BufferedImage img = ro.createScreenCapture(rec);\n File f = new File(\"myimage.jpg\");//set appropriate path\n ImageIO.write(img, \"jpg\", f);\n } catch (Exception ex) {\n System.out.println(ex.getMessage());\n }\n }\n}\n\npublic static void main(String[] args) {\n HelloWorldFrame obj = new HelloWorldFrame();\n}\n}\n</code></pre>\n"
},
{
"answer_id": 31083752,
"author": "joe pelletier",
"author_id": 4088794,
"author_profile": "https://Stackoverflow.com/users/4088794",
"pm_score": 2,
"selected": false,
"text": "<pre><code>GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); \nGraphicsDevice[] screens = ge.getScreenDevices(); \nRectangle allScreenBounds = new Rectangle(); \nfor (GraphicsDevice screen : screens) { \n Rectangle screenBounds = screen.getDefaultConfiguration().getBounds(); \n allScreenBounds.width += screenBounds.width; \n allScreenBounds.height = Math.max(allScreenBounds.height, screenBounds.height);\n allScreenBounds.x=Math.min(allScreenBounds.x, screenBounds.x);\n allScreenBounds.y=Math.min(allScreenBounds.y, screenBounds.y);\n } \nRobot robot = new Robot();\nBufferedImage bufferedImage = robot.createScreenCapture(allScreenBounds);\nFile file = new File(\"C:\\\\Users\\\\Joe\\\\Desktop\\\\scr.png\");\nif(!file.exists())\n file.createNewFile();\nFileOutputStream fos = new FileOutputStream(file);\nImageIO.write( bufferedImage, \"png\", fos );\n</code></pre>\n\n<p>bufferedImage will contain a full screenshot, this was tested with three monitors </p>\n"
},
{
"answer_id": 45937897,
"author": "Muhammad Yawar",
"author_id": 4770992,
"author_profile": "https://Stackoverflow.com/users/4770992",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <code>java.awt.Robot</code> to achieve this task.</p>\n\n<p>below is the code of server, which saves the captured screenshot as image in your Directory.</p>\n\n<pre><code>import java.awt.image.BufferedImage;\nimport java.io.File;\nimport java.io.IOException;\nimport java.net.ServerSocket;\nimport java.net.Socket;\nimport java.net.SocketTimeoutException;\nimport java.sql.SQLException;\nimport java.text.DateFormat;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\n\nimport javax.imageio.ImageIO;\n\npublic class ServerApp extends Thread\n{\n private ServerSocket serverSocket=null;\n private static Socket server = null;\n private Date date = null;\n private static final String DIR_NAME = \"screenshots\";\n\n public ServerApp() throws IOException, ClassNotFoundException, Exception{\n serverSocket = new ServerSocket(61000);\n serverSocket.setSoTimeout(180000);\n }\n\npublic void run()\n {\n while(true)\n {\n try\n {\n server = serverSocket.accept();\n date = new Date();\n DateFormat dateFormat = new SimpleDateFormat(\"_yyMMdd_HHmmss\");\n String fileName = server.getInetAddress().getHostName().replace(\".\", \"-\");\n System.out.println(fileName);\n BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));\n ImageIO.write(img, \"png\", new File(\"D:\\\\screenshots\\\\\"+fileName+dateFormat.format(date)+\".png\"));\n System.out.println(\"Image received!!!!\");\n //lblimg.setIcon(img);\n }\n catch(SocketTimeoutException st)\n {\n System.out.println(\"Socket timed out!\"+st.toString());\n //createLogFile(\"[stocktimeoutexception]\"+stExp.getMessage());\n break;\n }\n catch(IOException e)\n {\n e.printStackTrace();\n break;\n }\n catch(Exception ex)\n {\n System.out.println(ex);\n }\n }\n }\n\n public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{\n ServerApp serverApp = new ServerApp();\n serverApp.createDirectory(DIR_NAME);\n Thread thread = new Thread(serverApp);\n thread.start();\n }\n\nprivate void createDirectory(String dirName) {\n File newDir = new File(\"D:\\\\\"+dirName);\n if(!newDir.exists()){\n boolean isCreated = newDir.mkdir();\n }\n }\n} \n</code></pre>\n\n<p>And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.</p>\n\n<pre><code>package com.viremp.client;\n\nimport java.awt.AWTException;\nimport java.awt.Dimension;\nimport java.awt.Rectangle;\nimport java.awt.Robot;\nimport java.awt.Toolkit;\nimport java.awt.image.BufferedImage;\nimport java.io.IOException;\nimport java.net.Socket;\nimport java.util.Random;\n\nimport javax.imageio.ImageIO;\n\npublic class ClientApp implements Runnable {\n private static long nextTime = 0;\n private static ClientApp clientApp = null;\n private String serverName = \"192.168.100.18\"; //loop back ip\n private int portNo = 61000;\n //private Socket serverSocket = null;\n\n /**\n * @param args\n * @throws InterruptedException \n */\n public static void main(String[] args) throws InterruptedException {\n clientApp = new ClientApp();\n clientApp.getNextFreq();\n Thread thread = new Thread(clientApp);\n thread.start();\n }\n\n private void getNextFreq() {\n long currentTime = System.currentTimeMillis();\n Random random = new Random();\n long value = random.nextInt(180000); //1800000\n nextTime = currentTime + value;\n //return currentTime+value;\n }\n\n @Override\n public void run() {\n while(true){\n if(nextTime < System.currentTimeMillis()){\n System.out.println(\" get screen shot \");\n try {\n clientApp.sendScreen();\n clientApp.getNextFreq();\n } catch (AWTException e) {\n // TODO Auto-generated catch block\n System.out.println(\" err\"+e);\n } catch (IOException e) {\n // TODO Auto-generated catch block\n e.printStackTrace();\n } catch(Exception e){\n e.printStackTrace();\n }\n\n }\n //System.out.println(\" statrted ....\");\n }\n\n }\n\n private void sendScreen()throws AWTException, IOException {\n Socket serverSocket = new Socket(serverName, portNo);\n Toolkit toolkit = Toolkit.getDefaultToolkit();\n Dimension dimensions = toolkit.getScreenSize();\n Robot robot = new Robot(); // Robot class \n BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));\n ImageIO.write(screenshot,\"png\",serverSocket.getOutputStream());\n serverSocket.close();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 53084575,
"author": "MisterParser",
"author_id": 3123946,
"author_profile": "https://Stackoverflow.com/users/3123946",
"pm_score": 0,
"selected": false,
"text": "<p>Toolkit returns pixels based on PPI, as a result, a screenshot is not created for the entire screen when using PPI> 100% in Windows.\nI propose to do this:</p>\n\n<pre><code>DisplayMode displayMode = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDisplayMode();\nRectangle screenRectangle = new Rectangle(displayMode.getWidth(), displayMode.getHeight());\nBufferedImage screenShot = new Robot().createScreenCapture(screenRectangle);\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58305",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2598/"
]
| Simple as the title states: Can you use only Java commands to take a screenshot and save it? Or, do I need to use an OS specific program to take the screenshot and then grab it off the clipboard? | Believe it or not, you can actually use [`java.awt.Robot`](http://java.sun.com/javase/6/docs/api/java/awt/Robot.html#createScreenCapture(java.awt.Rectangle)) to "create an image containing pixels read from the screen." You can then write that image to a file on disk.
I just tried it, and the whole thing ends up like:
```
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage capture = new Robot().createScreenCapture(screenRect);
ImageIO.write(capture, "bmp", new File(args[0]));
```
NOTE: This will only capture the primary monitor. See [GraphicsConfiguration](http://java.sun.com/javase/6/docs/api/java/awt/GraphicsConfiguration.html) for multi-monitor support. |
58,306 | <p>I am trying to determine the best time efficient algorithm to accomplish the task described below.</p>
<p>I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.</p>
<p>All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).</p>
<p>I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).</p>
<p>Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).</p>
<p>For example:</p>
<pre>
If I have the following records:
A, B, C, D, E
and the following represents the connections:
(A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E),
(C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E)
[where (A,B) means record A connects to record B]
</pre>
<p>If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.</p>
<pre>
All paths connecting B to E:
B->E
B->F->E
B->F->C->E
B->A->C->E
B->A->C->F->E
</pre>
<p>This is an example, in practice I may have sets containing hundreds of thousands of records.</p>
| [
{
"answer_id": 58321,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I have solved a similar problem to this recently, instead of all solutions I was only interested in the shortest.</p>\n\n<p>I used a 'breadth first' iterative search which used a queue of status' each of which held a record containing a current point on the graph and the path taken to get there.</p>\n\n<p>you start with a single record in the queue, which has the starting node and an empty path.</p>\n\n<p>Each iteration through the code takes the item off the head of the list, and checks to see if it is a solution (the node arrived at is the one you want, if it is, we are done), otherwise, it constructs a new queue item with the nodes connecting to the current node, and amended paths that are based on the path of the previous node, with the new jump attached at the end.</p>\n\n<p>Now, you could use something similar, but when you find a solution, instead of stopping, add that solution to your 'found list' and continue.</p>\n\n<p>You need to keep track of a visited nodes list, so that you never backtrack on yourself otherwise you have an infinite loop.</p>\n\n<p>if you want a bit more pseudocode post a comment or something, and I will elaborate.</p>\n"
},
{
"answer_id": 58343,
"author": "Ryan Fox",
"author_id": 55,
"author_profile": "https://Stackoverflow.com/users/55",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a thought off the top of my head:</p>\n\n<ol>\n<li>Find one connection. (Depth-first search is probably a good algorithm for this, since the path length doesn't matter.)</li>\n<li>Disable the last segment.</li>\n<li>Try to find another connection from the last node before the previously disabled connection.</li>\n<li>Goto 2 until there are no more connections.</li>\n</ol>\n"
},
{
"answer_id": 58444,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I think you should describe your real problem behind this. I say this because you ask for something time efficient, yet the answer set to the problem seems to grow exponentially!</p>\n\n<p>Therefore I wouldn't expect a better algorithm than something exponential.</p>\n\n<p>I'd do backtracking and going through the whole graph. In order to avoid cycles, save all visited nodes along the way. When you go back, unmark the node.</p>\n\n<p>Using recursion:</p>\n\n<pre><code>static bool[] visited;//all false\nStack<int> currentway; initialize empty\n\nfunction findnodes(int nextnode)\n{\nif (nextnode==destnode)\n{\n print currentway \n return;\n}\nvisited[nextnode]=true;\nPush nextnode to the end of currentway.\nfor each node n accesible from nextnode:\n findnodes(n);\nvisited[nextnode]=false; \npop from currenteay\n}\n</code></pre>\n\n<p>Or is that wrong?</p>\n\n<p>edit:\nOh, and I forgot:\nYou should eliminate the recursive calls by utilizing that node stack</p>\n"
},
{
"answer_id": 58446,
"author": "Casey Watson",
"author_id": 4682,
"author_profile": "https://Stackoverflow.com/users/4682",
"pm_score": 8,
"selected": true,
"text": "<p>It appears that this can be accomplished with a depth-first search of the graph. <strong>The depth-first search will find all non-cyclical paths between two nodes.</strong> This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to).</p>\n\n<p>I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though.</p>\n\n<p><strong>Graph.java:</strong></p>\n\n\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.HashMap;\nimport java.util.LinkedHashSet;\nimport java.util.LinkedList;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Graph {\n private Map<String, LinkedHashSet<String>> map = new HashMap();\n\n public void addEdge(String node1, String node2) {\n LinkedHashSet<String> adjacent = map.get(node1);\n if(adjacent==null) {\n adjacent = new LinkedHashSet();\n map.put(node1, adjacent);\n }\n adjacent.add(node2);\n }\n\n public void addTwoWayVertex(String node1, String node2) {\n addEdge(node1, node2);\n addEdge(node2, node1);\n }\n\n public boolean isConnected(String node1, String node2) {\n Set adjacent = map.get(node1);\n if(adjacent==null) {\n return false;\n }\n return adjacent.contains(node2);\n }\n\n public LinkedList<String> adjacentNodes(String last) {\n LinkedHashSet<String> adjacent = map.get(last);\n if(adjacent==null) {\n return new LinkedList();\n }\n return new LinkedList<String>(adjacent);\n }\n}\n</code></pre>\n\n<p><strong>Search.java:</strong></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>import java.util.LinkedList;\n\npublic class Search {\n\n private static final String START = \"B\";\n private static final String END = \"E\";\n\n public static void main(String[] args) {\n // this graph is directional\n Graph graph = new Graph();\n graph.addEdge(\"A\", \"B\");\n graph.addEdge(\"A\", \"C\");\n graph.addEdge(\"B\", \"A\");\n graph.addEdge(\"B\", \"D\");\n graph.addEdge(\"B\", \"E\"); // this is the only one-way connection\n graph.addEdge(\"B\", \"F\");\n graph.addEdge(\"C\", \"A\");\n graph.addEdge(\"C\", \"E\");\n graph.addEdge(\"C\", \"F\");\n graph.addEdge(\"D\", \"B\");\n graph.addEdge(\"E\", \"C\");\n graph.addEdge(\"E\", \"F\");\n graph.addEdge(\"F\", \"B\");\n graph.addEdge(\"F\", \"C\");\n graph.addEdge(\"F\", \"E\");\n LinkedList<String> visited = new LinkedList();\n visited.add(START);\n new Search().depthFirst(graph, visited);\n }\n\n private void depthFirst(Graph graph, LinkedList<String> visited) {\n LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());\n // examine adjacent nodes\n for (String node : nodes) {\n if (visited.contains(node)) {\n continue;\n }\n if (node.equals(END)) {\n visited.add(node);\n printPath(visited);\n visited.removeLast();\n break;\n }\n }\n for (String node : nodes) {\n if (visited.contains(node) || node.equals(END)) {\n continue;\n }\n visited.addLast(node);\n depthFirst(graph, visited);\n visited.removeLast();\n }\n }\n\n private void printPath(LinkedList<String> visited) {\n for (String node : visited) {\n System.out.print(node);\n System.out.print(\" \");\n }\n System.out.println();\n }\n}\n</code></pre>\n\n<p>Program Output:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>B E \nB A C E \nB A C F E \nB F E \nB F C E \n</code></pre>\n"
},
{
"answer_id": 58461,
"author": "Robert Groves",
"author_id": 3534,
"author_profile": "https://Stackoverflow.com/users/3534",
"pm_score": 4,
"selected": false,
"text": "<p>Here is the pseudocode I came up with. This is not any particular pseudocode dialect, but should be simple enough to follow.</p>\n\n<p>Anyone want to pick this apart.</p>\n\n<ul>\n<li><p>[p] is a list of vertices representing the current path.</p></li>\n<li><p>[x] is a list of paths where meet the criteria</p></li>\n<li><p>[s] is the source vertex</p></li>\n<li><p>[d] is the destination vertex</p></li>\n<li><p>[c] is the current vertex (argument to the PathFind routine)</p></li>\n</ul>\n\n<p>Assume there is an efficient way to look up the adjacent vertices (line 6).</p>\n\n<pre>\n 1 PathList [p]\n 2 ListOfPathLists [x]\n 3 Vertex [s], [d]\n\n 4 PathFind ( Vertex [c] )\n 5 Add [c] to tail end of list [p]\n 6 For each Vertex [v] adjacent to [c]\n 7 If [v] is equal to [d] then\n 8 Save list [p] in [x]\n 9 Else If [v] is not in list [p]\n 10 PathFind([v])\n 11 Next For\n 12 Remove tail from [p]\n 13 Return\n</pre>\n"
},
{
"answer_id": 58507,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I can tell the solutions given by Ryan Fox (<a href=\"https://stackoverflow.com/questions/58306/graph-algorithm-to-find-all-connections-between-two-arbitrary-vertices#58343\">58343</a>, Christian (<a href=\"https://stackoverflow.com/questions/58306/graph-algorithm-to-find-all-connections-between-two-arbitrary-vertices#58444\">58444</a>), and yourself (<a href=\"https://stackoverflow.com/questions/58306/graph-algorithm-to-find-all-connections-between-two-arbitrary-vertices#58461\">58461</a>) are about as good as it get. I do not believe that breadth-first traversal helps in this case, as you will not get all paths. For example, with edges <code>(A,B)</code>, <code>(A,C)</code>, <code>(B,C)</code>, <code>(B,D)</code> and <code>(C,D)</code> you will get paths <code>ABD</code> and <code>ACD</code>, but not <code>ABCD</code>.</p>\n"
},
{
"answer_id": 75941,
"author": "Michael Dorfman",
"author_id": 6741,
"author_profile": "https://Stackoverflow.com/users/6741",
"pm_score": 5,
"selected": false,
"text": "<p>The National Institute of Standards and Technology (NIST) online Dictionary of Algorithms and Data Structures lists this problem as \"<a href=\"https://xlinux.nist.gov/dads/HTML/allSimplePaths.html\" rel=\"noreferrer\">all simple paths\"</a> and recommends a <a href=\"https://xlinux.nist.gov/dads/HTML/depthfirst.html\" rel=\"noreferrer\">depth-first search</a>. CLRS supplies the relevant algorithms.</p>\n\n<p>A clever technique using Petri Nets is found <a href=\"http://ieeexplore.ieee.org/xpls/abs_all.jsp?arnumber=1084515\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 4375881,
"author": "Vjeux",
"author_id": 232122,
"author_profile": "https://Stackoverflow.com/users/232122",
"pm_score": 0,
"selected": false,
"text": "<p>I found a way to enumerate all the paths including the infinite ones containing loops.</p>\n\n<p><a href=\"http://blog.vjeux.com/2009/project/project-shortest-path.html\" rel=\"nofollow\">http://blog.vjeux.com/2009/project/project-shortest-path.html</a></p>\n\n<p><strong>Finding Atomic Paths & Cycles</strong></p>\n\n<pre><code>Definition\n</code></pre>\n\n<p>What we want to do is find all the possible paths going from point A to point B. Since there are cycles involved, you can't just go through and enumerate them all. Instead, you will have to find atomic path that doesn't loop and the smallest possible cycles (you don't want your cycle to repeat itself).</p>\n\n<p>The first definition I took of an atomic path is a path that does not go through the same node twice. However, I found out that is was not taking all possibilities. After some reflexion, I figured out that nodes aren't important, however edges are! So an atomic path is a path that does not go through the same edge twice.</p>\n\n<p>This definition is handy, it also works for cycles: an atomic cycle of point A is an atomic path that goes from point A and ends to point A.</p>\n\n<p><strong>Implementation</strong></p>\n\n<pre><code>Atomic Paths A -> B\n</code></pre>\n\n<p>In order to get all the path starting from point A, we are going to traverse the graph recursively from the point A. While going through a child, we are going to make a link child -> parent in order to know all the edges we have already crossed. Before we go to that child, we must traverse that linked list and make sure the specified edge has not been already walked through.</p>\n\n<p>When we arrive to the destination point, we can store the path we found.</p>\n\n<pre><code>Freeing the list\n</code></pre>\n\n<p>A problem occurs when you want to free the linked list. It is basically a tree chained in the reverse order. A solution would be to double-link that list and when all the atomic paths been found, free the tree from the starting point.</p>\n\n<p>But a clever solution is to use a reference counting (inspired from Garbage Collection). Each time you add a link to a parent you adds one to its reference count. Then, when you arrive at the end of a path, you go backward and free while the reference count equals to 1. If it is higher, you just remove one and stop.</p>\n\n<pre><code>Atomic Cycle A\n</code></pre>\n\n<p>Looking for the atomic cycle of A is the same as looking for the atomic path from A to A. However there are several optimizations we can do. First, when we arrive at the destination point, we want to save the path only if the sum of the edges cost is negative: we only want to go through absorbing cycles.</p>\n\n<p>As you have seen previously, the whole graph is being traversed when looking for an atomic path. Instead, we can limit the search area to the strongly connected component containing A. Finding these components requires a simple traverse of the graph with Tarjan's algorithm.</p>\n\n<p><strong>Combining Atomic Paths and Cycles</strong></p>\n\n<p>At this point, we have all the atomic paths that goes from A to B and all the atomic cycles of each node, left to us to organize everything to get the shortest path. From now on we are going to study how to find the best combination of atomic cycles in an atomic path.</p>\n"
},
{
"answer_id": 7521818,
"author": "AndyUK",
"author_id": 6795,
"author_profile": "https://Stackoverflow.com/users/6795",
"pm_score": 0,
"selected": false,
"text": "<p>As ably described by some of the other posters, the problem in a nutshell is that of using a depth-first search algorithm to recursively search the graph for all combinations of paths between the communicating end nodes.</p>\n\n<p>The algorithm itself commences with the start node you give it, examines all its outgoing links and progresses by expanding the first child node of the search tree that appears, searching progressively deeper and deeper until a target node is found, or until it encounters a node that has no children. </p>\n\n<p>The search then backtracks, returning to the most recent node it hasn’t yet finished exploring.</p>\n\n<p>I <a href=\"http://technical-recipes.com/?p=1142\" rel=\"nofollow\">blogged</a> about this very topic quite recently, posting an example C++ implementation in the process.</p>\n"
},
{
"answer_id": 8263753,
"author": "Haibin Liu",
"author_id": 1064820,
"author_profile": "https://Stackoverflow.com/users/1064820",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a logically better-looking recursive version as compared to the second floor.</p>\n\n<pre><code>public class Search {\n\nprivate static final String START = \"B\";\nprivate static final String END = \"E\";\n\npublic static void main(String[] args) {\n // this graph is directional\n Graph graph = new Graph();\n graph.addEdge(\"A\", \"B\");\n graph.addEdge(\"A\", \"C\");\n graph.addEdge(\"B\", \"A\");\n graph.addEdge(\"B\", \"D\");\n graph.addEdge(\"B\", \"E\"); // this is the only one-way connection\n graph.addEdge(\"B\", \"F\");\n graph.addEdge(\"C\", \"A\");\n graph.addEdge(\"C\", \"E\");\n graph.addEdge(\"C\", \"F\");\n graph.addEdge(\"D\", \"B\");\n graph.addEdge(\"E\", \"C\");\n graph.addEdge(\"E\", \"F\");\n graph.addEdge(\"F\", \"B\");\n graph.addEdge(\"F\", \"C\");\n graph.addEdge(\"F\", \"E\");\n List<ArrayList<String>> paths = new ArrayList<ArrayList<String>>();\n String currentNode = START;\n List<String> visited = new ArrayList<String>();\n visited.add(START);\n new Search().findAllPaths(graph, seen, paths, currentNode);\n for(ArrayList<String> path : paths){\n for (String node : path) {\n System.out.print(node);\n System.out.print(\" \");\n }\n System.out.println();\n } \n}\n\nprivate void findAllPaths(Graph graph, List<String> visited, List<ArrayList<String>> paths, String currentNode) { \n if (currentNode.equals(END)) { \n paths.add(new ArrayList(Arrays.asList(visited.toArray())));\n return;\n }\n else {\n LinkedList<String> nodes = graph.adjacentNodes(currentNode); \n for (String node : nodes) {\n if (visited.contains(node)) {\n continue;\n } \n List<String> temp = new ArrayList<String>();\n temp.addAll(visited);\n temp.add(node); \n findAllPaths(graph, temp, paths, node);\n }\n }\n}\n}\n</code></pre>\n\n<p>Program Output</p>\n\n<pre><code>B A C E \n\nB A C F E \n\nB E\n\nB F C E\n\nB F E \n</code></pre>\n"
},
{
"answer_id": 9247432,
"author": "Leon Chang",
"author_id": 1204860,
"author_profile": "https://Stackoverflow.com/users/1204860",
"pm_score": 2,
"selected": false,
"text": "<p>Solution in C code. It is based on DFS which uses minimum memory. </p>\n\n<pre><code>#include <stdio.h>\n#include <stdbool.h>\n\n#define maxN 20 \n\nstruct nodeLink\n{\n\n char node1;\n char node2;\n\n};\n\nstruct stack\n{ \n int sp;\n char node[maxN];\n}; \n\nvoid initStk(stk)\nstruct stack *stk;\n{\n int i;\n for (i = 0; i < maxN; i++)\n stk->node[i] = ' ';\n stk->sp = -1; \n}\n\nvoid pushIn(stk, node)\nstruct stack *stk;\nchar node;\n{\n\n stk->sp++;\n stk->node[stk->sp] = node;\n\n} \n\nvoid popOutAll(stk)\nstruct stack *stk;\n{\n\n char node;\n int i, stkN = stk->sp;\n\n for (i = 0; i <= stkN; i++)\n {\n node = stk->node[i];\n if (i == 0)\n printf(\"src node : %c\", node);\n else if (i == stkN)\n printf(\" => %c : dst node.\\n\", node);\n else\n printf(\" => %c \", node);\n }\n\n}\n\n\n/* Test whether the node already exists in the stack */\nbool InStack(stk, InterN)\nstruct stack *stk;\nchar InterN;\n{\n\n int i, stkN = stk->sp; /* 0-based */\n bool rtn = false; \n\n for (i = 0; i <= stkN; i++)\n {\n if (stk->node[i] == InterN)\n {\n rtn = true;\n break;\n }\n }\n\n return rtn;\n\n}\n\nchar otherNode(targetNode, lnkNode)\nchar targetNode;\nstruct nodeLink *lnkNode;\n{\n\n return (lnkNode->node1 == targetNode) ? lnkNode->node2 : lnkNode->node1;\n\n}\n\nint entries = 8;\nstruct nodeLink topo[maxN] = \n {\n {'b', 'a'}, \n {'b', 'e'}, \n {'b', 'd'}, \n {'f', 'b'}, \n {'a', 'c'},\n {'c', 'f'}, \n {'c', 'e'},\n {'f', 'e'}, \n };\n\nchar srcNode = 'b', dstN = 'e'; \n\nint reachTime; \n\nvoid InterNode(interN, stk)\nchar interN;\nstruct stack *stk;\n{\n\n char otherInterN;\n int i, numInterN = 0;\n static int entryTime = 0;\n\n entryTime++;\n\n for (i = 0; i < entries; i++)\n {\n\n if (topo[i].node1 != interN && topo[i].node2 != interN) \n {\n continue; \n }\n\n otherInterN = otherNode(interN, &topo[i]);\n\n numInterN++;\n\n if (otherInterN == stk->node[stk->sp - 1])\n {\n continue; \n }\n\n /* Loop avoidance: abandon the route */\n if (InStack(stk, otherInterN) == true)\n {\n continue; \n }\n\n pushIn(stk, otherInterN);\n\n if (otherInterN == dstN)\n {\n popOutAll(stk);\n reachTime++;\n stk->sp --; /* back trace one node */\n continue;\n }\n else\n InterNode(otherInterN, stk);\n\n }\n\n stk->sp --;\n\n}\n\n\nint main()\n\n{\n\n struct stack stk;\n\n initStk(&stk);\n pushIn(&stk, srcNode); \n\n reachTime = 0;\n InterNode(srcNode, &stk);\n\n printf(\"\\nNumber of all possible and unique routes = %d\\n\", reachTime);\n\n}\n</code></pre>\n"
},
{
"answer_id": 25013511,
"author": "Avinash",
"author_id": 3116634,
"author_profile": "https://Stackoverflow.com/users/3116634",
"pm_score": 1,
"selected": false,
"text": "<p>The basic principle is you need not worry about graphs.This is standard problem known as Dynamic connectivity problem. There are following types of methods from which you can achieve nodes are connected or not:</p>\n\n<ol>\n<li>Quick Find</li>\n<li>Quick Union</li>\n<li>Improved Algorithm (Combination of both)</li>\n</ol>\n\n<p>Here is The C Code That I've tried with minimum time complexity O(log*n) That means for 65536 list of edges, it requires 4 search and for 2^65536, it requires 5 search. I am sharing my implementation from the algorithm: <a href=\"https://www.coursera.org/course/algs4partI\" rel=\"nofollow\">Algorithm Course from Princeton university</a> </p>\n\n<p><strong>TIP: You can find Java solution from link shared above with proper explanations.</strong></p>\n\n<pre><code>/* Checking Connection Between Two Edges */\n\n#include<stdio.h>\n#include<stdlib.h>\n#define MAX 100\n\n/*\n Data structure used\n\nvertex[] - used to Store The vertices\nsize - No. of vertices\nsz[] - size of child's\n*/\n\n/*Function Declaration */\nvoid initalize(int *vertex, int *sz, int size);\nint root(int *vertex, int i);\nvoid add(int *vertex, int *sz, int p, int q);\nint connected(int *vertex, int p, int q);\n\nint main() //Main Function\n{ \nchar filename[50], ch, ch1[MAX];\nint temp = 0, *vertex, first = 0, node1, node2, size = 0, *sz;\nFILE *fp;\n\n\nprintf(\"Enter the filename - \"); //Accept File Name\nscanf(\"%s\", filename);\nfp = fopen(filename, \"r\");\nif (fp == NULL)\n{\n printf(\"File does not exist\");\n exit(1);\n}\nwhile (1)\n{\n if (first == 0) //getting no. of vertices\n {\n ch = getc(fp);\n if (temp == 0)\n {\n fseek(fp, -1, 1);\n fscanf(fp, \"%s\", &ch1);\n fseek(fp, 1, 1);\n temp = 1;\n }\n if (isdigit(ch))\n {\n size = atoi(ch1);\n vertex = (int*) malloc(size * sizeof(int)); //dynamically allocate size \n sz = (int*) malloc(size * sizeof(int));\n initalize(vertex, sz, size); //initialization of vertex[] and sz[]\n }\n if (ch == '\\n')\n {\n first = 1;\n temp = 0;\n }\n }\n else\n {\n ch = fgetc(fp);\n if (isdigit(ch))\n temp = temp * 10 + (ch - 48); //calculating value from ch\n else\n {\n /* Validating the file */\n\n if (ch != ',' && ch != '\\n' && ch != EOF)\n {\n printf(\"\\n\\nUnkwown Character Detected.. Exiting..!\");\n\n exit(1);\n }\n if (ch == ',')\n node1 = temp;\n else\n {\n node2 = temp;\n printf(\"\\n\\n%d\\t%d\", node1, node2);\n if (node1 > node2)\n {\n temp = node1;\n node1 = node2;\n node2 = temp;\n }\n\n /* Adding the input nodes */\n\n if (!connected(vertex, node1, node2))\n add(vertex, sz, node1, node2);\n }\n temp = 0;\n }\n\n if (ch == EOF)\n {\n fclose(fp);\n break;\n }\n }\n}\n\ndo\n{\n printf(\"\\n\\n==== check if connected ===\");\n printf(\"\\nEnter First Vertex:\");\n scanf(\"%d\", &node1);\n printf(\"\\nEnter Second Vertex:\");\n scanf(\"%d\", &node2);\n\n /* Validating The Input */\n\n if( node1 > size || node2 > size )\n {\n printf(\"\\n\\n Invalid Node Value..\");\n break;\n }\n\n /* Checking the connectivity of nodes */\n\n if (connected(vertex, node1, node2))\n printf(\"Vertex %d and %d are Connected..!\", node1, node2);\n else\n printf(\"Vertex %d and %d are Not Connected..!\", node1, node2);\n\n\n printf(\"\\n 0/1: \");\n\n scanf(\"%d\", &temp);\n\n} while (temp != 0);\n\nfree((void*) vertex);\nfree((void*) sz);\n\n\nreturn 0;\n}\n\nvoid initalize(int *vertex, int *sz, int size) //Initialization of graph\n{\nint i;\nfor (i = 0; i < size; i++)\n{\n vertex[i] = i;\n sz[i] = 0;\n}\n}\nint root(int *vertex, int i) //obtaining the root\n{\nwhile (i != vertex[i])\n{\n vertex[i] = vertex[vertex[i]];\n i = vertex[i];\n}\nreturn i;\n}\n\n/* Time Complexity for Add --> logn */\nvoid add(int *vertex, int *sz, int p, int q) //Adding of node\n{\nint i, j;\ni = root(vertex, p);\nj = root(vertex, q);\n\n/* Adding small subtree in large subtree */\n\nif (sz[i] < sz[j])\n{\n vertex[i] = j;\n sz[j] += sz[i];\n}\nelse\n{\n vertex[j] = i;\n sz[i] += sz[j];\n}\n\n}\n\n/* Time Complexity for Search -->lg* n */\n\nint connected(int *vertex, int p, int q) //Checking of connectivity of nodes\n{\n/* Checking if root is same */\n\nif (root(vertex, p) == root(vertex, q))\n return 1;\n\nreturn 0;\n}\n</code></pre>\n"
},
{
"answer_id": 26429707,
"author": "batta",
"author_id": 444047,
"author_profile": "https://Stackoverflow.com/users/444047",
"pm_score": 2,
"selected": false,
"text": "<p>This may be late, but here's the same C# version of DFS algorithm in Java from Casey to traverse for all paths between two nodes using a stack. Readability is better with recursive as always.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> void DepthFirstIterative(T start, T endNode)\n {\n var visited = new LinkedList<T>();\n var stack = new Stack<T>();\n\n stack.Push(start);\n\n while (stack.Count != 0)\n {\n var current = stack.Pop();\n\n if (visited.Contains(current))\n continue;\n\n visited.AddLast(current);\n\n var neighbours = AdjacentNodes(current);\n\n foreach (var neighbour in neighbours)\n {\n if (visited.Contains(neighbour))\n continue;\n\n if (neighbour.Equals(endNode))\n {\n visited.AddLast(neighbour);\n printPath(visited));\n visited.RemoveLast();\n break;\n }\n }\n\n bool isPushed = false;\n foreach (var neighbour in neighbours.Reverse())\n {\n if (neighbour.Equals(endNode) || visited.Contains(neighbour) || stack.Contains(neighbour))\n {\n continue;\n }\n\n isPushed = true;\n stack.Push(neighbour);\n }\n\n if (!isPushed)\n visited.RemoveLast();\n }\n }\n</code></pre>\n\n<pre>\nThis is a sample graph to test:\n\n // Sample graph. Numbers are edge ids\n // 1 3 \n // A --- B --- C ----\n // | | 2 |\n // | 4 ----- D |\n // ------------------\n</pre>\n"
},
{
"answer_id": 35531270,
"author": "Ilmari Karonen",
"author_id": 411022,
"author_profile": "https://Stackoverflow.com/users/411022",
"pm_score": 3,
"selected": false,
"text": "<p>Since the existing non-recursive DFS implementation given in <a href=\"https://stackoverflow.com/questions/58306/graph-algorithm-to-find-all-connections-between-two-arbitrary-vertices/26429707#26429707\">this answer</a> seems to be broken, let me provide one that actually works.</p>\n\n<p>I've written this in Python, because I find it pretty readable and uncluttered by implementation details (and because it has the handy <code>yield</code> keyword for implementing <a href=\"https://wiki.python.org/moin/Generators\" rel=\"nofollow noreferrer\">generators</a>), but it should be fairly easy to port to other languages.</p>\n\n\n\n<pre class=\"lang-python prettyprint-override\"><code># a generator function to find all simple paths between two nodes in a\n# graph, represented as a dictionary that maps nodes to their neighbors\ndef find_simple_paths(graph, start, end):\n visited = set()\n visited.add(start)\n\n nodestack = list()\n indexstack = list()\n current = start\n i = 0\n\n while True:\n # get a list of the neighbors of the current node\n neighbors = graph[current]\n\n # find the next unvisited neighbor of this node, if any\n while i < len(neighbors) and neighbors[i] in visited: i += 1\n\n if i >= len(neighbors):\n # we've reached the last neighbor of this node, backtrack\n visited.remove(current)\n if len(nodestack) < 1: break # can't backtrack, stop!\n current = nodestack.pop()\n i = indexstack.pop()\n elif neighbors[i] == end:\n # yay, we found the target node! let the caller process the path\n yield nodestack + [current, end]\n i += 1\n else:\n # push current node and index onto stacks, switch to neighbor\n nodestack.append(current)\n indexstack.append(i+1)\n visited.add(neighbors[i])\n current = neighbors[i]\n i = 0\n</code></pre>\n\n<p>This code maintains two parallel stacks: one containing the earlier nodes in the current path, and one containing the current neighbor index for each node in the node stack (so that we can resume iterating through the neighbors of a node when we pop it back off the stack). I could've equally well used a single stack of (node, index) pairs, but I figured the two-stack method would be more readable, and perhaps easier to implement for users of other languages.</p>\n\n<p>This code also uses a separate <code>visited</code> set, which always contains the current node and any nodes on the stack, to let me efficiently check whether a node is already part of the current path. If your language happens to have an \"ordered set\" data structure that provides both efficient stack-like push/pop operations <em>and</em> efficient membership queries, you can use that for the node stack and get rid of the separate <code>visited</code> set.</p>\n\n<p>Alternatively, if you're using a custom mutable class / structure for your nodes, you can just store a boolean flag in each node to indicate whether it has been visited as part of the current search path. Of course, this method won't let you run two searches on the same graph in parallel, should you for some reason wish to do that.</p>\n\n<p>Here's some test code demonstrating how the function given above works:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code># test graph:\n# ,---B---.\n# A | D\n# `---C---'\ngraph = {\n \"A\": (\"B\", \"C\"),\n \"B\": (\"A\", \"C\", \"D\"),\n \"C\": (\"A\", \"B\", \"D\"),\n \"D\": (\"B\", \"C\"),\n}\n\n# find paths from A to D\nfor path in find_simple_paths(graph, \"A\", \"D\"): print \" -> \".join(path)\n</code></pre>\n\n<p>Running this code on the given example graph produces the following output:</p>\n\n<pre>\nA -> B -> C -> D\nA -> B -> D\nA -> C -> B -> D\nA -> C -> D\n</pre>\n\n<p>Note that, while this example graph is undirected (i.e. all its edges go both ways), the algorithm also works for arbitrary directed graphs. For example, removing the <code>C -> B</code> edge (by removing <code>B</code> from the neighbor list of <code>C</code>) yields the same output except for the third path (<code>A -> C -> B -> D</code>), which is no longer possible.</p>\n\n<hr>\n\n<p><strong>Ps.</strong> It's easy to construct graphs for which simple search algorithms like this one (and the others given in this thread) perform very poorly.</p>\n\n<p>For example, consider the task of find all paths from A to B on an undirected graph where the starting node A has two neighbors: the target node B (which has no other neighbors than A) and a node C that is part of a <a href=\"https://en.wikipedia.org/wiki/Clique_%28graph_theory%29\" rel=\"nofollow noreferrer\">clique</a> of <em>n</em>+1 nodes, like this:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>graph = {\n \"A\": (\"B\", \"C\"),\n \"B\": (\"A\"),\n \"C\": (\"A\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"D\": (\"C\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"E\": (\"C\", \"D\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"F\": (\"C\", \"D\", \"E\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"G\": (\"C\", \"D\", \"E\", \"F\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"H\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"I\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"J\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"J\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"K\", \"L\", \"M\", \"N\", \"O\"),\n \"K\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"L\", \"M\", \"N\", \"O\"),\n \"L\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"M\", \"N\", \"O\"),\n \"M\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"N\", \"O\"),\n \"N\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"O\"),\n \"O\": (\"C\", \"D\", \"E\", \"F\", \"G\", \"H\", \"I\", \"J\", \"K\", \"L\", \"M\", \"N\"),\n}\n</code></pre>\n\n<p>It's easy to see that the only path between A and B is the direct one, but a naïve DFS started from node A will waste O(<em>n</em>!) time uselessly exploring paths within the clique, even though it's obvious (to a human) that none of those paths can possibly lead to B.</p>\n\n<p>One can also construct <a href=\"https://en.wikipedia.org/wiki/Directed_acyclic_graph\" rel=\"nofollow noreferrer\">DAGs</a> with similar properties, e.g. by having the starting node A connect target node B and to two other nodes C<sub>1</sub> and C<sub>2</sub>, both of which connect to the nodes D<sub>1</sub> and D<sub>2</sub>, both of which connect to E<sub>1</sub> and E<sub>2</sub>, and so on. For <em>n</em> layers of nodes arranged like this, a naïve search for all paths from A to B will end up wasting O(2<sup><em>n</em></sup>) time examining all the possible dead ends before giving up.</p>\n\n<p>Of course, adding an edge to the target node B from one of the nodes in the clique (other than C), or from the last layer of the DAG, <em>would</em> create an exponentially large number of possible paths from A to B, and a purely local search algorithm can't really tell in advance whether it will find such an edge or not. Thus, in a sense, the poor <a href=\"https://en.wikipedia.org/wiki/Output-sensitive_algorithm\" rel=\"nofollow noreferrer\">output sensitivity</a> of such naïve searches is due to their lack of awareness of the global structure of the graph.</p>\n\n<p>While there are various preprocessing methods (such as iteratively eliminating leaf nodes, searching for single-node vertex separators, etc.) that could be used to avoid some of these \"exponential-time dead ends\", I don't know of any general preprocessing trick that could eliminate them in <em>all</em> cases. A general solution would be to check at every step of the search whether the target node is still reachable (using a sub-search), and backtrack early if it isn't — but alas, that would significantly slow down the search (at worst, proportionally to the size of the graph) for many graphs that <em>don't</em> contain such pathological dead ends.</p>\n"
},
{
"answer_id": 39172826,
"author": "Jamshed Katta",
"author_id": 4314880,
"author_profile": "https://Stackoverflow.com/users/4314880",
"pm_score": 0,
"selected": false,
"text": "<p>Adding to Casey Watson's answer, here is another Java implementation,. \nInitializing the visited node with the start node.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private void getPaths(Graph graph, LinkedList<String> visitedNodes) {\n LinkedList<String> adjacent = graph.getAdjacent(visitedNodes.getLast());\n for(String node : adjacent){\n if(visitedNodes.contains(node)){\n continue;\n }\n if(node.equals(END)){\n visitedNodes.add(node);\n printPath(visitedNodes);\n visitedNodes.removeLast();\n }\n visitedNodes.add(node);\n getPaths(graph, visitedNodes);\n visitedNodes.removeLast(); \n }\n }\n</code></pre>\n"
},
{
"answer_id": 42600378,
"author": "SumNeuron",
"author_id": 5623899,
"author_profile": "https://Stackoverflow.com/users/5623899",
"pm_score": 1,
"selected": false,
"text": "<h1>find_paths[s, t, d, k]</h1>\n\n<p>This question is old and answered already. However, none show perhaps a more flexible algorithm for accomplishing the same thing. So I'll throw my hat into the ring.</p>\n\n<p>I personally find an algorithm of the form <code>find_paths[s, t, d, k]</code> useful, where:</p>\n\n<ul>\n<li>s is the starting node</li>\n<li>t is the target node</li>\n<li>d is the maximum depth to search</li>\n<li>k is the number of paths to find</li>\n</ul>\n\n<p>Using your programming language's form of infinity for <code>d</code> and <code>k</code> will give you all paths§.</p>\n\n<p>§ obviously if you are using a directed graph and you want all <em>undirected</em> paths between <code>s</code> and <code>t</code> you will have to run this both ways:</p>\n\n<pre><code>find_paths[s, t, d, k] <join> find_paths[t, s, d, k]\n</code></pre>\n\n<hr>\n\n<h3>Helper Function</h3>\n\n<p>I personally like recursion, although it can difficult some times, anyway first lets define our helper function:</p>\n\n<pre><code>def find_paths_recursion(graph, current, goal, current_depth, max_depth, num_paths, current_path, paths_found)\n current_path.append(current)\n\n if current_depth > max_depth:\n return\n\n if current == goal:\n if len(paths_found) <= number_of_paths_to_find:\n paths_found.append(copy(current_path))\n\n current_path.pop()\n return\n\n else:\n for successor in graph[current]:\n self.find_paths_recursion(graph, successor, goal, current_depth + 1, max_depth, num_paths, current_path, paths_found)\n\n current_path.pop()\n</code></pre>\n\n<h3>Main Function</h3>\n\n<p>With that out of the way, the core function is trivial:</p>\n\n<pre><code>def find_paths[s, t, d, k]:\n paths_found = [] # PASSING THIS BY REFERENCE \n find_paths_recursion(s, t, 0, d, k, [], paths_found)\n</code></pre>\n\n<hr>\n\n<p>First, lets notice a few thing:</p>\n\n<ul>\n<li>the above pseudo-code is a mash-up of languages - but most strongly resembling python (since I was just coding in it). A strict copy-paste will not work.</li>\n<li><code>[]</code> is an uninitialized list, replace this with the equivalent for your programming language of choice</li>\n<li><code>paths_found</code> is passed by <strong>reference</strong>. It is clear that the recursion function doesn't return anything. Handle this appropriately.</li>\n<li>here <code>graph</code> is assuming some form of <code>hashed</code> structure. There are a plethora of ways to implement a graph. Either way, <code>graph[vertex]</code> gets you a list of adjacent vertices in a <em>directed</em> graph - adjust accordingly.</li>\n<li>this assumes you have pre-processed to remove \"buckles\" (self-loops), cycles and multi-edges</li>\n</ul>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58306",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3534/"
]
| I am trying to determine the best time efficient algorithm to accomplish the task described below.
I have a set of records. For this set of records I have connection data which indicates how pairs of records from this set connect to one another. This basically represents an undirected graph, with the records being the vertices and the connection data the edges.
All of the records in the set have connection information (i.e. no orphan records are present; each record in the set connects to one or more other records in the set).
I want to choose any two records from the set and be able to show all simple paths between the chosen records. By "simple paths" I mean the paths which do not have repeated records in the path (i.e. finite paths only).
Note: The two chosen records will always be different (i.e. start and end vertex will never be the same; no cycles).
For example:
```
If I have the following records:
A, B, C, D, E
and the following represents the connections:
(A,B),(A,C),(B,A),(B,D),(B,E),(B,F),(C,A),(C,E),
(C,F),(D,B),(E,C),(E,F),(F,B),(F,C),(F,E)
[where (A,B) means record A connects to record B]
```
If I chose B as my starting record and E as my ending record, I would want to find all simple paths through the record connections that would connect record B to record E.
```
All paths connecting B to E:
B->E
B->F->E
B->F->C->E
B->A->C->E
B->A->C->F->E
```
This is an example, in practice I may have sets containing hundreds of thousands of records. | It appears that this can be accomplished with a depth-first search of the graph. **The depth-first search will find all non-cyclical paths between two nodes.** This algorithm should be very fast and scale to large graphs (The graph data structure is sparse so it only uses as much memory as it needs to).
I noticed that the graph you specified above has only one edge that is directional (B,E). Was this a typo or is it really a directed graph? This solution works regardless. Sorry I was unable to do it in C, I'm a bit weak in that area. I expect that you will be able to translate this Java code without too much trouble though.
**Graph.java:**
```java
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
public class Graph {
private Map<String, LinkedHashSet<String>> map = new HashMap();
public void addEdge(String node1, String node2) {
LinkedHashSet<String> adjacent = map.get(node1);
if(adjacent==null) {
adjacent = new LinkedHashSet();
map.put(node1, adjacent);
}
adjacent.add(node2);
}
public void addTwoWayVertex(String node1, String node2) {
addEdge(node1, node2);
addEdge(node2, node1);
}
public boolean isConnected(String node1, String node2) {
Set adjacent = map.get(node1);
if(adjacent==null) {
return false;
}
return adjacent.contains(node2);
}
public LinkedList<String> adjacentNodes(String last) {
LinkedHashSet<String> adjacent = map.get(last);
if(adjacent==null) {
return new LinkedList();
}
return new LinkedList<String>(adjacent);
}
}
```
**Search.java:**
```java
import java.util.LinkedList;
public class Search {
private static final String START = "B";
private static final String END = "E";
public static void main(String[] args) {
// this graph is directional
Graph graph = new Graph();
graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "A");
graph.addEdge("B", "D");
graph.addEdge("B", "E"); // this is the only one-way connection
graph.addEdge("B", "F");
graph.addEdge("C", "A");
graph.addEdge("C", "E");
graph.addEdge("C", "F");
graph.addEdge("D", "B");
graph.addEdge("E", "C");
graph.addEdge("E", "F");
graph.addEdge("F", "B");
graph.addEdge("F", "C");
graph.addEdge("F", "E");
LinkedList<String> visited = new LinkedList();
visited.add(START);
new Search().depthFirst(graph, visited);
}
private void depthFirst(Graph graph, LinkedList<String> visited) {
LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
// examine adjacent nodes
for (String node : nodes) {
if (visited.contains(node)) {
continue;
}
if (node.equals(END)) {
visited.add(node);
printPath(visited);
visited.removeLast();
break;
}
}
for (String node : nodes) {
if (visited.contains(node) || node.equals(END)) {
continue;
}
visited.addLast(node);
depthFirst(graph, visited);
visited.removeLast();
}
}
private void printPath(LinkedList<String> visited) {
for (String node : visited) {
System.out.print(node);
System.out.print(" ");
}
System.out.println();
}
}
```
Program Output:
```java
B E
B A C E
B A C F E
B F E
B F C E
``` |
58,380 | <p>The following bit of code catches the EOS Exception</p>
<pre><code>using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
</code></pre>
<p>So why do I still receive first-chance exceptions in my console? </p>
<blockquote>
<p>A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll</p>
</blockquote>
<p>Is there a way to hide these first chance exception messages?</p>
| [
{
"answer_id": 58381,
"author": "DevelopingChris",
"author_id": 1220,
"author_profile": "https://Stackoverflow.com/users/1220",
"pm_score": -1,
"selected": false,
"text": "<p>I think the stream is throwing this exception, so your try is scoped to narrow to catch it.</p>\n\n<p>Add a few more try catch combos around the different scopes until you catch it where its actually being thrown, but it appears to be happening either at our outside of your using, since the stream object is not created in the using's scope.</p>\n"
},
{
"answer_id": 58387,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 7,
"selected": true,
"text": "<p>The point of \"first-chance\" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A \"second-chance\" exception is one that has no appropriate handler. Sometimes you want to catch \"first-chance\" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.</p>\n\n<p>There's nothing to be concerned with. This is normal behavior.</p>\n"
},
{
"answer_id": 58392,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 4,
"selected": false,
"text": "<ol>\n<li><p>In Visual Studio you can change the settings for the way the Debugger handles (breaks on) exceptions.</p>\n<p>Go to Debug > Exceptions. (Note this may not be in your menu depending on your Visual Studio Environment setting. If not just add it to your menu using the Customize menu.)</p>\n<p>There you are presented with a dialog of exceptions and when to break on them.</p>\n<p>In the line "Common Language Runtime Exceptions" you can deselect thrown (which should then stop bothering you about first-chance exceptions) and you can also deselect User-unhandeled (which I would not recommend) if want to.</p>\n</li>\n<li><p>The message you are getting should not be in the console, but should be appearing in the 'Output' window of Visual Studio. If the latter is the case, then I have not found a possibility to remove that, but it doesn't appear if you run the app without Visual Studio.</p>\n</li>\n</ol>\n"
},
{
"answer_id": 58409,
"author": "loudej",
"author_id": 6056,
"author_profile": "https://Stackoverflow.com/users/6056",
"pm_score": 4,
"selected": false,
"text": "<p>Unlike Java, .NET exceptions are fairly expensive in terms of processing power, and handled exceptions should be avoided in the normal and successful execution path.</p>\n\n<p>Not only will you avoid clutter in the console window, but your performance will improve, and it will make performance counters like .NET CLR Exceptions more meaningful.</p>\n\n<p>In this example you would use</p>\n\n<pre><code>while (reader.PeekChar() != -1)\n{\n bodyByteList.Add(reader.ReadByte());\n}\n</code></pre>\n"
},
{
"answer_id": 60765,
"author": "André Chalella",
"author_id": 4850,
"author_profile": "https://Stackoverflow.com/users/4850",
"pm_score": 8,
"selected": false,
"text": "<p>To avoid seeing the messages, right-click on the output window and uncheck \"Exception Messages\".</p>\n\n<p>However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.</p>\n"
},
{
"answer_id": 1247084,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>in VB.NET:</p>\n\n<pre><code><DebuggerHidden()> _\nPublic Function Write(ByVal Text As String) As Boolean\n ...\n</code></pre>\n"
},
{
"answer_id": 2799329,
"author": "AareP",
"author_id": 11741,
"author_profile": "https://Stackoverflow.com/users/11741",
"pm_score": 2,
"selected": false,
"text": "<p>Actually if are having many exceptions per second, you would achieve must better performance by checking reader.EndOfStream-value.. Printing out those exception messages is unbelievably slow, and hiding them in visual studio won't speed up anything.</p>\n"
},
{
"answer_id": 13086139,
"author": "Hallgeir Engen",
"author_id": 813606,
"author_profile": "https://Stackoverflow.com/users/813606",
"pm_score": 3,
"selected": false,
"text": "<p>I had this problem and couldn't figure out where the exception was thrown. So my solution was to enable Visual Studio to stop executing on this kind of exception. </p>\n\n<ol>\n<li>Navigate to \"Debug/Exceptions\"</li>\n<li>Expand the \"Common Language Runtime Exceptions\" tree.</li>\n<li>Expand the \"System\" branch.</li>\n<li>Scroll down to where \"NullReferenceException\" is, and check the\n\"throw\" checkbox, and uncheck the \"user-handled\".</li>\n<li>Debug your project.</li>\n</ol>\n"
},
{
"answer_id": 23159773,
"author": "VoteCoffee",
"author_id": 848419,
"author_profile": "https://Stackoverflow.com/users/848419",
"pm_score": 2,
"selected": false,
"text": "<p>If you want more control over these messages, you can add a handler:</p>\n\n<pre><code>Friend Sub AddTheHandler()\nAddHandler AppDomain.CurrentDomain.FirstChanceException, AddressOf FirstChanceExceptionHandler\nEnd Sub\n\n<Conditional(\"DEBUG\")>\nFriend Sub FirstChanceExceptionHandler( source As Object, e As Runtime.ExceptionServices.FirstChanceExceptionEventArgs)\n' Process first chance exception\n\nEnd Sub\n</code></pre>\n\n<p>This allows you to silence them as mentioned in other comments, but still makes sure you are able to be aware of them. I find it is good to see how many I am really throwing if I log a message and timestamp to a text file.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/209/"
]
| The following bit of code catches the EOS Exception
```
using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
```
So why do I still receive first-chance exceptions in my console?
>
> A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll
>
>
>
Is there a way to hide these first chance exception messages? | The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.
There's nothing to be concerned with. This is normal behavior. |
58,384 | <p>I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem):</p>
<pre><code>public class GraphicsItem<T>
{
private T _item;
public void Load(T item)
{
_item = item;
}
}
</code></pre>
<p>How can I save such open generic type in an array?</p>
| [
{
"answer_id": 58401,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to store heterogeneous GrpahicsItem's i.e. GraphicsItem< X> and GrpahicsItem< Y> you need to derive them from common base class, or implement common interface. Another option is to store them in List< object></p>\n"
},
{
"answer_id": 58406,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 0,
"selected": false,
"text": "<p>Are you trying to create an array of GraphicsItem in a non-generic method?</p>\n\n<p>You cannot do the following:</p>\n\n<pre><code>static void foo()\n{\n var _bar = List<GraphicsItem<T>>();\n}\n</code></pre>\n\n<p>and then fill the list later. </p>\n\n<p>More probably you are trying to do something like this?</p>\n\n<pre><code>static GraphicsItem<T>[] CreateArrays<T>()\n{\n GraphicsItem<T>[] _foo = new GraphicsItem<T>[1];\n\n // This can't work, because you don't know if T == typeof(string)\n // _foo[0] = (GraphicsItem<T>)new GraphicsItem<string>();\n\n // You can only create an array of the scoped type parameter T\n _foo[0] = new GraphicsItem<T>();\n\n List<GraphicsItem<T>> _bar = new List<GraphicsItem<T>>();\n\n // Again same reason as above\n // _bar.Add(new GraphicsItem<string>());\n\n // This works\n _bar.Add(new GraphicsItem<T>());\n\n return _bar.ToArray();\n}\n</code></pre>\n\n<p>Remember you are going to need a generic type reference to create an array of a generic type. This can be either at method-level (using the T after the method) or at class-level (using the T after the class).</p>\n\n<p>If you want the method to return an array of GraphicsItem and GraphicsItem, then let GraphicsItem inherit from a non-generic base class GraphicsItem and return an array of that. You will lose all type safety though.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 58462,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 3,
"selected": true,
"text": "<p>Implement a non-generic interface and use that:</p>\n\n<pre><code>public class GraphicsItem<T> : IGraphicsItem\n{\n private T _item;\n\n public void Load(T item)\n {\n _item = item;\n }\n\n public void SomethingWhichIsNotGeneric(int i)\n {\n // Code goes here...\n }\n}\n\npublic interface IGraphicsItem\n{\n void SomethingWhichIsNotGeneric(int i);\n}\n</code></pre>\n\n<p>Then use that interface as the item in the list:</p>\n\n<pre><code>var values = new List<IGraphicsItem>();\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58384",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2078/"
]
| I am facing a problem with .NET generics. The thing I want to do is saving an array of generics types (GraphicsItem):
```
public class GraphicsItem<T>
{
private T _item;
public void Load(T item)
{
_item = item;
}
}
```
How can I save such open generic type in an array? | Implement a non-generic interface and use that:
```
public class GraphicsItem<T> : IGraphicsItem
{
private T _item;
public void Load(T item)
{
_item = item;
}
public void SomethingWhichIsNotGeneric(int i)
{
// Code goes here...
}
}
public interface IGraphicsItem
{
void SomethingWhichIsNotGeneric(int i);
}
```
Then use that interface as the item in the list:
```
var values = new List<IGraphicsItem>();
``` |
58,425 | <p>I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".</p>
<p>The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."</p>
<p>Here is my app.xaml:</p>
<pre><code><Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
</code></pre>
<p>And here is my app.xaml.cs (exception thrown at "public App()"):</p>
<pre><code>public partial class App : Application
{
public App()
{
Bootstrapper bootStrapper = new Bootstrapper();
bootStrapper.Run();
}
}
</code></pre>
<p>I have set the "App" class as the startup object in the project.</p>
<p>What is going astray?</p>
| [
{
"answer_id": 58447,
"author": "ima",
"author_id": 5733,
"author_profile": "https://Stackoverflow.com/users/5733",
"pm_score": 3,
"selected": false,
"text": "<p>Do you use .config file? If so, check it for errors. Initialization errors of such sort are often triggered by invalid XML: if there are no errors in XAML, XML config is the first place to look.</p>\n"
},
{
"answer_id": 58464,
"author": "Adrian Clark",
"author_id": 148,
"author_profile": "https://Stackoverflow.com/users/148",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this:</p>\n\n<pre><code><configuration>\n <startup>\n <supportedRuntime version=\"v2.0.50727\" sku=\"Client\"/>\n </startup>\n <configSections>\n <section name=\"modules\" type=\"Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite\"/>\n </configSections>\n <modules>\n <module assemblyFile=\"Modules/MyNamespace.Modules.ModuleName.dll\" moduleType=\"MyNamespace.Modules.ModuleName.ModuleClass\" moduleName=\"Name\"/>\n </modules>\n</configuration>\n</code></pre>\n\n<p>It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the \"Client Profile\" available in 3.5 SP1.</p>\n\n<p>After some mucking about checking and un-checking the box I ended up with a configuration file like this:</p>\n\n<pre><code><configuration>\n <configSections>\n <section name=\"modules\" type=\"Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite\"/>\n </configSections>\n <modules>\n <module assemblyFile=\"Modules/MyNamespace.Modules.ModuleName.dll\" moduleType=\"MyNamespace.Modules.ModuleName.ModuleClass\" moduleName=\"Name\"/>\n </modules>\n <startup>\n <supportedRuntime version=\"v2.0.50727\" sku=\"Client\"/>\n </startup>\n</configuration>\n</code></pre>\n\n<p>Which works!</p>\n\n<p>I'm not sure why the order of elements in the app.config is important - but it seems it is.</p>\n"
},
{
"answer_id": 1012016,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You have two sections named \"modules\". Place both module definitions in one section named \"modules\".</p>\n"
},
{
"answer_id": 2876057,
"author": "Umesh Bhavsar",
"author_id": 346354,
"author_profile": "https://Stackoverflow.com/users/346354",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into a similar situation.\nAfter searching for a week time, I found the resolution and it really worked for me.\nIt solved 2-3 problems arising due to same problem.</p>\n\n<p>Follow these steps:\nCheck the WPF key (absence) in registry:\nHKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\Setup\\Windows Presentation Foundation\nMy problem was due to the absence of above mentioned key in registry.</p>\n\n<p>You can modify and use following details in your registry: (Actually, you can save in file and import in registry)</p>\n\n<p>[HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\NET Framework Setup\\NDP\\v3.0\\Setup\\Windows Presentation Foundation]\n@=\"WPF v3.0.6920.1453\"\n\"Version\"=\"3.0.6920.1453\"\n\"WPFReferenceAssembliesPathx86\"=\"C:\\Program Files\\Reference Assemblies\\Microsoft\\Framework\\v3.0\\\"\n\"WPFCommonAssembliesPathx86\"=\"C:\\Windows\\System32\\\"\n\"InstallRoot\"=\"C:\\Windows\\Microsoft.NET\\Framework\\v3.0\\WPF\\\"\n\"InstallSuccess\"=dword:00000001\n\"ProductVersion\"=\"3.0.6920.1453\"\n\"WPFNonReferenceAssembliesPathx86\"=\"C:\\Windows\\Microsoft.NET\\Framework\\v3.0\\WPF\\\"</p>\n\n<p>I am sure it will work.</p>\n\n<p>all the best.</p>\n\n<p>Regards,</p>\n\n<p>Umesh </p>\n"
},
{
"answer_id": 14492905,
"author": "Lin Song Yang",
"author_id": 247011,
"author_profile": "https://Stackoverflow.com/users/247011",
"pm_score": 4,
"selected": false,
"text": "<p>Anything wrong in the <strong>App.config</strong> file may cause the error, such as a typo of <code>*</code> at the end of a line, eg <code>...</startup></code> has an additional \"*\" at the end of the line <code>...</startup>*</code>.</p>\n"
},
{
"answer_id": 36924610,
"author": "usefulBee",
"author_id": 2093880,
"author_profile": "https://Stackoverflow.com/users/2093880",
"pm_score": 2,
"selected": false,
"text": "<p>Tracking the InnerExceptions deep down , you might find the following error:</p>\n\n<p><code>\"Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element\"</code></p>\n\n<p>This order change happened after Visual Studio EntityFramework Wizard added the connectionStrings element to the top</p>\n"
},
{
"answer_id": 39642579,
"author": "lvmeijer",
"author_id": 393367,
"author_profile": "https://Stackoverflow.com/users/393367",
"pm_score": 2,
"selected": false,
"text": "<p>If you only see the TypeInitializationException with no reason or no details on what's wrong, then disable Just My Code in the Visual Studio options. </p>\n"
},
{
"answer_id": 42322164,
"author": "Denis Kirin",
"author_id": 7191785,
"author_profile": "https://Stackoverflow.com/users/7191785",
"pm_score": 0,
"selected": false,
"text": "<p>In my case this is need to be added:</p>\n\n<pre><code><configSections>\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n<section name=\"entityFramework\" type=\"System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" requirePermission=\"false\" />\n</code></pre>\n\n<p></p>\n\n<p>Section at App.config (VS 2015 .NET 4.5.2)</p>\n\n<p>Open any WPF project what builded before, check build, if OK - check and compare App.config's at both projects</p>\n"
},
{
"answer_id": 46125350,
"author": "Jason Cheng",
"author_id": 1419440,
"author_profile": "https://Stackoverflow.com/users/1419440",
"pm_score": 2,
"selected": false,
"text": "<p>For me, I had copied app settings over from another application into my app.config into a new section called \"userSettings\". However, there needs to be a \"configSections\" also added to the app.config which defines \"userSettings\". I deleted the userSettings section then edited the app settings and saved it. VS automatically creates the correct \"userSettings\" and \"configSections\" for you if they are absent.</p>\n"
},
{
"answer_id": 63356436,
"author": "Sely Lychee",
"author_id": 5128530,
"author_profile": "https://Stackoverflow.com/users/5128530",
"pm_score": 0,
"selected": false,
"text": "<p>For me I renamed my Application name and caused this error. I had a server and client app. the server app was not having this issue. so i checked App.config file of both server and client. I found</p>\n<pre><code><startup>\n<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />\n</startup>\n\n<configSections>\n<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n</configSections>\n</code></pre>\n<p><startup> tag above <configSections> tag in client and server had the other way so I copy pasted startup tag down configSections tag and it worked. Like this.</p>\n<pre><code><configSections>\n<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />\n<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->\n</configSections>\n\n<startup>\n<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />\n</startup>\n</code></pre>\n"
},
{
"answer_id": 70990589,
"author": "AviB",
"author_id": 4653372,
"author_profile": "https://Stackoverflow.com/users/4653372",
"pm_score": 0,
"selected": false,
"text": "<p>I was getting the same error. The suggestions mentioned above did not work for me. i was getting the following error after running</p>\n<pre><code>System.TypeInitializationException\n HResult=0x80131534\n Message=The type initializer for 'System.Windows.Application' threw an exception.\n Source=PresentationFramework\n StackTrace:\n at System.Windows.Application..ctor()\n at ShortBarDetectionSystem.App..ctor()\n at ShortBarDetectionSystem.App.Main()\n\nInner Exception 1:\nTypeInitializationException: The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception.\n\nInner Exception 2:\nTypeInitializationException: The type initializer for 'MS.Internal.TraceDependencyProperty' threw an exception.\n\nInner Exception 3:\nConfigurationErrorsException: Configuration system failed to initialize\n\nInner Exception 4:\nConfigurationErrorsException: Section or group name 'oracle.manageddataaccess.client' is already defined. Updates to this may only occur at the configuration level where it is defined. (C:\\ShortBarDetectionSystem\\code\\framework\\TypeInitializationException\\ver0_1\\ShortBarDetectionSystem\\ShortBarDetectionSystem\\bin\\x64\\Debug\\GrateBarDefectDetectionSystem.exe.Config line 4)\n</code></pre>\n<p>I was getting an error in my exe.config file line 4. The .exe.config file was :</p>\n<pre><code><?xml version="1.0" encoding="utf-8"?>\n<configuration>\n <configSections>\n <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />\n </configSections>\n <startup>\n <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />\n </startup>\n <system.data>\n <DbProviderFactories>\n <remove invariant="Oracle.ManagedDataAccess.Client" />\n <add name="ODP.NET, Managed Driver" invariant="Oracle.ManagedDataAccess.Client" description="Oracle Data Provider for .NET, Managed Driver" type="Oracle.ManagedDataAccess.Client.OracleClientFactory, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />\n </DbProviderFactories>\n </system.data>\n <runtime>\n <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">\n <dependentAssembly>\n <assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />\n </dependentAssembly>\n <dependentAssembly>\n <assemblyIdentity name="System.Text.Json" publicKeyToken="cc7b13ffcd2ddd51" culture="neutral" />\n <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n</configuration>\n</code></pre>\n<p>However after trial and error i figured out that deleting the configSections</p>\n<pre><code><configSections>\n <section name="oracle.manageddataaccess.client" type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess, Version=4.122.21.1, Culture=neutral, PublicKeyToken=89b483f429c47342" />\n </configSections>\n</code></pre>\n<p>worked for me.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148/"
]
| I have a simple WPF application which I am trying to start. I am following the Microsoft Patterns and Practices "Composite Application Guidance for WPF". I've followed their instructions however my WPF application fails immediately with a "TypeInitializationException".
The InnerException property reveals that "The type initializer for 'System.Windows.Navigation.BaseUriHelper' threw an exception."
Here is my app.xaml:
```
<Application x:Class="MyNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Application.Resources>
</Application.Resources>
</Application>
```
And here is my app.xaml.cs (exception thrown at "public App()"):
```
public partial class App : Application
{
public App()
{
Bootstrapper bootStrapper = new Bootstrapper();
bootStrapper.Run();
}
}
```
I have set the "App" class as the startup object in the project.
What is going astray? | Thanks @ima, your answer pointed me in the right direction. I was using an app.config file and it contained this:
```
<configuration>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
</configuration>
```
It seems the problem was the <startup> element because when I removed it the application ran fine. I was confused because Visual Studio 2008 added that when I checked the box to utilise the "Client Profile" available in 3.5 SP1.
After some mucking about checking and un-checking the box I ended up with a configuration file like this:
```
<configuration>
<configSections>
<section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
<module assemblyFile="Modules/MyNamespace.Modules.ModuleName.dll" moduleType="MyNamespace.Modules.ModuleName.ModuleClass" moduleName="Name"/>
</modules>
<startup>
<supportedRuntime version="v2.0.50727" sku="Client"/>
</startup>
</configuration>
```
Which works!
I'm not sure why the order of elements in the app.config is important - but it seems it is. |
58,429 | <p>How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.<p>
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
<p>For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:</p>
<pre><code>select sum(n) from numbers where n between 100 and 200
</code></pre>
<p>Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.</p>
<p>[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. <a href="https://stackoverflow.com/questions/58429/sql-set-based-range#59657">See below.</a></p>
| [
{
"answer_id": 58511,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 0,
"selected": false,
"text": "<p>If using SQL Server 2000 or greater, you could use the <strong>table datatype</strong> to avoid creating a normal or temporary table. Then use the normal table operations on it.</p>\n\n<p>With this solution you have essentially a table structure in memory that you can use almost like a real table, but much more performant.</p>\n\n<p>I found a good discussion here: <a href=\"http://www.odetocode.com/articles/365.aspx\" rel=\"nofollow noreferrer\">Temporary tables vs the table data type</a></p>\n"
},
{
"answer_id": 59188,
"author": "Anders Eurenius",
"author_id": 1421,
"author_profile": "https://Stackoverflow.com/users/1421",
"pm_score": 1,
"selected": false,
"text": "<p>This is basically one of those things that reveal SQL to be less than ideal. I'm thinking maybe the right way to do this is to build a function that creates the range. (Or a generator.)</p>\n\n<p>I believe the correct answer to your question is basically, \"you can't\".\n(Sorry.)</p>\n"
},
{
"answer_id": 59314,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 4,
"selected": true,
"text": "<p>I think the very short answer to your question is to use WITH clauses to generate your own.</p>\n\n<p>Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a <strong>huge</strong> failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.</p>\n\n<p>So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.</p>\n\n<p>Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them \"common table expressions\", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like...</p>\n\n<p>In Oracle SQL:</p>\n\n<pre><code>WITH\n digits AS -- Limit recursion by just using it for digits.\n (SELECT\n LEVEL - 1 AS num\n FROM\n DUAL\n WHERE\n LEVEL < 10\n CONNECT BY\n num = (PRIOR num) + 1),\n numrange AS\n (SELECT\n ones.num\n + (tens.num * 10)\n + (hundreds.num * 100)\n AS num\n FROM\n digits ones\n CROSS JOIN\n digits tens\n CROSS JOIN\n digits hundreds\n WHERE\n hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.\nSELECT\n -- Some columns and operations\nFROM\n numrange\n -- Join to other data if needed\n</code></pre>\n\n<p>This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.</p>\n\n<p>I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know.</p>\n\n<p>At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data.</p>\n\n<p><strong>UPDATE:</strong> I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven <a href=\"http://en.wikipedia.org/wiki/Declarative_programming_language\" rel=\"nofollow noreferrer\">declarative language</a>. Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.</p>\n"
},
{
"answer_id": 59657,
"author": "Hafthor",
"author_id": 4489,
"author_profile": "https://Stackoverflow.com/users/4489",
"pm_score": 2,
"selected": false,
"text": "<p>I created a SQL CLR table valued function that works great for this purpose.</p>\n\n<pre><code>SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11\nSELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this)\n</code></pre>\n\n<p>Here's the code:</p>\n\n<pre><code>using System;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\nusing System.Collections;\n\n[assembly: CLSCompliant(true)]\nnamespace Range {\n public static partial class UserDefinedFunctions {\n [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = \"FillRow\", TableDefinition = \"n bigint\")]\n public static IEnumerable Range(SqlInt64 start, SqlInt64 end, SqlInt64 incr) {\n return new Ranger(start.Value, end.Value, incr.Value);\n }\n\n [Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = \"FillRowF\", TableDefinition = \"n float\")]\n public static IEnumerable RangeF(SqlDouble start, SqlDouble end, SqlDouble incr) {\n return new RangerF(start.Value, end.Value, incr.Value);\n }\n\n public static void FillRow(object row, out SqlInt64 n) {\n n = new SqlInt64((long)row);\n }\n\n public static void FillRowF(object row, out SqlDouble n) {\n n = new SqlDouble((double)row);\n }\n }\n\n internal class Ranger : IEnumerable {\n Int64 _start, _end, _incr;\n\n public Ranger(Int64 start, Int64 end, Int64 incr) {\n _start = start; _end = end; _incr = incr;\n }\n\n public IEnumerator GetEnumerator() {\n return new RangerEnum(_start, _end, _incr);\n }\n }\n\n internal class RangerF : IEnumerable {\n double _start, _end, _incr;\n\n public RangerF(double start, double end, double incr) {\n _start = start; _end = end; _incr = incr;\n }\n\n public IEnumerator GetEnumerator() {\n return new RangerFEnum(_start, _end, _incr);\n }\n }\n\n internal class RangerEnum : IEnumerator {\n Int64 _cur, _start, _end, _incr;\n bool hasFetched = false;\n\n public RangerEnum(Int64 start, Int64 end, Int64 incr) {\n _start = _cur = start; _end = end; _incr = incr;\n if ((_start < _end ^ _incr > 0) || _incr == 0)\n throw new ArgumentException(\"Will never reach end!\");\n }\n\n public long Current {\n get { hasFetched = true; return _cur; }\n }\n\n object IEnumerator.Current {\n get { hasFetched = true; return _cur; }\n }\n\n public bool MoveNext() {\n if (hasFetched) _cur += _incr;\n return (_cur > _end ^ _incr > 0);\n }\n\n public void Reset() {\n _cur = _start; hasFetched = false;\n }\n }\n\n internal class RangerFEnum : IEnumerator {\n double _cur, _start, _end, _incr;\n bool hasFetched = false;\n\n public RangerFEnum(double start, double end, double incr) {\n _start = _cur = start; _end = end; _incr = incr;\n if ((_start < _end ^ _incr > 0) || _incr == 0)\n throw new ArgumentException(\"Will never reach end!\");\n }\n\n public double Current {\n get { hasFetched = true; return _cur; }\n }\n\n object IEnumerator.Current {\n get { hasFetched = true; return _cur; }\n }\n\n public bool MoveNext() {\n if (hasFetched) _cur += _incr;\n return (_cur > _end ^ _incr > 0);\n }\n\n public void Reset() {\n _cur = _start; hasFetched = false;\n }\n }\n}\n</code></pre>\n\n<p>and I deployed it like this:</p>\n\n<pre><code>create assembly Range from 'Range.dll' with permission_set=safe -- mod path to point to actual dll location on disk.\ngo\ncreate function dbo.Range(@start bigint, @end bigint, @incr bigint)\n returns table(n bigint)\n as external name [Range].[Range.UserDefinedFunctions].[Range]\ngo\ncreate function dbo.RangeF(@start float, @end float, @incr float)\n returns table(n float)\n as external name [Range].[Range.UserDefinedFunctions].[RangeF]\ngo\n</code></pre>\n"
},
{
"answer_id": 153973,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a hack you should never use:</p>\n\n<pre><code>select sum(numberGenerator.rank)\nfrom\n(\nselect\n rank = ( select count(*) \n from reallyLargeTable t1 \n where t1.uniqueValue > t2.uniqueValue ), \n t2.uniqueValue id1, \n t2.uniqueValue id2\nfrom reallyLargeTable t2 \n) numberGenerator\nwhere rank between 1 and 10\n</code></pre>\n\n<p>You can simplify this using the Rank() or Row_Number functions in SQL 2005</p>\n"
},
{
"answer_id": 7556043,
"author": "Mike Powell",
"author_id": 205,
"author_profile": "https://Stackoverflow.com/users/205",
"pm_score": 1,
"selected": false,
"text": "<p>You can use a common table expression to do this in SQL2005+.</p>\n\n<pre><code>WITH CTE AS\n(\n SELECT 100 AS n\n UNION ALL\n SELECT n + 1 AS n FROM CTE WHERE n + 1 <= 200\n)\nSELECT n FROM CTE\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58429",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4489/"
]
| How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:
```
select sum(n) from numbers where n between 100 and 200
```
Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.
[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. [See below.](https://stackoverflow.com/questions/58429/sql-set-based-range#59657) | I think the very short answer to your question is to use WITH clauses to generate your own.
Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a **huge** failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.
So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.
Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them "common table expressions", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like...
In Oracle SQL:
```
WITH
digits AS -- Limit recursion by just using it for digits.
(SELECT
LEVEL - 1 AS num
FROM
DUAL
WHERE
LEVEL < 10
CONNECT BY
num = (PRIOR num) + 1),
numrange AS
(SELECT
ones.num
+ (tens.num * 10)
+ (hundreds.num * 100)
AS num
FROM
digits ones
CROSS JOIN
digits tens
CROSS JOIN
digits hundreds
WHERE
hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.
SELECT
-- Some columns and operations
FROM
numrange
-- Join to other data if needed
```
This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.
I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know.
At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data.
**UPDATE:** I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven [declarative language](http://en.wikipedia.org/wiki/Declarative_programming_language). Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms. |
58,431 | <p>I have wondered for some time, what a nice, clean solution for joining an array of strings might look like.
Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".</p>
<p>Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented.
When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string).
I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).</p>
<p>Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant?</p>
| [
{
"answer_id": 58437,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 4,
"selected": false,
"text": "<p>The most elegant solution i found for problems like this is something like this (in pseudocode)</p>\n\n<pre><code>separator = \"\"\nforeach(item in stringCollection)\n{\n concatenatedString += separator + item\n separator = \",\"\n}\n</code></pre>\n\n<p>You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop.</p>\n"
},
{
"answer_id": 58440,
"author": "Matt Sheppard",
"author_id": 797,
"author_profile": "https://Stackoverflow.com/users/797",
"pm_score": 2,
"selected": false,
"text": "<p>I usually go with something like...</p>\n\n<pre><code>list = [\"Alpha\", \"Beta\", \"Gamma\"];\noutput = \"\";\nseparator = \"\";\nfor (int i = 0; i < list.length ; i++) {\n output = output + separator;\n output = output + list[i];\n separator = \", \";\n}\n</code></pre>\n\n<p>This works because on the first pass, separator is empty (so you don't get a comma at the start, but on every subsequent pass, you add a comma before adding the next element.</p>\n\n<p>You could certainly unroll this a little to make it a bit faster (assigning to the separator over and over isn't ideal), though I suspect that's something the compiler could do for you automatically.</p>\n\n<p>In the end though, I suspect pretty this is what most language level join functions come down to. Nothing more than syntax sugar, but it sure is sweet.</p>\n"
},
{
"answer_id": 58441,
"author": "Luke Halliwell",
"author_id": 3974,
"author_profile": "https://Stackoverflow.com/users/3974",
"pm_score": 2,
"selected": false,
"text": "<p>For pure elegance, a typical recursive functional-language solution is quite nice. This isn't in an actual language syntax but you get the idea (it's also hardcoded to use comma separator):</p>\n\n<p>join([]) = \"\"</p>\n\n<p>join([x]) = \"x\"</p>\n\n<p>join([x, rest]) = \"x,\" + join(rest)</p>\n\n<p>In reality you would write this in a more generic way, to reuse the same algorithm but abstract away the data type (doesn't have to be strings) and the operation (doesn't have to be concatenation with a comma in the middle). Then it usually gets called 'reduce', and many functional languages have this built in, e.g. multiplying all numbers in a list, in Lisp:</p>\n\n<p>(reduce #'* '(1 2 3 4 5)) => 120</p>\n"
},
{
"answer_id": 58452,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 3,
"selected": false,
"text": "<p>All of these solutions are decent ones, but for an underlying library, both independence of separator and decent speed are important. Here is a function that fits the requirement assuming the language has some form of string builder.</p>\n\n<pre><code>public static string join(String[] strings, String sep) {\n if(strings.length == 0) return \"\";\n if(strings.length == 1) return strings[0];\n StringBuilder sb = new StringBuilder();\n sb.append(strings[0]);\n for(int i = 1; i < strings.length; i++) {\n sb.append(sep);\n sb.append(strings[i]);\n }\n return sb.toString();\n}\n</code></pre>\n\n<p>EDIT: I suppose I should mention why this would be speedier. The main reason would be because any time you call c = a + b; the underlying construct is usually c = (new StringBuilder()).append(a).append(b).toString();. By reusing the same string builder object, we can reduce the amount of allocations and garbage we produce. </p>\n\n<p>And before someone chimes in with optimization is evil, we're talking about implementing a common library function. Acceptable, scalable performance is one of the requirements them. A join that takes a long time is one that's going to be not oft used.</p>\n"
},
{
"answer_id": 58454,
"author": "David L Morris",
"author_id": 3137,
"author_profile": "https://Stackoverflow.com/users/3137",
"pm_score": 1,
"selected": false,
"text": "<p>' Pseudo code Assume zero based</p>\n\n<pre>\nResultString = InputArray[0]\nn = 1\nwhile n (is less than) Number_Of_Strings\n ResultString (concatenate) \", \"\n ResultString (concatenate) InputArray[n]\n n = n + 1\nloop\n</pre>\n"
},
{
"answer_id": 58455,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>The following is no longer language-agnostic (but that doesn't matter for the discussion because the implementation is easily portable to other languages). I tried to implement Luke's (theretically best) solution in an imperative programming language. Take your pick; mine's C#. Not very elegant at all. However, (without any testing whatsoever) I could imagine that its performance is quite decent because the recursion is in fact tail recursive.</p>\n\n<p>My challenge: give a better recursive implementation (in an imperative language). You say what “better” means: less code, faster, I'm open for suggestions.</p>\n\n<pre><code>private static StringBuilder RecJoin(IEnumerator<string> xs, string sep, StringBuilder result) {\n result.Append(xs.Current);\n if (xs.MoveNext()) {\n result.Append(sep);\n return RecJoin(xs, sep, result);\n } else\n return result;\n}\n\npublic static string Join(this IEnumerable<string> xs, string separator) {\n var i = xs.GetEnumerator();\n if (!i.MoveNext())\n return string.Empty;\n else\n return RecJoin(i, separator, new StringBuilder()).ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 58496,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<p>In Perl, I just use the <strong>join</strong> command:</p>\n\n<pre><code>$ echo \"Alpha\nBeta\nGamma\" | perl -e 'print(join(\", \", map {chomp; $_} <> ))'\nAlpha, Beta, Gamma\n</code></pre>\n\n<p>(The <strong>map</strong> stuff is mostly there to create a list.)</p>\n\n<p>In languages that don't have a built in, like C, I use simple iteration (untested):</p>\n\n<pre><code>for (i = 0; i < N-1; i++){\n strcat(s, a[i]);\n strcat(s, \", \");\n}\nstrcat(s, a[N]);\n</code></pre>\n\n<p>Of course, you'd need to check the size of <em>s</em> before you add more bytes to it. </p>\n\n<p>You either have to special case the <a href=\"https://stackoverflow.com/questions/58431/algorithm-for-joining-eg-an-array-of-strings#58454\">first entry</a> or the last.</p>\n"
},
{
"answer_id": 58515,
"author": "Bobby Jack",
"author_id": 5058,
"author_profile": "https://Stackoverflow.com/users/5058",
"pm_score": 3,
"selected": false,
"text": "<p>Most languages nowadays - e.g. perl (mention by Jon Ericson), php, javascript - have a join() function or method, and this is by far the most elegant solution. Less code is better code.</p>\n\n<p>In response to Mendelt Siebenga, if you do require a hand-rolled solution, I'd go with the ternary operator for something like:</p>\n\n<pre><code>separator = \",\"\nforeach (item in stringCollection)\n{\n concatenatedString += concatenatedString ? separator + item : item\n}\n</code></pre>\n"
},
{
"answer_id": 61319,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 2,
"selected": false,
"text": "<p>@Mendelt Siebenga</p>\n\n<p>Strings are corner-stone objects in programming languages. Different languages implement strings differently. An implementation of <code>join()</code> strongly depends on underlying implementation of strings. Pseudocode doesn't reflect underlying implementation.</p>\n\n<p>Consider <code>join()</code> in Python. It can be easily used:</p>\n\n<pre><code>print \", \".join([\"Alpha\", \"Beta\", \"Gamma\"])\n# Alpha, Beta, Gamma\n</code></pre>\n\n<p>It could be easily implemented as follow:</p>\n\n<pre><code>def join(seq, sep=\" \"):\n if not seq: return \"\"\n elif len(seq) == 1: return seq[0]\n return reduce(lambda x, y: x + sep + y, seq)\n\nprint join([\"Alpha\", \"Beta\", \"Gamma\"], \", \")\n# Alpha, Beta, Gamma\n</code></pre>\n\n<p>And here how <code>join()</code> method is implemented in C (taken from <a href=\"http://svn.python.org/view/python/trunk/Objects/stringobject.c?rev=66119&view=markup\" rel=\"nofollow noreferrer\">trunk</a>):</p>\n\n<pre><code>PyDoc_STRVAR(join__doc__,\n\"S.join(sequence) -> string\\n\\\n\\n\\\nReturn a string which is the concatenation of the strings in the\\n\\\nsequence. The separator between elements is S.\");\n\nstatic PyObject *\nstring_join(PyStringObject *self, PyObject *orig)\n{\n char *sep = PyString_AS_STRING(self);\n const Py_ssize_t seplen = PyString_GET_SIZE(self);\n PyObject *res = NULL;\n char *p;\n Py_ssize_t seqlen = 0;\n size_t sz = 0;\n Py_ssize_t i;\n PyObject *seq, *item;\n\n seq = PySequence_Fast(orig, \"\");\n if (seq == NULL) {\n return NULL;\n }\n\n seqlen = PySequence_Size(seq);\n if (seqlen == 0) {\n Py_DECREF(seq);\n return PyString_FromString(\"\");\n }\n if (seqlen == 1) {\n item = PySequence_Fast_GET_ITEM(seq, 0);\n if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {\n Py_INCREF(item);\n Py_DECREF(seq);\n return item;\n }\n }\n\n /* There are at least two things to join, or else we have a subclass\n * of the builtin types in the sequence.\n * Do a pre-pass to figure out the total amount of space we'll\n * need (sz), see whether any argument is absurd, and defer to\n * the Unicode join if appropriate.\n */\n for (i = 0; i < seqlen; i++) {\n const size_t old_sz = sz;\n item = PySequence_Fast_GET_ITEM(seq, i);\n if (!PyString_Check(item)){\n#ifdef Py_USING_UNICODE\n if (PyUnicode_Check(item)) {\n /* Defer to Unicode join.\n * CAUTION: There's no gurantee that the\n * original sequence can be iterated over\n * again, so we must pass seq here.\n */\n PyObject *result;\n result = PyUnicode_Join((PyObject *)self, seq);\n Py_DECREF(seq);\n return result;\n }\n#endif\n PyErr_Format(PyExc_TypeError,\n \"sequence item %zd: expected string,\"\n \" %.80s found\",\n i, Py_TYPE(item)->tp_name);\n Py_DECREF(seq);\n return NULL;\n }\n sz += PyString_GET_SIZE(item);\n if (i != 0)\n sz += seplen;\n if (sz < old_sz || sz > PY_SSIZE_T_MAX) {\n PyErr_SetString(PyExc_OverflowError,\n \"join() result is too long for a Python string\");\n Py_DECREF(seq);\n return NULL;\n }\n }\n\n /* Allocate result space. */\n res = PyString_FromStringAndSize((char*)NULL, sz);\n if (res == NULL) {\n Py_DECREF(seq);\n return NULL;\n }\n\n /* Catenate everything. */\n p = PyString_AS_STRING(res);\n for (i = 0; i < seqlen; ++i) {\n size_t n;\n item = PySequence_Fast_GET_ITEM(seq, i);\n n = PyString_GET_SIZE(item);\n Py_MEMCPY(p, PyString_AS_STRING(item), n);\n p += n;\n if (i < seqlen - 1) {\n Py_MEMCPY(p, sep, seplen);\n p += seplen;\n }\n }\n\n Py_DECREF(seq);\n return res;\n}\n</code></pre>\n\n<hr>\n\n<p>Note that the above <code>Catenate everything.</code> code is a small part of the whole function.</p>\n\n<p>In pseudocode:</p>\n\n<pre><code>/* Catenate everything. */\nfor each item in sequence\n copy-assign item\n if not last item\n copy-assign separator\n</code></pre>\n"
},
{
"answer_id": 61581,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p><code>join()</code> function in Ruby:</p>\n\n<pre><code>def join(seq, sep) \n seq.inject { |total, item| total << sep << item } or \"\" \nend\n\njoin([\"a\", \"b\", \"c\"], \", \")\n# => \"a, b, c\"\n</code></pre>\n"
},
{
"answer_id": 61623,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 0,
"selected": false,
"text": "<p><code>join()</code> in Perl: </p>\n\n<pre><code>use List::Util qw(reduce);\n\nsub mjoin($@) {$sep = shift; reduce {$a.$sep.$b} @_ or ''}\n\nsay mjoin(', ', qw(Alpha Beta Gamma));\n# Alpha, Beta, Gamma\n</code></pre>\n\n<p>Or without <code>reduce</code>:</p>\n\n<pre><code> sub mjoin($@) \n {\n my ($sep, $sum) = (shift, shift); \n $sum .= $sep.$_ for (@_); \n $sum or ''\n }\n</code></pre>\n"
},
{
"answer_id": 64299,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 0,
"selected": false,
"text": "<h2>Perl 6</h2>\n<pre><code>sub join( $separator, @strings ){\n my $return = shift @strings;\n for @strings -> ( $string ){\n $return ~= $separator ~ $string;\n }\n return $return;\n}\n</code></pre>\n<p><em>Yes I know it is pointless because Perl 6 already has a join function.</em></p>\n"
},
{
"answer_id": 76738,
"author": "Mark B",
"author_id": 13070,
"author_profile": "https://Stackoverflow.com/users/13070",
"pm_score": 0,
"selected": false,
"text": "<p><strong>In Java 5, with unit test:</strong></p>\n\n<pre><code>import junit.framework.Assert;\nimport org.junit.Test;\n\npublic class StringUtil\n{\n public static String join(String delim, String... strings)\n {\n StringBuilder builder = new StringBuilder();\n\n if (strings != null)\n {\n for (String str : strings)\n {\n if (builder.length() > 0)\n {\n builder.append(delim);\n }\n\n builder.append(str);\n }\n } \n\n return builder.toString();\n }\n\n @Test\n public void joinTest()\n {\n Assert.assertEquals(\"\", StringUtil.join(\", \", null));\n Assert.assertEquals(\"\", StringUtil.join(\", \", \"\"));\n Assert.assertEquals(\"\", StringUtil.join(\", \", new String[0]));\n Assert.assertEquals(\"test\", StringUtil.join(\", \", \"test\"));\n Assert.assertEquals(\"foo, bar\", StringUtil.join(\", \", \"foo\", \"bar\"));\n Assert.assertEquals(\"foo, bar, baz\", StringUtil.join(\", \", \"foo\", \"bar\", \"baz\"));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 80475,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote a recursive version of the solution in lisp. If the length of the list is greater that 2 it splits the list in half as best as it can and then tries merging the sublists</p>\n\n<pre><code> (defun concatenate-string(list)\n (cond ((= (length list) 1) (car list))\n ((= (length list) 2) (concatenate 'string (first list) \",\" (second list)))\n (t (let ((mid-point (floor (/ (- (length list) 1) 2))))\n (concatenate 'string \n (concatenate-string (subseq list 0 mid-point))\n \",\"\n (concatenate-string (subseq list mid-point (length list))))))))\n\n\n\n (concatenate-string '(\"a\" \"b\"))\n</code></pre>\n\n<p>I tried applying the divide and conquer strategy to the problem, but I guess that does not give a better result than plain iteration. Please let me know if this could have been done better. </p>\n\n<p>I have also performed an analysis of the recursion obtained by the algorithm, it is available <a href=\"http://www4.ncsu.edu/~rfcornel/analysis.pdf\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 437254,
"author": "blabla999",
"author_id": 48469,
"author_profile": "https://Stackoverflow.com/users/48469",
"pm_score": 1,
"selected": false,
"text": "<p>collecting different language implementations ?\n<br>Here is, for your amusement, a Smalltalk version:</p>\n\n<pre><code>join:collectionOfStrings separatedBy:sep\n\n |buffer|\n\n buffer := WriteStream on:''.\n collectionOfStrings \n do:[:each | buffer nextPutAll:each ]\n separatedBy:[ buffer nextPutAll:sep ].\n ^ buffer contents.\n</code></pre>\n\n<p>Of course, the above code is already in the standard library found as:</p>\n\n<p>Collection >> asStringWith:</p>\n\n<p>so, using that, you'd write:</p>\n\n<pre><code>#('A' 'B' 'C') asStringWith:','\n</code></pre>\n\n<p><strong>But here's my main point</strong>:</p>\n\n<p>I would like to put more emphasis on the fact that using a StringBuilder (or what is called \"WriteStream\" in Smalltalk) is highly recommended. Do not concatenate strings using \"+\" in a loop - the result will be many many intermediate throw-away strings. If you have a good Garbage Collector, thats fine. But some are not and a lot of memory needs to be reclaimed. StringBuilder (and WriteStream, which is its grand-grand-father) use a buffer-doubling or even adaptive growing algorithm, which needs <em>MUCH</em> less scratch memory. </p>\n\n<p>However, if its only a few small strings you are concatenating, dont care, and \"+\" them; the extra work using a StringBuilder might be actually counter-productive, up to an implementation- and language-dependent number of strings.</p>\n"
},
{
"answer_id": 719348,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use the String.join method in C#</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/57a79xd0.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/57a79xd0.aspx</a></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58431",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4991/"
]
| I have wondered for some time, what a nice, clean solution for joining an array of strings might look like.
Example: I have ["Alpha", "Beta", "Gamma"] and want to join the strings into one, separated by commas – "Alpha, Beta, Gamma".
Now I know that most programming languages offer some kind of join method for this. I just wonder how these might be implemented.
When I took introductory courses, I often tried to go it alone, but never found a satisfactory algorithm. Everything seemed rather messy, the problem being that you can not just loop through the array, concatenating the strings, as you would add one too many commas (either before or after the last string).
I don’t want to check conditions in the loop. I don’t really want to add the first or the last string before/after the loop (I guess this is maybe the best way?).
Can someone show me an elegant solution? Or tell me exactly why there can’t be anything more elegant? | The most elegant solution i found for problems like this is something like this (in pseudocode)
```
separator = ""
foreach(item in stringCollection)
{
concatenatedString += separator + item
separator = ","
}
```
You just run the loop and only after the second time around the separator is set. So the first time it won't get added. It's not as clean as I'd like it to be so I'd still add comments but it's better than an if statement or adding the first or last item outside the loop. |
58,457 | <p>How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?</p>
<p>For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight.</p>
| [
{
"answer_id": 58459,
"author": "Dane",
"author_id": 2929,
"author_profile": "https://Stackoverflow.com/users/2929",
"pm_score": 3,
"selected": false,
"text": "<p>You simply need to sum the weights of all candidate rows, then choose a random point within that sum, then select the record that coordinates with that chosen point (each record is incrementally carrying an accumulating weight sum with it).</p>\n\n<pre><code>DECLARE @id int, @weight_sum int, @weight_point int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)\n\nSELECT TOP 1 @id = t1.id\nFROM @table t1, @table t2\nWHERE t1.id >= t2.id\nGROUP BY t1.id\nHAVING SUM(t2.weight) >= @weight_point\nORDER BY t1.id\n\nSELECT @id\n</code></pre>\n"
},
{
"answer_id": 58995,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>The <em>\"incrementally carrying a an accumlating[sic] weight sum\"</em> part is expensive if you have a lot of records. If you also already have a wide range of scores/weights (ie: the range is wide enough that most records weights are unique. 1-5 stars probably wouldn't cut it), you can do something like this to pick a weight value. I'm using VB.Net here to demonstrate, but this could easily be done in pure Sql as well:</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Function PickScore()\n 'Assume we have a database wrapper class instance called SQL and seeded a PRNG already\n 'Get count of scores in database\n Dim ScoreCount As Double = SQL.ExecuteScalar(\"SELECT COUNT(score) FROM [MyTable]\")\n ' You could also approximate this with just the number of records in the table, which might be faster.\n\n 'Random number between 0 and 1 with ScoreCount possible values\n Dim rand As Double = Random.GetNext(ScoreCount) / ScoreCount\n\n 'Use the equation y = 1 - x^3 to skew results in favor of higher scores\n ' For x between 0 and 1, y is also between 0 and 1 with a strong bias towards 1\n rand = 1 - (rand * rand * rand)\n\n 'Now we need to map the (0,1] vector to [1,Maxscore].\n 'Just find MaxScore and mutliply by rand\n Dim MaxScore As UInteger = SQL.ExecuteScalar(\"SELECT MAX(Score) FROM Songs\")\n Return MaxScore * rand\nEnd Function\n</code></pre>\n\n<p>Run this, and pick the record with the largest score less than the returned weight. If more than one record share that score, pick it at random. The advantages here are that you don't have to maintain any sums, and you can tweak the probability equation used to suit your tastes. But again, it works best with a larger distribution of scores.</p>\n"
},
{
"answer_id": 93328,
"author": "ConcernedOfTunbridgeWells",
"author_id": 15401,
"author_profile": "https://Stackoverflow.com/users/15401",
"pm_score": 2,
"selected": false,
"text": "<p>The way to do this with random number generators is to integrate the probabiliity density function. With a set of discrete values you can calculate the prefix sum (sum of all values up to this one) and store it. With this you select the minumum prefix sum (aggregate to date) value greater than the random number. </p>\n\n<p>On a database the subsequent values after an insertion have to be updated. If the relative frequency of updates and size of the data set doesn't make the cost of doing this prohibitive it means that the appropriate value can be obtained in from a single s-argable (predicate that can be resolved by an index lookup) query.</p>\n"
},
{
"answer_id": 454454,
"author": "MatBailie",
"author_id": 53341,
"author_profile": "https://Stackoverflow.com/users/53341",
"pm_score": 5,
"selected": true,
"text": "<p>Dane's answer includes a self joins in a way that introduces a square law. <code>(n*n/2)</code> rows after the join where there are n rows in the table.</p>\n<p>What would be more ideal is to be able to just parse the table once.</p>\n<pre><code>DECLARE @id int, @weight_sum int, @weight_point int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))\n\nSELECT\n @id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END,\n @weight_point = @weight_point - [table].weight\nFROM\n @table [table]\nORDER BY\n [table].Weight DESC\n</code></pre>\n<p>This will go through the table, setting <code>@id</code> to each record's <code>id</code> value while at the same time decrementing <code>@weight</code> point. Eventually, the <code>@weight_point</code> will go negative. This means that the <code>SUM</code> of all preceding weights is greater than the randomly chosen target value. This is the record we want, so from that point onwards we set <code>@id</code> to itself (ignoring any IDs in the table).</p>\n<p>This runs through the table just once, but does have to run through the entire table even if the chosen value is the first record. Because the average position is half way through the table (and less if ordered by ascending weight) writing a loop could possibly be faster... (Especially if the weightings are in common groups):</p>\n<pre><code>DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int\nDECLARE @table TABLE (id int, weight int)\n\nINSERT INTO @table(id, weight) VALUES(1, 50)\nINSERT INTO @table(id, weight) VALUES(2, 25)\nINSERT INTO @table(id, weight) VALUES(3, 25)\n\nSELECT @weight_sum = SUM(weight)\nFROM @table\n\nSELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)\n\nSELECT @next_weight = MAX(weight) FROM @table\nSELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight\nSET @weight_point = @weight_point - (@next_weight * @row_count)\n\nWHILE (@weight_point > 0)\nBEGIN\n SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight\n SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight\n SET @weight_point = @weight_point - (@next_weight * @row_count)\nEND\n\n-- # Once the @weight_point is less than 0, we know that the randomly chosen record\n-- # is in the group of records WHERE [table].weight = @next_weight\n\nSELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))\n\nSELECT\n @id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END,\n @row_count = @row_count - 1\nFROM\n @table [table]\nWHERE\n [table].weight = @next_weight\nORDER BY\n [table].Weight DESC\n</code></pre>\n"
},
{
"answer_id": 51090191,
"author": "Shiroy",
"author_id": 1555435,
"author_profile": "https://Stackoverflow.com/users/1555435",
"pm_score": 2,
"selected": false,
"text": "<p>If you need to do get a group of samples (say, you want to sample 50 rows from a collection of 5M rows) where each row has a column called <code>Weight</code> which is an <code>int</code> and where larger values means more weight, you can use this function:</p>\n\n<pre><code>SELECT * \nFROM \n(\n SELECT TOP 50 RowData, Weight \n FROM MyTable \n ORDER BY POWER(RAND(CAST(NEWID() AS VARBINARY)), (1.0/Weight)) DESC\n) X \nORDER BY Weight DESC\n</code></pre>\n\n<p>The key here is using the POWER( ) function as illustrated <a href=\"https://stackoverflow.com/a/18282419/1555435\">here</a></p>\n\n<p>A reference on the choice of a random function is <a href=\"https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms189108(v=sql.105)\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://technet.microsoft.com/en-us/library/aa175776(v=sql.80).aspx\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Alternatively you can use: </p>\n\n<pre><code>1.0 * ABS(CAST(CHECKSUM(NEWID()) AS bigint)) / CAST(0x7FFFFFFF AS INT) \n</code></pre>\n\n<p>You cast checksum as <code>BIGINT</code> instead of <code>INT</code> because of <a href=\"https://stackoverflow.com/questions/1045138/how-do-i-generate-random-number-for-each-row-in-a-tsql-select\">this</a> issue:</p>\n\n<blockquote>\n <p>Because checksum returns an int, and the range of an int is -2^31\n (-2,147,483,648) to 2^31-1 (2,147,483,647), the abs() function can\n return an overflow error if the result happens to be exactly\n -2,147,483,648! The chances are obviously very low, about 1 in 4 billion, however we were running it over a ~1.8b row table every day,\n so it was happening about once a week! Fix is to cast the checksum to\n bigint before the abs.</p>\n</blockquote>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2929/"
]
| How do you randomly select a table row in T-SQL based on an applied weight for all candidate rows?
For example, I have a set of rows in a table weighted at 50, 25, and 25 (which adds up to 100 but does not need to), and I want to select one of them randomly with a statistical outcome equivalent to the respective weight. | Dane's answer includes a self joins in a way that introduces a square law. `(n*n/2)` rows after the join where there are n rows in the table.
What would be more ideal is to be able to just parse the table once.
```
DECLARE @id int, @weight_sum int, @weight_point int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = FLOOR(((@weight_sum - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @weight_point < 0 THEN @id ELSE [table].id END,
@weight_point = @weight_point - [table].weight
FROM
@table [table]
ORDER BY
[table].Weight DESC
```
This will go through the table, setting `@id` to each record's `id` value while at the same time decrementing `@weight` point. Eventually, the `@weight_point` will go negative. This means that the `SUM` of all preceding weights is greater than the randomly chosen target value. This is the record we want, so from that point onwards we set `@id` to itself (ignoring any IDs in the table).
This runs through the table just once, but does have to run through the entire table even if the chosen value is the first record. Because the average position is half way through the table (and less if ordered by ascending weight) writing a loop could possibly be faster... (Especially if the weightings are in common groups):
```
DECLARE @id int, @weight_sum int, @weight_point int, @next_weight int, @row_count int
DECLARE @table TABLE (id int, weight int)
INSERT INTO @table(id, weight) VALUES(1, 50)
INSERT INTO @table(id, weight) VALUES(2, 25)
INSERT INTO @table(id, weight) VALUES(3, 25)
SELECT @weight_sum = SUM(weight)
FROM @table
SELECT @weight_point = ROUND(((@weight_sum - 1) * RAND() + 1), 0)
SELECT @next_weight = MAX(weight) FROM @table
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
WHILE (@weight_point > 0)
BEGIN
SELECT @next_weight = MAX(weight) FROM @table WHERE weight < @next_weight
SELECT @row_count = COUNT(*) FROM @table WHERE weight = @next_weight
SET @weight_point = @weight_point - (@next_weight * @row_count)
END
-- # Once the @weight_point is less than 0, we know that the randomly chosen record
-- # is in the group of records WHERE [table].weight = @next_weight
SELECT @row_count = FLOOR(((@row_count - 1) * RAND() + 1))
SELECT
@id = CASE WHEN @row_count < 0 THEN @id ELSE [table].id END,
@row_count = @row_count - 1
FROM
@table [table]
WHERE
[table].weight = @next_weight
ORDER BY
[table].Weight DESC
``` |
58,482 | <p>I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:</p>
<pre><code>foo = ["goo", "baz"]
</code></pre>
<p>How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?</p>
<p>Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:</p>
<pre><code> [foo, goo, bar].each { |param|
if param.class != Array
puts "param_name wasn't an Array. It was a/an #{param.class}"
return "Error: param_name wasn't an Array"
end
}
</code></pre>
<p>My question is then: Can I replace the instances of 'param_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala <a href="https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870">dbr's answer</a>) </p>
| [
{
"answer_id": 58492,
"author": "Josh Moore",
"author_id": 5004,
"author_profile": "https://Stackoverflow.com/users/5004",
"pm_score": 2,
"selected": false,
"text": "<p>I do not know of any way to get a local variable name. But, you can use the <code>instance_variables</code> method, this will return an array of all the instance variable names in the object. </p>\n\n<p>Simple call:</p>\n\n<pre><code>object.instance_variables\n</code></pre>\n\n<p>or</p>\n\n<pre><code>self.instance_variables\n</code></pre>\n\n<p>to get an array of all instance variable names.</p>\n"
},
{
"answer_id": 58734,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "<p>Building on <a href=\"https://stackoverflow.com/users/5004/joshsmooremyopenidcom\">joshmsmoore</a>, something like this would probably do it:</p>\n\n<pre><code># Returns the first instance variable whose value == x\n# Returns nil if no name maps to the given value\ndef instance_variable_name_for(x)\n self.instance_variables.find do |var|\n x == self.instance_variable_get(var)\n end\nend\n</code></pre>\n"
},
{
"answer_id": 58765,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 2,
"selected": false,
"text": "<p>There's <code>Kernel::local_variables</code>, but I'm not sure that this will work for a method's local vars, and I don't know that you can manipulate it in such a way as to do what you wish to acheive.</p>\n"
},
{
"answer_id": 58830,
"author": "Brian Warshaw",
"author_id": 1344,
"author_profile": "https://Stackoverflow.com/users/1344",
"pm_score": 3,
"selected": false,
"text": "<p>OK, it DOES work in instance methods, too, and, based on your specific requirement (the one you put in the comment), you could do this:</p>\n\n<pre><code>local_variables.each do |var|\n puts var if (eval(var).class != Fixnum)\nend\n</code></pre>\n\n<p>Just replace <code>Fixnum</code> with your specific type checking.</p>\n"
},
{
"answer_id": 58870,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 3,
"selected": false,
"text": "<p>It seems you are trying to solve a problem that has a far easier solution..</p>\n\n<p>Why not just store the data in a hash? If you do..</p>\n\n<pre><code>data_container = {'foo' => ['goo', 'baz']}\n</code></pre>\n\n<p>..it is then utterly trivial to get the 'foo' name.</p>\n\n<p>That said, you've not given any context to the problem, so there may be a reason you can't do this..</p>\n\n<p><em>[edit]</em> After clarification, I see the issue, but I don't think this is the problem.. With [foo, bar, bla], it's equivalent like saying <code>['content 1', 'content 2', 'etc']</code>. The actual variables name is (or rather, should be) utterly irrelevant. If the name of the variable is important, that is exactly why hashes exist.</p>\n\n<p>The problem isn't with iterating over [foo, bar] etc, it's the fundamental problem with how the SOAP server is returing the data, and/or how you're trying to use it.</p>\n\n<p>The solution, I would say, is to either make the SOAP server return hashes, or, since you know there is always going to be three elements, can you not do something like..</p>\n\n<pre><code>{\"foo\" => foo, \"goo\" => goo, \"bar\"=>bar}.each do |param_name, param|\n if param.class != Array\n puts \"#{param_name} wasn't an Array. It was a/an #{param.class}\"\n puts \"Error: #{param_name} wasn't an Array\"\n end\nend\n</code></pre>\n"
},
{
"answer_id": 59259,
"author": "pauliephonic",
"author_id": 5374,
"author_profile": "https://Stackoverflow.com/users/5374",
"pm_score": 1,
"selected": false,
"text": "<p>You can't, you need to go back to the drawing board and re-engineer your solution.</p>\n"
},
{
"answer_id": 61729,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 5,
"selected": false,
"text": "<p>You need to re-architect your solution. Even if you <em>could</em> do it (you can't), the question simply doesn't have a reasonable answer.</p>\n\n<p>Imagine a get_name method.</p>\n\n<pre><code>a = 1\nget_name(a)\n</code></pre>\n\n<p>Everyone could probably agree this should return 'a'</p>\n\n<pre><code>b = a\nget_name(b)\n</code></pre>\n\n<p>Should it return 'b', or 'a', or an array containing both?</p>\n\n<pre><code>[b,a].each do |arg|\n get_name(arg)\nend\n</code></pre>\n\n<p>Should it return 'arg', 'b', or 'a' ?</p>\n\n<pre><code>def do_stuff( arg )\n get_name(arg)\ndo\ndo_stuff(b)\n</code></pre>\n\n<p>Should it return 'arg', 'b', or 'a', or maybe the array of all of them? Even if it did return an array, what would the order be and how would I know how to interpret the results?</p>\n\n<p>The answer to all of the questions above is \"It depends on the particular thing I want at the time.\" I'm not sure how you could solve that problem for Ruby.</p>\n"
},
{
"answer_id": 63523,
"author": "glenn mcdonald",
"author_id": 7919,
"author_profile": "https://Stackoverflow.com/users/7919",
"pm_score": 6,
"selected": true,
"text": "<p>What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:</p>\n\n<pre><code>[\"foo\", \"goo\", \"bar\"].each { |param_name|\n param = eval(param_name)\n if param.class != Array\n puts \"#{param_name} wasn't an Array. It was a/an #{param.class}\"\n return \"Error: #{param_name} wasn't an Array\"\n end\n }\n</code></pre>\n\n<p>If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add \"rescue nil\" to the end of the \"param = ...\" line to keep the eval from throwing an exception...</p>\n"
},
{
"answer_id": 66517,
"author": "Michael Latta",
"author_id": 9679,
"author_profile": "https://Stackoverflow.com/users/9679",
"pm_score": 1,
"selected": false,
"text": "<p>Foo is only a location to hold a pointer to the data. The data has no knowledge of what points at it. In Smalltalk systems you could ask the VM for all pointers to an object, but that would only get you the object that contained the foo variable, not foo itself. There is no real way to reference a vaiable in Ruby. As mentioned by one answer you can stil place a tag in the data that references where it came from or such, but generally that is not a good apporach to most problems. You can use a hash to receive the values in the first place, or use a hash to pass to your loop so you know the argument name for validation purposes as in DBR's answer.</p>\n"
},
{
"answer_id": 67910,
"author": "Greg Borenstein",
"author_id": 10419,
"author_profile": "https://Stackoverflow.com/users/10419",
"pm_score": 1,
"selected": false,
"text": "<p>The closest thing to a real answer to you question is to use the Enumerable method each_with_index instead of each, thusly:</p>\n\n<pre><code>my_array = [foo, baz, bar]\nmy_array.each_with_index do |item, index|\n if item.class != Array\n puts \"#{my_array[index]} wasn't an Array. It was a/an #{item.class}\"\n end\nend\n</code></pre>\n\n<p>I removed the return statement from the block you were passing to each/each_with_index because it didn't do/mean anything. Each and each_with_index both return the array on which they were operating.</p>\n\n<p>There's also something about scope in blocks worth noting here: if you've defined a variable outside of the block, it will be available within it. In other words, you could refer to foo, bar, and baz directly inside the block. The converse is not true: variables that you create for the first time inside the block will not be available outside of it.</p>\n\n<p>Finally, the do/end syntax is preferred for multi-line blocks, but that's simply a matter of style, though it is universal in ruby code of any recent vintage.</p>\n"
},
{
"answer_id": 17029573,
"author": "Boris Stitnicky",
"author_id": 1153747,
"author_profile": "https://Stackoverflow.com/users/1153747",
"pm_score": 2,
"selected": false,
"text": "<p>Great question. I fully understand your motivation. Let me start by noting, that there are certain kinds of special objects, that, under certain circumstances, have knowledge of the variable, to which they have been assigned. These special objects are eg. <code>Module</code> instances, <code>Class</code> instances and <code>Struct</code> instances:</p>\n\n<pre><code>Dog = Class.new\nDog.name # Dog\n</code></pre>\n\n<p>The catch is, that this works only when the variable, to which the assignment is performed, is a constant. (We all know that Ruby constants are nothing more than emotionally sensitive variables.) Thus:</p>\n\n<pre><code>x = Module.new # creating an anonymous module\nx.name #=> nil # the module does not know that it has been assigned to x\nAnimal = x # but will notice once we assign it to a constant\nx.name #=> \"Animal\"\n</code></pre>\n\n<p>This behavior of objects being aware to which variables they have been assigned, is commonly called <em>constant magic</em> (because it is limited to constants). But this highly desirable <em>constant magic</em> only works for certain objects:</p>\n\n<pre><code>Rover = Dog.new\nRover.name #=> raises NoMethodError\n</code></pre>\n\n<p>Fortunately, <a href=\"https://github.com/boris-s/y_support\" rel=\"nofollow\">I have written a gem <code>y_support/name_magic</code></a>, that takes care of this for you:</p>\n\n<pre><code> # first, gem install y_support\nrequire 'y_support/name_magic'\n\nclass Cat\n include NameMagic\nend\n</code></pre>\n\n<p>The fact, that this only works with constants (ie. variables starting with a capital letter) is not such a big limitation. In fact, it gives you freedom to name or not to name your objects at will:</p>\n\n<pre><code>tmp = Cat.new # nameless kitty\ntmp.name #=> nil\nJosie = tmp # by assigning to a constant, we name the kitty Josie\ntmp.name #=> :Josie\n</code></pre>\n\n<p>Unfortunately, this will not work with array literals, because they are internally constructed without using <code>#new</code> method, on which <code>NameMagic</code> relies. Therefore, to achieve what you want to, you will have to subclass <code>Array</code>:</p>\n\n<pre><code>require 'y_support/name_magic'\nclass MyArr < Array\n include NameMagic\nend\n\nfoo = MyArr.new [\"goo\", \"baz\"] # not named yet\nfoo.name #=> nil\nFoo = foo # but assignment to a constant is noticed\nfoo.name #=> :Foo\n\n# You can even list the instances\nMyArr.instances #=> [[\"goo\", \"baz\"]]\nMyArr.instance_names #=> [:Foo]\n\n# Get an instance by name:\nMyArr.instance \"Foo\" #=> [\"goo\", \"baz\"]\nMyArr.instance :Foo #=> [\"goo\", \"baz\"]\n\n# Rename it:\nFoo.name = \"Quux\"\nFoo.name #=> :Quux\n\n# Or forget the name again:\nMyArr.forget :Quux\nFoo.name #=> nil\n\n# In addition, you can name the object upon creation even without assignment\nu = MyArr.new [1, 2], name: :Pair\nu.name #=> :Pair\nv = MyArr.new [1, 2, 3], ɴ: :Trinity\nv.name #=> :Trinity\n</code></pre>\n\n<p>I achieved the constant magic-imitating behavior by <em>searching all the constants in all the namespaces</em> of the current Ruby object space. This wastes a fraction of second, but since the search is performed only once, there is no performance penalty once the object figures out its name. In the future, Ruby core team <a href=\"http://bugs.ruby-lang.org/issues/7149\" rel=\"nofollow\">has promised <code>const_assigned</code> hook</a>.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
]
| I'm not entirely sure if this is possible in Ruby, but hopefully there's an easy way to do this. I want to declare a variable and later find out the name of the variable. That is, for this simple snippet:
```
foo = ["goo", "baz"]
```
How can I get the name of the array (here, "foo") back? If it is indeed possible, does this work on any variable (e.g., scalars, hashes, etc.)?
Edit: Here's what I'm basically trying to do. I'm writing a SOAP server that wraps around a class with three important variables, and the validation code is essentially this:
```
[foo, goo, bar].each { |param|
if param.class != Array
puts "param_name wasn't an Array. It was a/an #{param.class}"
return "Error: param_name wasn't an Array"
end
}
```
My question is then: Can I replace the instances of 'param\_name' with foo, goo, or bar? These objects are all Arrays, so the answers I've received so far don't seem to work (with the exception of re-engineering the whole thing ala [dbr's answer](https://stackoverflow.com/questions/58482/ruby-get-a-variables-name#58870)) | What if you turn your problem around? Instead of trying to get names from variables, get the variables from the names:
```
["foo", "goo", "bar"].each { |param_name|
param = eval(param_name)
if param.class != Array
puts "#{param_name} wasn't an Array. It was a/an #{param.class}"
return "Error: #{param_name} wasn't an Array"
end
}
```
If there were a chance of one the variables not being defined at all (as opposed to not being an array), you would want to add "rescue nil" to the end of the "param = ..." line to keep the eval from throwing an exception... |
58,513 | <p>How do I Unit Test a MVC redirection?</p>
<pre><code>public ActionResult Create(Product product)
{
_productTask.Save(product);
return RedirectToAction("Success");
}
public ActionResult Success()
{
return View();
}
</code></pre>
<p>Is <a href="http://www.ayende.com/Blog/archive/2007/12/13/Dont-like-visibility-levels-change-that.aspx" rel="nofollow noreferrer">Ayende's</a> approach still the best way to go, with preview 5:</p>
<pre><code> public static void RenderView(this Controller self, string action)
{
typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} );
}
</code></pre>
<p>Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable.</p>
| [
{
"answer_id": 58789,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You can assert on the ActionResult that is returned, you'll need to cast it to the appropriate type but it does allow you to use state-based testing. A search on the Web should find some useful links, here's <a href=\"http://sebastienlachance.com/2008/05/06/testing-controllers-in-aspnet-mvc-aka-actionresult/\" rel=\"nofollow noreferrer\">just one</a> though.</p>\n"
},
{
"answer_id": 58818,
"author": "Matt Hinze",
"author_id": 2676,
"author_profile": "https://Stackoverflow.com/users/2676",
"pm_score": 6,
"selected": true,
"text": "<pre><code>[TestFixture]\npublic class RedirectTester\n{\n [Test]\n public void Should_redirect_to_success_action()\n {\n var controller = new RedirectController();\n var result = controller.Index() as RedirectToRouteResult;\n Assert.That(result, Is.Not.Null);\n Assert.That(result.Values[\"action\"], Is.EqualTo(\"success\"));\n }\n}\n\npublic class RedirectController : Controller\n{\n public ActionResult Index()\n {\n return RedirectToAction(\"success\");\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3057516,
"author": "hurbata",
"author_id": 368725,
"author_profile": "https://Stackoverflow.com/users/368725",
"pm_score": -1,
"selected": false,
"text": "<p>you can use Mvc.Contrib.TestHelper which provides assertions for testing redirections. Take a look at <a href=\"http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html\" rel=\"nofollow noreferrer\">http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html</a> and the code sample. It might be helpful. </p>\n"
},
{
"answer_id": 35017463,
"author": "Kevin O'Shaughnessy",
"author_id": 4253016,
"author_profile": "https://Stackoverflow.com/users/4253016",
"pm_score": 0,
"selected": false,
"text": "<p>This works for ASP.NET MVC 5 using NUnit:</p>\n\n<pre><code> [Test]\n public void ShouldRedirectToSuccessAction()\n {\n var controller = new RedirectController();\n var result = controller.Index() as RedirectToRouteResult;\n\n Assert.That(result.RouteValues[\"action\"], Is.EqualTo(\"success\"));\n }\n</code></pre>\n\n<p>If you want to test that you are redirecting to a different controller (say NewController), the assertion would be:</p>\n\n<pre><code>Assert.That(result.RouteValues[\"controller\"], Is.EqualTo(\"New\"));\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58513",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
]
| How do I Unit Test a MVC redirection?
```
public ActionResult Create(Product product)
{
_productTask.Save(product);
return RedirectToAction("Success");
}
public ActionResult Success()
{
return View();
}
```
Is [Ayende's](http://www.ayende.com/Blog/archive/2007/12/13/Dont-like-visibility-levels-change-that.aspx) approach still the best way to go, with preview 5:
```
public static void RenderView(this Controller self, string action)
{
typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} );
}
```
Seems odd to have to do this, especially as the MVC team have said they are writing the framework to be testable. | ```
[TestFixture]
public class RedirectTester
{
[Test]
public void Should_redirect_to_success_action()
{
var controller = new RedirectController();
var result = controller.Index() as RedirectToRouteResult;
Assert.That(result, Is.Not.Null);
Assert.That(result.Values["action"], Is.EqualTo("success"));
}
}
public class RedirectController : Controller
{
public ActionResult Index()
{
return RedirectToAction("success");
}
}
``` |
58,517 | <p>Is there a way to combine Enums in VB.net?</p>
| [
{
"answer_id": 58524,
"author": "Hath",
"author_id": 5186,
"author_profile": "https://Stackoverflow.com/users/5186",
"pm_score": 0,
"selected": false,
"text": "<p>If you taking about using enum flags() there is a good article <a href=\"http://www.codeguru.com/vb/sample_chapter/article.php/c12963\" rel=\"nofollow noreferrer\" title=\"VB flags\">here</a>.</p>\n"
},
{
"answer_id": 58525,
"author": "Mendelt",
"author_id": 3320,
"author_profile": "https://Stackoverflow.com/users/3320",
"pm_score": 1,
"selected": false,
"text": "<p>If I understand your question correctly you want to combine different enum types. So one variable can store a value from one of two different enum's right? If you're asking about storing combining two different values of one enum type you can look at Dave Arkell's explanation</p>\n\n<p>Enums are just integers with some syntactic sugar. So if you make sure there's no overlap you can combine them by casting to int.</p>\n\n<p>It won't make for pretty code though. I try to avoid using enums most of the time. Usually if you let enums breed in your code it's just a matter of time before they give birth to repeated case statements and other messy antipatterns.</p>\n"
},
{
"answer_id": 58526,
"author": "Jonas Follesø",
"author_id": 1199387,
"author_profile": "https://Stackoverflow.com/users/1199387",
"pm_score": 1,
"selected": false,
"text": "<p>The key to combination <code>Enum</code>s is to make sure that the value is a power of two (1, 2, 4, 8, etc.) so that you can perform bit operations on them (<code>|=</code> <code>&=</code>). Those <code>Enum</code>s can be be tagged with a <code>Flags</code> attribute. The <code>Anchor</code> property on Windows Forms controls is an example of such a control. If it's marked as a flag, Visual Studio will let you check values instead of selecting a single one in a drop-down in the properties designer.</p>\n"
},
{
"answer_id": 58527,
"author": "Dave Arkell",
"author_id": 4002,
"author_profile": "https://Stackoverflow.com/users/4002",
"pm_score": 7,
"selected": true,
"text": "<p>I believe what you want is a flag type enum.</p>\n<p>You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword.</p>\n<p>Like this:</p>\n<pre><code><Flags()> _\nEnum CombinationEnums As Integer\n HasButton = 1\n TitleBar = 2\n [ReadOnly] = 4\n ETC = 8\nEnd Enum\n</code></pre>\n<p><strong>Note:</strong> The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set.</p>\n<p>Combine the desired flags using the Or keyword:</p>\n<pre><code>Dim settings As CombinationEnums\nsettings = CombinationEnums.TitleBar Or CombinationEnums.Readonly\n</code></pre>\n<p>This sets TitleBar and Readonly into the enum</p>\n<p>To check what's been set:</p>\n<pre><code>If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then\n Window.TitleBar = True\nEnd If\n</code></pre>\n"
},
{
"answer_id": 58535,
"author": "Tyler",
"author_id": 5642,
"author_profile": "https://Stackoverflow.com/users/5642",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the FlagsAttribute to decorate an Enum like so which will let you combine the Enum:</p>\n\n<pre><code><FlagsAttribute> _\nPublic Enumeration SecurityRights\nNone = 0\nRead = 1\nWrite = 2\nExecute = 4\n</code></pre>\n\n<p>And then call them like so (class UserPriviltes):</p>\n\n<pre><code>Public Sub New ( _\n options As SecurityRights _\n)\n\nNew UserPrivileges(SecurityRights.Read OR SecurityRights.Execute)\n</code></pre>\n\n<p>They effectively get combined (bit math) so that the above user has both Read AND Execute all carried around in one fancy SecurityRights variable.</p>\n\n<p>To check to see if the user has a privilege you use AND (more bitwise math) to check the users enum value with the the Enum value you're checking for:</p>\n\n<pre><code>//Check to see if user has Write rights\nIf (user.Privileges And SecurityRights.Write = SecurityRigths.Write) Then\n //Do something clever...\nElse\n //Tell user he can't write.\nEnd If\n</code></pre>\n\n<p>HTH,\nTyler</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58517",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5055/"
]
| Is there a way to combine Enums in VB.net? | I believe what you want is a flag type enum.
You need to add the Flags attribute to the top of the enum, and then you can combine enums with the 'Or' keyword.
Like this:
```
<Flags()> _
Enum CombinationEnums As Integer
HasButton = 1
TitleBar = 2
[ReadOnly] = 4
ETC = 8
End Enum
```
**Note:** The numbers to the right are always twice as big (powers of 2) - this is needed to be able to separate the individual flags that have been set.
Combine the desired flags using the Or keyword:
```
Dim settings As CombinationEnums
settings = CombinationEnums.TitleBar Or CombinationEnums.Readonly
```
This sets TitleBar and Readonly into the enum
To check what's been set:
```
If (settings And CombinationEnums.TitleBar) = CombinationEnums.TitleBar Then
Window.TitleBar = True
End If
``` |
58,538 | <p>I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.</p>
<p>Does anyone know the best way to do this using the WiX framework.</p>
| [
{
"answer_id": 58686,
"author": "Paul Lalonde",
"author_id": 5782,
"author_profile": "https://Stackoverflow.com/users/5782",
"pm_score": 7,
"selected": true,
"text": "<p>Wix has out-of-the-box support for creating event log sources.</p>\n\n<p>Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :</p>\n\n<pre><code><Wix xmlns=\"http://schemas.microsoft.com/wix/2006/wi\"\n xmlns:util=\"http://schemas.microsoft.com/wix/UtilExtension\">\n\n <Component ...>\n ...\n <util:EventSource Log=\"Application\" Name=\"*source name*\"\n EventMessageFile=\"*path to message file*\"/>\n ...\n </Component>\n</code></pre>\n\n<p>If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.</p>\n"
},
{
"answer_id": 574055,
"author": "Gordon",
"author_id": 69455,
"author_profile": "https://Stackoverflow.com/users/69455",
"pm_score": 4,
"selected": false,
"text": "<p>Just to save people some time - if you are trying to use the Application log and the .NET messages you can cut paste the below code:</p>\n\n<pre><code><Util:EventSource\n xmlns:Util=\"http://schemas.microsoft.com/wix/UtilExtension\"\n Name=\"ROOT Builder\"\n Log=\"Application\"\n EventMessageFile=\"%SystemRoot%\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll\"\n/>\n</code></pre>\n\n<p>NOTE: the path above is now correct..</p>\n"
},
{
"answer_id": 5029747,
"author": "Daniel Fisher lennybacon",
"author_id": 12679,
"author_profile": "https://Stackoverflow.com/users/12679",
"pm_score": 4,
"selected": false,
"text": "<p>How about the more flexible stuff built in:</p>\n\n<pre><code>EventMessageFile=\"[NETFRAMEWORK20INSTALLROOTDIR]EventLogMessages.dll\"\n</code></pre>\n\n<p>or</p>\n\n<pre><code>EventMessageFile=\"[NETFRAMEWORK40FULLINSTALLROOTDIR]EventLogMessages.dll\"\n</code></pre>\n\n<p>And </p>\n\n<pre><code>EventMessageFile=\"[NETFRAMEWORK40FULLINSTALLROOTDIR64]EventLogMessages.dll\"\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5182/"
]
| I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.
Does anyone know the best way to do this using the WiX framework. | Wix has out-of-the-box support for creating event log sources.
Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :
```
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
<Component ...>
...
<util:EventSource Log="Application" Name="*source name*"
EventMessageFile="*path to message file*"/>
...
</Component>
```
If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file. |
58,540 | <p>When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:</p>
<blockquote>
<p>Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.<br>
ADDITIONAL INFORMATION:<br>
Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle) </p>
</blockquote>
<p>I have tried following the suggestion here but don't quite understand what is required:<a href="http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html" rel="noreferrer">Parameterized queries against Oracle</a></p>
<p>Any ideas?</p>
| [
{
"answer_id": 59116,
"author": "Rich Lawrence",
"author_id": 1281,
"author_profile": "https://Stackoverflow.com/users/1281",
"pm_score": 5,
"selected": true,
"text": "<p>To expand on the link given in the question:</p>\n\n<ol>\n<li>Create a package variable</li>\n<li>Double click on the package variable name. (This allows you to access the properties of the variable)</li>\n<li>Set the property 'EvaluateAsExpression' to true</li>\n<li>Enter the query in the expression builder.</li>\n<li>Set the OLE DB source query to SQL Command from Variable</li>\n</ol>\n\n<p>The expression builder can dynamically create expressions using variable to create 'parametised queries'.<br>\nSo the following 'normal' query:</p>\n\n<pre><code>select * from book where book.BOOK_ID = ?\n</code></pre>\n\n<p>Can be written in the expression builder as:</p>\n\n<pre><code>\"select * from book where book.BOOK_ID = \" + @[User::BookID]\n</code></pre>\n\n<p>You can then do null handling and data conversion using the expression builder.</p>\n"
},
{
"answer_id": 51440458,
"author": "toha",
"author_id": 1084742,
"author_profile": "https://Stackoverflow.com/users/1084742",
"pm_score": 1,
"selected": false,
"text": "<p>If You use Data Flow Task and use OLE DB Source, and you need parameterize your Query : </p>\n\n<ol>\n<li>Create Variable to save \"Full\" of Query statement : Right Click on blank area outside the package - and Click Variables : </li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/yLvNJ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/yLvNJ.jpg\" alt=\"Variables\"></a></p>\n\n<p>Click Add Variables on Variables Window : </p>\n\n<p><a href=\"https://i.stack.imgur.com/AgX1w.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AgX1w.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>Make the name is <code>SQL_DTFLOW_FULL</code> or something that can you understand easily. The <code>variable data type</code> is <code>STRING</code></p>\n\n<ol start=\"2\">\n<li>Create Variable(s) to save your parameter(s). </li>\n</ol>\n\n<p>i.e, the full of Query stamements is : </p>\n\n<pre><code>SELECT * FROM BOOK WHERE BOOK_ID = @BookID --@BookID is SQL Parameter\n</code></pre>\n\n<p>at the sample above, I have just one parameter : @BookID, so I need to create one variable to save my parameter. Add more variables depends on your Queries. </p>\n\n<p><a href=\"https://i.stack.imgur.com/M4siL.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/M4siL.jpg\" alt=\"ParamAdd\"></a></p>\n\n<p>Give it name <code>SQL_DTFLOW_BOOKID</code></p>\n\n<p>The <code>variable data type</code> is <code>STRING</code></p>\n\n<p>So, you need make your SSIS neat, and the variables is sorted in understandable parts.</p>\n\n<p>Try to make the variable name is <code>SQL_{TASK NAME}_{VariableName}</code></p>\n\n<ol start=\"3\">\n<li>Make Expression for <code>SQL_DTFLOW_FULL</code> variable, click on number 1, and start fill number 2. Make Your SQL Statements to be a correct SQL Statement using string block. String block usually using \"Double Quote\" at the beginning and the end. Concat the variables with the string block.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/5UEVk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5UEVk.jpg\" alt=\"Expression\"></a></p>\n\n<p>Click evaluate Expression, to showing result, to make sure your query is correct, copy-paste the Query result at SSMS. </p>\n\n<p>Make sure by yourself that the variables is free from SQL Injection using your own logic. (Use your developer instinct)</p>\n\n<ol start=\"4\">\n<li>Open the Data Flow Task, open the OLE DB Source Editor by double click the item.</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/Vb3tM.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Vb3tM.jpg\" alt=\"Data Flow\"></a></p>\n\n<ul>\n<li>Select the Data Access Mode : <code>SQL Command From Variable</code></li>\n<li>Select the Variable Name : <code>SQL_DTFLOW_FULL</code></li>\n<li>Click Preview to make sure it works.</li>\n</ul>\n\n<p>That is all, my way to prevent this SSIS failure case. Since I use this way, I never got that problem, you know, SSIS something is weird.</p>\n\n<p>To change the variable value, set it before Data Flow Task, the SQL Result of <code>SQL_DTFLOW_FULL</code> variable will changed every you change your variable value. </p>\n"
},
{
"answer_id": 52480280,
"author": "PanLondon",
"author_id": 8517285,
"author_profile": "https://Stackoverflow.com/users/8517285",
"pm_score": 1,
"selected": false,
"text": "<p>In my case the issue was that i had comments within the sql in the normal form of /* */ and i also had column aliases as \"Column name\" instead of [Column Name]. </p>\n\n<p>Once i removed them it works. </p>\n\n<p>Also try to have your parameter ? statement within the WHERE clause and not within the JOINS, that was part of the issue too.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1281/"
]
| When trying to enter a SQL query with parameters using the Oracle OLE DB provider I get the following error:
>
> Parameters cannot be extracted from the SQL command. The provider might not help to parse parameter information from the command. In that case, use the "SQL command from variable" access mode, in which the entire SQL command is stored in a variable.
>
> ADDITIONAL INFORMATION:
>
> Provider cannot derive parameter information and SetParameterInfo has not been called. (Microsoft OLE DB Provider for Oracle)
>
>
>
I have tried following the suggestion here but don't quite understand what is required:[Parameterized queries against Oracle](http://microsoftdw.blogspot.com/2005/11/parameterized-queries-against-oracle.html)
Any ideas? | To expand on the link given in the question:
1. Create a package variable
2. Double click on the package variable name. (This allows you to access the properties of the variable)
3. Set the property 'EvaluateAsExpression' to true
4. Enter the query in the expression builder.
5. Set the OLE DB source query to SQL Command from Variable
The expression builder can dynamically create expressions using variable to create 'parametised queries'.
So the following 'normal' query:
```
select * from book where book.BOOK_ID = ?
```
Can be written in the expression builder as:
```
"select * from book where book.BOOK_ID = " + @[User::BookID]
```
You can then do null handling and data conversion using the expression builder. |
58,543 | <p>I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <code><iframe></code>.</p>
<p>Easy: just set <code>height</code> and <code>width</code> to <code>100%</code>! Except, it doesn't work.</p>
<p>I did find out about setting <code>frameborder</code> to <code>0</code>, so it at least <em>looks</em> like part of the site, but I'd prefer not to have an ugly scrollbar <em>inside</em> a page that allready has one.</p>
<p>Do you know of any tricks to do this?</p>
<p><strong>EDIT:</strong> I think I need to clarify my question somewhat:</p>
<ul>
<li>the company CMS displays the fluff and stuff for our whole website</li>
<li>most pages created through the CMS</li>
<li>my application isn't, but they will let me embedd it in an <code><iframe></code></li>
<li>I have no control over the <code>iframe</code>, so any solution must work from the referenced page (according to the <code>src</code> attribute of the <code>iframe</code> tag)</li>
<li>the CMS displays a footer, so setting the height to 1 million pixels is not a good idea</li>
</ul>
<p>Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...</p>
<p>This technique seems to work (<a href="http://bytes.com/forum/thread91876.html" rel="noreferrer">gleaned</a> from several sources, but inspired by the <a href="http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe" rel="noreferrer">link</a> from the accepted answer:</p>
<p>In parent document:</p>
<pre><code><iframe id="MyIFRAME" name="MyIFRAME"
src="http://localhost/child.html"
scrolling="auto" width="100%" frameborder="0">
no iframes supported...
</iframe>
</code></pre>
<p>In child:</p>
<pre><code><!-- ... -->
<body>
<script type="text/javascript">
function resizeIframe() {
var docHeight;
if (typeof document.height != 'undefined') {
docHeight = document.height;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
docHeight = document.documentElement.scrollHeight;
}
else if (document.body
&& typeof document.body.scrollHeight != 'undefined') {
docHeight = document.body.scrollHeight;
}
// magic number: suppress generation of scrollbars...
docHeight += 20;
parent.document.getElementById('MyIFRAME').style.height = docHeight + "px";
}
parent.document.getElementById('MyIFRAME').onload = resizeIframe;
parent.window.onresize = resizeIframe;
</script>
</body>
</code></pre>
<p><strong>BTW:</strong> This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...</p>
| [
{
"answer_id": 58553,
"author": "ralfe",
"author_id": 340241,
"author_profile": "https://Stackoverflow.com/users/340241",
"pm_score": 3,
"selected": true,
"text": "<p>You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods:</p>\n\n<p><a href=\"http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe\" rel=\"nofollow noreferrer\">http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe</a>\n<a href=\"http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html\" rel=\"nofollow noreferrer\">http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html</a></p>\n"
},
{
"answer_id": 58562,
"author": "Adam Hepton",
"author_id": 2268,
"author_profile": "https://Stackoverflow.com/users/2268",
"pm_score": 0,
"selected": false,
"text": "<p>I might be missing something here, but adding <code>scrolling=no</code> as an attribute to the <code>iframe</code> tag normally gets rid of the scrollbars.</p>\n"
},
{
"answer_id": 58582,
"author": "ConroyP",
"author_id": 2287,
"author_profile": "https://Stackoverflow.com/users/2287",
"pm_score": 2,
"selected": false,
"text": "<p>Provided that your iframe is hosted on the same server as the containing page, you can <a href=\"http://www.esqsoft.com/javascript_examples/iframe_talks_to_parent/\" rel=\"nofollow noreferrer\">access it via javascript</a>.</p>\n\n<p>There are a number of suggested methods for <a href=\"http://www.programmersheaven.com/2/FAQ-JavaScript-Set-Iframe-Width-Height-Onload\" rel=\"nofollow noreferrer\">setting the iframe to the full height of the contents</a>, each with varying degrees of success - a google for this problem shows that it's quite a common one, with no real, one-size-fits-all consensus solution i'm afraid!</p>\n\n<p>Several people have reported that <a href=\"http://www.dynamicdrive.com/dynamicindex17/iframessi2.htm\" rel=\"nofollow noreferrer\">this script</a> does the trick, but may need <a href=\"http://www.daniweb.com/forums/post258858-4.html\" rel=\"nofollow noreferrer\">some modification</a> for your specific case (again, assuming your iframe and parent page are on the same domain).</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2260/"
]
| I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an `<iframe>`.
Easy: just set `height` and `width` to `100%`! Except, it doesn't work.
I did find out about setting `frameborder` to `0`, so it at least *looks* like part of the site, but I'd prefer not to have an ugly scrollbar *inside* a page that allready has one.
Do you know of any tricks to do this?
**EDIT:** I think I need to clarify my question somewhat:
* the company CMS displays the fluff and stuff for our whole website
* most pages created through the CMS
* my application isn't, but they will let me embedd it in an `<iframe>`
* I have no control over the `iframe`, so any solution must work from the referenced page (according to the `src` attribute of the `iframe` tag)
* the CMS displays a footer, so setting the height to 1 million pixels is not a good idea
Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...
This technique seems to work ([gleaned](http://bytes.com/forum/thread91876.html) from several sources, but inspired by the [link](http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe) from the accepted answer:
In parent document:
```
<iframe id="MyIFRAME" name="MyIFRAME"
src="http://localhost/child.html"
scrolling="auto" width="100%" frameborder="0">
no iframes supported...
</iframe>
```
In child:
```
<!-- ... -->
<body>
<script type="text/javascript">
function resizeIframe() {
var docHeight;
if (typeof document.height != 'undefined') {
docHeight = document.height;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
docHeight = document.documentElement.scrollHeight;
}
else if (document.body
&& typeof document.body.scrollHeight != 'undefined') {
docHeight = document.body.scrollHeight;
}
// magic number: suppress generation of scrollbars...
docHeight += 20;
parent.document.getElementById('MyIFRAME').style.height = docHeight + "px";
}
parent.document.getElementById('MyIFRAME').onload = resizeIframe;
parent.window.onresize = resizeIframe;
</script>
</body>
```
**BTW:** This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons... | You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods:
<http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe>
<http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html> |
58,547 | <p>In C++ we acquiring a resource in a constructor and release it in a destructor.</p>
<p>So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.</p>
<p>AFAIK java classes don't have destructors. So how does one do the resource management in Java.</p>
<p>For example:</p>
<pre><code>public int foo() {
Resource f = new Resource();
DoSomething(f);
f.Release();
}
</code></pre>
<p>How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we?</p>
| [
{
"answer_id": 58552,
"author": "qbeuek",
"author_id": 5348,
"author_profile": "https://Stackoverflow.com/users/5348",
"pm_score": 3,
"selected": true,
"text": "<p>Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand \"using\" statement, but in Java you are stuck with:</p>\n\n<pre><code>public int foo() {\n Resource f = new Resource();\n try {\n DoSomething(f);\n }\n finally {\n f.Release();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 58563,
"author": "svrist",
"author_id": 86,
"author_profile": "https://Stackoverflow.com/users/86",
"pm_score": 0,
"selected": false,
"text": "<p>If you want the using block get involved in the java closure debate :S</p>\n"
},
{
"answer_id": 58573,
"author": "Spoike",
"author_id": 3713,
"author_profile": "https://Stackoverflow.com/users/3713",
"pm_score": -1,
"selected": false,
"text": "<p>Sorry to disappoint you but in Java we <strong>do</strong> use try\\catch\\finally blocks a lot. And with \"a lot\", I mean <strong>A LOT</strong>. I do sometimes wish that Java has the C# using block. Most of the time you won't need to free up resources as Java's garbage collector will take care of that.</p>\n\n<p>However exceptions do have their uses in making error handling a lot cleaner. You can write your own exceptions and catch them for whatever you are doing. No more returning arbitrary error codes to the user!</p>\n"
},
{
"answer_id": 58817,
"author": "Tom Hawtin - tackline",
"author_id": 4725,
"author_profile": "https://Stackoverflow.com/users/4725",
"pm_score": 2,
"selected": false,
"text": "<p>It is possible to factor out try/finally (and exception and algorithms) using the Execute around idiom. However the syntax is highly verbose.</p>\n\n<pre><code>public int foo() {\n withResource(new WithResource() { public void run(Resource resource) {\n doSomething(resource);\n }});\n}\n\n...\n\npublic interface WithResource {\n void run(Resource resource);\n}\n\npublic static void withResource(WithResource handler) {\n Resource resource = new Resource();\n try {\n handler.run(resource);\n } finally {\n resource.release();\n }\n}\n</code></pre>\n\n<p>This sort of thing makes more sense if you are abstracting more than try/finally. For instance, with JDBC you can execute a statement, loop through the results, close resources and wrap the exception.</p>\n"
},
{
"answer_id": 7866351,
"author": "Raedwald",
"author_id": 545127,
"author_profile": "https://Stackoverflow.com/users/545127",
"pm_score": 2,
"selected": false,
"text": "<p>This question dates to 2008 and therefore pertains to Java 6. Since then Java 7 has been released, which contains a new feature for Automatic Resource Management. For a more recent question that is relevant to Java 7 see this question:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/6628611/java-techniques-for-automatic-resource-release-prompt-cleanup\">java techniques for automatic resource release? "prompt cleanup"?</a></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58547",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
]
| In C++ we acquiring a resource in a constructor and release it in a destructor.
So when an exception rises in a middle of a function there will be no resource leak or locked mutexes or whatever.
AFAIK java classes don't have destructors. So how does one do the resource management in Java.
For example:
```
public int foo() {
Resource f = new Resource();
DoSomething(f);
f.Release();
}
```
How can one release resource if DoSomething throws an exception? We can't put try\catch blocks all over the code, can we? | Yes you can and should put try/catch/finally block around your code. In C# there is a shorthand "using" statement, but in Java you are stuck with:
```
public int foo() {
Resource f = new Resource();
try {
DoSomething(f);
}
finally {
f.Release();
}
}
``` |
58,554 | <p>I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function.</p>
<p>However, there's a catch: I also use <a href="http://www.lazycplusplus.com/" rel="nofollow noreferrer">Lazy C++</a>, a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file).</p>
<p>So my typical SourceFile.lzz looks like this:</p>
<pre><code>$hdr
#include <iosfwd>
#include "ProjectA/BaseClass.h"
$end
$src
#include <iostream>
#include "ProjectB/OtherClass.h"
$end
// Forward declarations
namespace BigScope::ProjectB
{
class OtherClass;
}
namespace BigScope::ProjectA
{
class MyClass : public ProjectA::BaseClass
{
void SomeMethod(const ProjectB::OtherClass& Foo) { }
}
}
</code></pre>
<p>As you see, it's still recognizable C++, but with a few extras.</p>
<p>For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access.</p>
<p>So here's my <strong>question</strong>: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options?</p>
<p>Thanks,</p>
<p>Carl</p>
| [
{
"answer_id": 59251,
"author": "Mike McQuaid",
"author_id": 5355,
"author_profile": "https://Stackoverflow.com/users/5355",
"pm_score": 2,
"selected": false,
"text": "<p>I'd imagine its one of:</p>\n\n<ul>\n<li><p>Eclipse doesn't want to display non-C++ resources in the tree (I've had problems with this)</p></li>\n<li><p>You don't have \"Preferences > C/C++ > Indexer > Index All Files\" enabled.</p></li>\n<li><p>You want to use the \"Full C/C++ Indexer\" rather than the \"Fast C/C++ Indexer\"</p></li>\n</ul>\n"
},
{
"answer_id": 837016,
"author": "Mike Kucera",
"author_id": 102367,
"author_profile": "https://Stackoverflow.com/users/102367",
"pm_score": 1,
"selected": false,
"text": "<p>The CDT parser/indexer won't recognize weird extensions like that. The only thing you can do is to define macros on the Paths and Symbols property page to trick the parser. Try creating macros for <code>$hdr</code>, <code>$end</code> and <code>$src</code> that have empty bodies. That way the preprocessor will remove them and the parser won't choke on them.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58554",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2095/"
]
| I'm using Eclipse as my IDE for a C++ project, and I would love for it to tell me where a given symbol is defined and what the parameters are for a function.
However, there's a catch: I also use [Lazy C++](http://www.lazycplusplus.com/), a tool that takes a single source file and generates the .h and the .cpp files. Those .lzz files look like headers, but this tool supports some very mild syntactic benefits, like combining nested namespaces into a qualified name. Additionally, it has some special tags to tell the tool specifically where to put what (in header or in source file).
So my typical SourceFile.lzz looks like this:
```
$hdr
#include <iosfwd>
#include "ProjectA/BaseClass.h"
$end
$src
#include <iostream>
#include "ProjectB/OtherClass.h"
$end
// Forward declarations
namespace BigScope::ProjectB
{
class OtherClass;
}
namespace BigScope::ProjectA
{
class MyClass : public ProjectA::BaseClass
{
void SomeMethod(const ProjectB::OtherClass& Foo) { }
}
}
```
As you see, it's still recognizable C++, but with a few extras.
For some reason, CDT's indexer does not seem to want to index anything, and I don't know what's wrong. In the Indexer View, it shows me an empty tree, but tells me that it has some 15000 symbols and more stuff, none of which I can seem to access.
So here's my **question**: how can I make the Indexer output some more information about what it's doing and why it fails when it does so, and can I tweak it more than with just the GUI-accessible options?
Thanks,
Carl | I'd imagine its one of:
* Eclipse doesn't want to display non-C++ resources in the tree (I've had problems with this)
* You don't have "Preferences > C/C++ > Indexer > Index All Files" enabled.
* You want to use the "Full C/C++ Indexer" rather than the "Fast C/C++ Indexer" |
58,561 | <p>I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?</p>
<p>An example :</p>
<pre><code>final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
.append( bob.class.getName() ).append( " bob " )
.append( "where bob.id > 10");
final Query query = session.createQuery( hql.toString() );
return query.list();
</code></pre>
| [
{
"answer_id": 58624,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 6,
"selected": false,
"text": "<p>I think you could do that with Projections, something like</p>\n\n<pre><code>Criteria.forClass(bob.class.getName())\n .add(Restrictions.gt(\"id\", 10))\n .setProjection(Projections.property(\"id\"))\n );\n</code></pre>\n"
},
{
"answer_id": 59028,
"author": "jspinks",
"author_id": 5253,
"author_profile": "https://Stackoverflow.com/users/5253",
"pm_score": 3,
"selected": false,
"text": "<p>or setProjection(Projections.id())</p>\n"
},
{
"answer_id": 781235,
"author": "Avinash",
"author_id": 42791,
"author_profile": "https://Stackoverflow.com/users/42791",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/2/\" rel=\"nofollow noreferrer\">http://www.devarticles.com/c/a/Java/Hibernate-Criteria-Queries-in-Depth/2/</a></p>\n"
},
{
"answer_id": 17128402,
"author": "korosmatick",
"author_id": 1885786,
"author_profile": "https://Stackoverflow.com/users/1885786",
"pm_score": 4,
"selected": false,
"text": "<p>Similarly you can also:</p>\n\n<pre><code>Criteria criteria = session.createCriteria(bob.class);\n\ncriteria.add(Expression.gt(\"id\", 10));\n\ncriteria.setProjection(Projections.property(\"id\"));\n\ncriteria.addOrder(Order.asc(\"id\"));\n\nreturn criteria.list();\n</code></pre>\n"
},
{
"answer_id": 29683153,
"author": "rogerdpack",
"author_id": 32453,
"author_profile": "https://Stackoverflow.com/users/32453",
"pm_score": 1,
"selected": false,
"text": "<p>Another option (though a bit un hibernate-esque) is to use \"raw\" sql, like this:</p>\n\n<pre><code>List<Long> myList = session.createSQLQuery(\"select single_column from table_name\")\n .addScalar(\"single_column\", StandardBasicTypes.LONG).list();\n</code></pre>\n"
},
{
"answer_id": 37202954,
"author": "Nalaka Dissanayake",
"author_id": 3650354,
"author_profile": "https://Stackoverflow.com/users/3650354",
"pm_score": -1,
"selected": false,
"text": "<p>You can do that like this</p>\n\n<pre><code> bob bb=null;\n\n Criteria criteria = session.createCriteria(bob.class); \n criteria.add(Restrictions.eq(\"id\",id));\n\n bb = (bob) criteria.uniqueResult();\n</code></pre>\n\n<p>as Restrictions you can add your condition</p>\n"
},
{
"answer_id": 57584281,
"author": "Ajinz",
"author_id": 11607606,
"author_profile": "https://Stackoverflow.com/users/11607606",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SessionFactory sessionFactory; \nCriteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class);\ncrit.setProjection(Projections.property(\"id\"));\nList result = crit.list();\n</code></pre>\n\n<p>This code code will give you list of ids in the model class like <code>[1,2,3]</code>.\nif you wants to get the array list like <code>[{\"id\":1},{\"id\":2}]</code> then use the following code</p>\n\n<pre><code>SessionFactory sessionFactory; \nCriteria crit=sessionFactory.getCurrentSession().createCriteria(Model.class); \ncrit.setProjection(Projections.property(\"id\").as(\"id\")); \nList result = crit.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP).list();\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I'm trying to get only the list of id of object bob for example instead of the list of bob. It's ok with a HQL request, but I would know if it's possible using criteria ?
An example :
```
final StringBuilder hql = new StringBuilder();
hql.append( "select bob.id from " )
.append( bob.class.getName() ).append( " bob " )
.append( "where bob.id > 10");
final Query query = session.createQuery( hql.toString() );
return query.list();
``` | I think you could do that with Projections, something like
```
Criteria.forClass(bob.class.getName())
.add(Restrictions.gt("id", 10))
.setProjection(Projections.property("id"))
);
``` |
58,564 | <p>I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug.</p>
| [
{
"answer_id": 58578,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>A core dump is a copy of the memory the process had access to when crashed. Depending on how the leak is occurring, it might have lost the reference to the handles, so it may prove to be useless.</p>\n\n<p>lsof lists all currently open files in the system, you could check its output to find leaked sockets or files. Yes, you'd need to have the process running. You could run it with a specific username to easily discern which are the open files from the process you are debugging.</p>\n\n<p>I hope somebody else has better information :-)</p>\n"
},
{
"answer_id": 58580,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 2,
"selected": false,
"text": "<p>You can try using <code>strace</code> to see the <code>open</code>, <code>socket</code> and <code>close</code> calls the program makes.</p>\n\n<p>Edit: I don't think you can get the information from the core; at most it will have the file descriptors somewhere, but this still doesn't give you the actual file/socket. (Assuming you can distinguish open from closed file descriptors, which I also doubt.)</p>\n"
},
{
"answer_id": 58583,
"author": "skolima",
"author_id": 3205,
"author_profile": "https://Stackoverflow.com/users/3205",
"pm_score": 0,
"selected": false,
"text": "<p>Another way to find out what files a process has opened - again, only during runtime - is looking into /proc/PID/fd/ , which contains symlinks to open files.</p>\n"
},
{
"answer_id": 58606,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>If the program forgot to close those resources it might be because something like the following happened:</p>\n\n<pre><code>fd = open(\"/tmp/foo\",O_CREAT);\n//do stuff\nfd = open(\"/tmp/bar\",O_CREAT); //Oops, forgot to close(fd)\n</code></pre>\n\n<p>now I won't have the file descriptor for foo in memory.</p>\n\n<p>If this didn't happen, you might be able to find the file descriptor number, but then again, that is not very useful because they are continuously changing, by the time you get to debug you won't know which file it actually meant at the time.</p>\n\n<p>I really think you should debug this live, with strace, lsof and friends.</p>\n\n<p>If there is a way to do it from the core dump, I'm eager to know it too :-)</p>\n"
},
{
"answer_id": 59039,
"author": "Martin Del Vecchio",
"author_id": 5397,
"author_profile": "https://Stackoverflow.com/users/5397",
"pm_score": 3,
"selected": false,
"text": "<p>Your best bet is to install a signal handler for whatever signal is crashing your program (SIGSEGV, etc.).</p>\n\n<p>Then, in the signal handler, inspect /proc/self/fd, and save the contents to a file. Here is a sample of what you might see:</p>\n\n<pre><code>Anderson cxc # ls -l /proc/8247/fd\ntotal 0\nlrwx------ 1 root root 64 Sep 12 06:05 0 -> /dev/pts/0\nlrwx------ 1 root root 64 Sep 12 06:05 1 -> /dev/pts/0\nlrwx------ 1 root root 64 Sep 12 06:05 10 -> anon_inode:[eventpoll]\nlrwx------ 1 root root 64 Sep 12 06:05 11 -> socket:[124061]\nlrwx------ 1 root root 64 Sep 12 06:05 12 -> socket:[124063]\nlrwx------ 1 root root 64 Sep 12 06:05 13 -> socket:[124064]\nlrwx------ 1 root root 64 Sep 12 06:05 14 -> /dev/driver0\nlr-x------ 1 root root 64 Sep 12 06:05 16 -> /temp/app/whatever.tar.gz\nlr-x------ 1 root root 64 Sep 12 06:05 17 -> /dev/urandom\n</code></pre>\n\n<p>Then you can return from your signal handler, and you should get a core dump as usual.</p>\n"
},
{
"answer_id": 65548,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 4,
"selected": false,
"text": "<p>If you have a core file and you have compiled the program with debugging options (-g), you can see where the core was dumped:</p>\n<pre><code>$ gcc -g -o something something.c\n$ ./something\nSegmentation fault (core dumped)\n$ gdb something core\n</code></pre>\n<p>You can use this to do some post-morten debugging. A few gdb commands: bt prints the stack, fr jumps to given stack frame (see the output of bt).</p>\n<p>Now if you want to see which files are opened at a segmentation fault, just handle the SIGSEGV signal, and in the handler, just dump the contents of the /proc/PID/fd directory (i.e. with system('ls -l /proc/PID/fs') or execv).</p>\n<p>With these information at hand you can easily find what caused the crash, which files are opened and if the crash and the file descriptor leak are connected.</p>\n"
},
{
"answer_id": 27558400,
"author": "JodieC",
"author_id": 1467450,
"author_profile": "https://Stackoverflow.com/users/1467450",
"pm_score": 2,
"selected": false,
"text": "<p>One of the ways I jump to this information is just running <code>strings</code> on the core file. For instance, when I was running file on a core recently, due to the length of the folders I would get a truncated arguments list. I knew my run would have opened files from my home directory, so I just ran:</p>\n\n<pre><code>strings core.14930|grep jodie\n</code></pre>\n\n<p>But this is a case where I had a needle and a haystack. </p>\n"
},
{
"answer_id": 32613101,
"author": "Pinak Mazumdar",
"author_id": 5343092,
"author_profile": "https://Stackoverflow.com/users/5343092",
"pm_score": 2,
"selected": false,
"text": "<p>Recently during my error troubleshooting and analysis , my customer provided me a coredump which got generated in his filesystem and he went out of station in order to quickly scan through the file and read its contents i used the command</p>\n\n<p>strings core.67545 > coredump.txt\nand later i was able to open the file in file editor.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
]
| I have a core dump file from a process that has probably a file descriptor leak (it opens files and sockets but apparently sometimes forgets to close some of them). Is there a way to find out which files and sockets the process had opened before crashing? I can't easily reproduce the crash, so analyzing the core file seems to be the only way to get a hint on the bug. | If you have a core file and you have compiled the program with debugging options (-g), you can see where the core was dumped:
```
$ gcc -g -o something something.c
$ ./something
Segmentation fault (core dumped)
$ gdb something core
```
You can use this to do some post-morten debugging. A few gdb commands: bt prints the stack, fr jumps to given stack frame (see the output of bt).
Now if you want to see which files are opened at a segmentation fault, just handle the SIGSEGV signal, and in the handler, just dump the contents of the /proc/PID/fd directory (i.e. with system('ls -l /proc/PID/fs') or execv).
With these information at hand you can easily find what caused the crash, which files are opened and if the crash and the file descriptor leak are connected. |
58,584 | <p>Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?</p>
<p>I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?</p>
<p>And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs?</p>
| [
{
"answer_id": 58585,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 3,
"selected": false,
"text": "<p>Use the visual block command v (or V for whole lines and <kbd>C</kbd>-<kbd>V</kbd> for rectangular blocks). While in visual block mode, you can use any motion commands including search; I use } frequently to skip to the next blank line. Once the block is marked, you can :w it to a file, delete, yank, or whatever. If you execute a command and the visual block goes away, re-select the same block with gv. See :help visual-change for more.</p>\n\n<p>I think there are language-specific scripts that come with vim that do things like comment out blocks of code in a way that fits your language of choice.</p>\n"
},
{
"answer_id": 58586,
"author": "fijter",
"author_id": 3215,
"author_profile": "https://Stackoverflow.com/users/3215",
"pm_score": 2,
"selected": false,
"text": "<p>Use <kbd>Shift</kbd>+<kbd>V</kbd> to go in visual mode, then you can select lines and delete / change them.</p>\n"
},
{
"answer_id": 58588,
"author": "zigdon",
"author_id": 4913,
"author_profile": "https://Stackoverflow.com/users/4913",
"pm_score": 6,
"selected": true,
"text": "<p>Well, first of all, you can set <code>vim</code> to work with the mouse, which would allow you to select text just like you would in <code>Eclipse</code>.</p>\n\n<p>You can also use the Visual selection - <kbd>v</kbd>, by default. Once selected, you can <code>yank</code>, <code>cut</code>, etc.</p>\n\n<p>As far as commenting out the block, I usually select it with <code>VISUAL</code>, then do</p>\n\n<pre><code>:'<,'>s/^/# /\n</code></pre>\n\n<p>Replacing the beginning of each line with a <code>#</code>. (The <code>'<</code> and <code>'></code> markers are the beginning and and of the visual selection.</p>\n"
},
{
"answer_id": 58590,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>v enters visual block mode, where you can select as if with shift in most common editors, later you can do anything you can normally do with normal commands (substitution :'<,'>s/^/#/ to prepend with a comment, for instance) where '<,'> means the selected visual block instead of all the text.</p>\n"
},
{
"answer_id": 58592,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 2,
"selected": false,
"text": "<p>Press <code>V</code> (uppercase V) and then press <code>40j</code> to select 40 lines and then press <code>d</code> to delete them. Or as @zigdon replied, you can comment them out.</p>\n"
},
{
"answer_id": 58598,
"author": "luntain",
"author_id": 5978,
"author_profile": "https://Stackoverflow.com/users/5978",
"pm_score": 2,
"selected": false,
"text": "<p>The visual mode is the solution for your main problem. As to commenting out sections of code, there are many plugins for that on vim.org, I am using tComment.vim at the moment. </p>\n\n<p>There is also a neat way to comment out a block without a plugin. Lets say you work in python and # is the comment character. Make a visual block selection of the column you want the hash sign to be in, and type I#ESCAPE. To enter a visual block mode press C-q on windows or C-v on linux.</p>\n"
},
{
"answer_id": 58610,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 4,
"selected": false,
"text": "<p>Use markers.</p>\n\n<p>Go to the top of the text block you want to delete and enter</p>\n\n<pre><code>ma\n</code></pre>\n\n<p>anywhere on that line. No need for the colon.</p>\n\n<p>Then go to the end of the block and enter the following:</p>\n\n<pre><code>:'a,.d\n</code></pre>\n\n<p>Entering <code>ma</code> has set marker <code>a</code> for the character under the cursor.</p>\n\n<p>The command you have entered after moving to the bottom of the text block says \"from the line containing the character described by marker <code>a</code> (<kbd>'</kbd><kbd>a</kbd>) to the current line (<kbd>.</kbd>) <code>d</code>elete.\"</p>\n\n<p>This sort of thing can be used for other things as well.</p>\n\n<pre><code>:'a,.ya b - yank from 'a to current line and put in buffer 'b'\n:'a,.ya B - yank from 'a to current line and append to buffer 'b'\n:'a,.s/^/#/ - from 'a to current line, substitute '#' for line begin\n(i.e. comment out in Perl)\n:'s,.s#^#//# - from 'a to current line, substitute '//' for line begin\n(i.e. comment out in C++)\n</code></pre>\n\n<p><strong>N.B.</strong> <code>'a</code> (apostrophe-a) refers to the line containing the character marked by <code>a</code>. ``a<code>(backtick-a) refers to the character marked by</code>a`.</p>\n"
},
{
"answer_id": 58696,
"author": "Jagmal",
"author_id": 4406,
"author_profile": "https://Stackoverflow.com/users/4406",
"pm_score": 2,
"selected": false,
"text": "<p>Or you may want to give this script a try...</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=23\" rel=\"nofollow noreferrer\">http://www.vim.org/scripts/script.php?script_id=23</a></p>\n"
},
{
"answer_id": 58727,
"author": "Jonas Engman",
"author_id": 4164,
"author_profile": "https://Stackoverflow.com/users/4164",
"pm_score": 4,
"selected": false,
"text": "<p>To insert comments select the beginning characters of the lines using <kbd>CTRL</kbd>-<kbd>v</kbd> (blockwise-visual, not 'v' character wise-visual or 'V' linewise-visual). Then go to insert-mode using 'I', enter your comment-character(s) on the first line (for example '#') and finally escape to normal mode using 'Esc'. Voila!</p>\n\n<p>To remove the comments use blockwise-visual to select the comments and just delete them using '<kbd>x</kbd>'.</p>\n"
},
{
"answer_id": 58882,
"author": "amrox",
"author_id": 4468,
"author_profile": "https://Stackoverflow.com/users/4468",
"pm_score": 2,
"selected": false,
"text": "<p>My block comment technique:</p>\n\n<p><kbd>Ctrl</kbd>+<kbd>V</kbd> to start blockwise visual mode.</p>\n\n<p>Make your selection.</p>\n\n<p>With the selection still active, <kbd>Shift</kbd>+<kbd>I</kbd>. This put you into column insert mode.</p>\n\n<p>Type you comment characters '#' or '//' or whatever.</p>\n\n<p>ESC.</p>\n"
},
{
"answer_id": 65510,
"author": "JP Lodine",
"author_id": 8998,
"author_profile": "https://Stackoverflow.com/users/8998",
"pm_score": 1,
"selected": false,
"text": "<p>My usual method for commenting out 40 lines would be to put the cursor on the first line and enter the command:</p>\n\n<p>:.,+40s/^/# /</p>\n\n<p>(For here thru 40 lines forward, substitute start-of-line with hash, space)\nSeems a bit longer than some other methods suggested, but I like to do things with the keyboard instead of the mouse.</p>\n"
},
{
"answer_id": 65593,
"author": "shyam",
"author_id": 7616,
"author_profile": "https://Stackoverflow.com/users/7616",
"pm_score": 0,
"selected": false,
"text": "<p>marks would be the simplest <strong>mb</strong> where u want to begin and <strong>me</strong> where u want to end once this is done you can do pretty much anything you want</p>\n\n<pre><code>:'b,'ed\n</code></pre>\n\n<p>deletes from marker <strong>b</strong> to marker <strong>e</strong></p>\n\n<p>commenting out 40 lines you can do in the visual mode</p>\n\n<pre><code>V40j:s/^/#/\n</code></pre>\n\n<p>will comment out 40 lines from where u start the sequence</p>\n"
},
{
"answer_id": 274837,
"author": "Dergachev",
"author_id": 9621,
"author_profile": "https://Stackoverflow.com/users/9621",
"pm_score": 1,
"selected": false,
"text": "<p>You should be aware of the normal mode command [count]<kbd>CTRL</kbd>-<kbd>D</kbd>.\nIt optionally changes the 'scroll' option from 10 to [count], and then scrolls down that many lines. Pressing <kbd>CTRL</kbd>-<kbd>D</kbd> again will scroll down that same lines again.</p>\n\n<p>So try entering </p>\n\n<pre><code>V \"visual line selection mode\n30 \"optionally set scroll value to 30\nCTRL-D \"jump down a screen, repeated as necessary\ny \" yank your selection\n</code></pre>\n\n<p>CTRL-U works the same way but scrolls up.</p>\n"
},
{
"answer_id": 560369,
"author": "Nathan Fellman",
"author_id": 1084,
"author_profile": "https://Stackoverflow.com/users/1084",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to perform an action on a range of lines, and you know the line numbers, you can put the range on the command line. For instance, to delete lines 20 through 200 you can do:</p>\n\n<pre><code>:20,200d\n</code></pre>\n\n<p>To move lines 20 through 200 to where line 300 is you can use:</p>\n\n<pre><code>:20,200m300\n</code></pre>\n\n<p>And so on.</p>\n"
},
{
"answer_id": 570665,
"author": "Jeremy Cantrell",
"author_id": 18866,
"author_profile": "https://Stackoverflow.com/users/18866",
"pm_score": 2,
"selected": false,
"text": "<p>For commenting out lines, I would suggest one of these plugins:</p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=23\" rel=\"nofollow noreferrer\">EnhancedCommentify</a></p>\n\n<p><a href=\"http://www.vim.org/scripts/script.php?script_id=1218\" rel=\"nofollow noreferrer\">NERD Commenter</a></p>\n\n<p>I find myself using NERD more these days, but I've used EnhancedCommentify for years.</p>\n"
},
{
"answer_id": 3007803,
"author": "Evgeny",
"author_id": 331701,
"author_profile": "https://Stackoverflow.com/users/331701",
"pm_score": 1,
"selected": false,
"text": "<p>First answer is currently not quite right?\nTo comment out selection press ':' and type command\n:'<,'>s/^/# /g</p>\n\n<p>('<, '> - will be there automatically)</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
]
| Selecting a large amount of text that extends over many screens in an IDE like Eclipse is fairly easy since you can use the mouse, but what is the best way to e.g. select and delete multiscreen blocks of text or write e.g. three large methods out to another file and then delete them for testing purposes in Vim when using it via putty/ssh where you cannot use the mouse?
I can easily yank-to-the-end-of-line or yank-to-the-end-of-code-block but if the text extends over many screens, or has lots of blank lines in it, I feel like my hands are tied in Vim. Any solutions?
And a related question: is there a way to somehow select 40 lines, and then comment them all out (with "#" or "//"), as is common in most IDEs? | Well, first of all, you can set `vim` to work with the mouse, which would allow you to select text just like you would in `Eclipse`.
You can also use the Visual selection - `v`, by default. Once selected, you can `yank`, `cut`, etc.
As far as commenting out the block, I usually select it with `VISUAL`, then do
```
:'<,'>s/^/# /
```
Replacing the beginning of each line with a `#`. (The `'<` and `'>` markers are the beginning and and of the visual selection. |
58,614 | <p>I'm developing a multi-threaded app for a Linux embedded platform.</p>
<p>At the moment I'm setting the stack size for each thread (via pthread_set_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.</p>
<p>I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)</p>
<p>Thanks</p>
| [
{
"answer_id": 58628,
"author": "Tobi",
"author_id": 5422,
"author_profile": "https://Stackoverflow.com/users/5422",
"pm_score": 2,
"selected": false,
"text": "<p>I do not know any good tools but as last resort you could include some code in your application to check it, similar to the following:</p>\n\n<pre><code>__thread void* stack_start;\n__thread long stack_max_size = 0L;\n\nvoid check_stack_size() {\n // address of 'nowhere' approximates end of stack\n char nowhere;\n void* stack_end = (void*)&nowhere;\n // may want to double check stack grows downward on your platform\n long stack_size = (long)stack_start - (long)stack_end;\n // update max_stack_size for this thread\n if (stack_size > stack_max_size)\n stack_max_size = stack_size;\n}\n</code></pre>\n\n<p>The check_stack_size() function would have to be called in some of the functions that are most deeply nested.</p>\n\n<p>Then as last statement in the thread you could output stack_max_size to somewhere.</p>\n\n<p>The stack_start variable would have to be initialized at start of your thread:</p>\n\n<pre><code>void thread_proc() {\n char nowhere;\n stack_start = (void*)&nowhere;\n // do stuff including calls to check_stack_size()\n // in deeply nested functions\n // output stack_max_size here\n}\n</code></pre>\n"
},
{
"answer_id": 58980,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 2,
"selected": false,
"text": "<p>Referencing Tobi's answer: You can use <code>pthread_attr_getstackaddr</code> to get the base of the stack at any time, if setting a variable at thread initialization is difficult. You can then get the address of an automatic variable in your own function to determine how deep the stack is at that moment.</p>\n"
},
{
"answer_id": 28856039,
"author": "d99kris",
"author_id": 485047,
"author_profile": "https://Stackoverflow.com/users/485047",
"pm_score": 3,
"selected": false,
"text": "<p>Here are two tools that measure (native pthreads) stack usage in Linux applications:</p>\n\n<ul>\n<li><a href=\"http://valgrind.org\" rel=\"nofollow noreferrer\" title=\"Valgrind\">Valgrind</a></li>\n<li><a href=\"https://github.com/d99kris/stackusage\" rel=\"nofollow noreferrer\" title=\"stackusage\">Stackusage</a></li>\n</ul>\n\n<p><strong>Valgrind</strong></p>\n\n<p>Usage:</p>\n\n<pre><code>valgrind --tool=drd --show-stack-usage=yes PROG\n</code></pre>\n\n<p>Valgrind is a stable and powerful tool, useful not only for measuring stack usage. It may not support all embedded CPU models though.</p>\n\n<p><strong>Stackusage</strong></p>\n\n<p>Usage:</p>\n\n<pre><code>stackusage PROG\n</code></pre>\n\n<p>Stackusage is a light-weight tool specifically designed for measuring thread stack usage which should be portable for most embedded Linux platforms equipped with glibc. It is likely not as well-tested or mature as Valgrind/drd at this point.</p>\n\n<p>Full disclosure: I'm the author of Stackusage.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58614",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6089/"
]
| I'm developing a multi-threaded app for a Linux embedded platform.
At the moment I'm setting the stack size for each thread (via pthread\_set\_attr) to a fairly large default value. I would like to fine tune that value for each thread to something smaller to reduce my application's memory usage. I could go through the trial and error route of setting each thread's stack size to progressively smaller values until the program crashed, but the application uses ~15 threads each with completely different functionality/attributes so that approach would be extremely time consuming.
I would much rather prefer being able to directly measure each thread's stack usage. Is there some utility people can recommend to do this? (For example, I come from a vxWorks background and using the 'ti' command from the vxWorks shell directly gives stats on the stack usage as well as other useful info on the task status.)
Thanks | Here are two tools that measure (native pthreads) stack usage in Linux applications:
* [Valgrind](http://valgrind.org "Valgrind")
* [Stackusage](https://github.com/d99kris/stackusage "stackusage")
**Valgrind**
Usage:
```
valgrind --tool=drd --show-stack-usage=yes PROG
```
Valgrind is a stable and powerful tool, useful not only for measuring stack usage. It may not support all embedded CPU models though.
**Stackusage**
Usage:
```
stackusage PROG
```
Stackusage is a light-weight tool specifically designed for measuring thread stack usage which should be portable for most embedded Linux platforms equipped with glibc. It is likely not as well-tested or mature as Valgrind/drd at this point.
Full disclosure: I'm the author of Stackusage. |
58,620 | <p>How do I create a button control (with <code>CreateWindow</code> of a <code>BUTTON</code> window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.</p>
<blockquote>
<p><strong>Remark:</strong> Using <code>USE_CW_DEFAULT</code> for width and height results in a 0, 0 size button, so that's not a solution.</p>
</blockquote>
| [
{
"answer_id": 58636,
"author": "Timbo",
"author_id": 1810,
"author_profile": "https://Stackoverflow.com/users/1810",
"pm_score": 3,
"selected": false,
"text": "<p>This is what MSDN has to say: <a href=\"http://msdn.microsoft.com/en-us/library/ms997619.aspx\" rel=\"noreferrer\">Design Specifications and Guidelines - Visual Design: Layout</a>.</p>\n\n<p>The default size of a button is 50x14 DLUs, which can be calculated to pixels using the examples shown for <a href=\"http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx\" rel=\"noreferrer\">GetDialogBaseUnits</a>.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/ms645502(VS.85).aspx\" rel=\"noreferrer\">MapDialogRect</a> function seems to do the calculation for you.</p>\n"
},
{
"answer_id": 58689,
"author": "macbirdie",
"author_id": 5049,
"author_profile": "https://Stackoverflow.com/users/5049",
"pm_score": 4,
"selected": true,
"text": "<h2>In the perfect, hassle-free world...</h2>\n\n<p>To create a standard size button we would have to do this:</p>\n\n<pre><code>LONG units = GetDialogBaseUnits();\nm_hButton = CreateWindow(TEXT(\"BUTTON\"), TEXT(\"Close\"), \n WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON, \n 0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),\n hwnd, NULL, hInst, NULL);\n</code></pre>\n\n<p>where <strong>50</strong> and <strong>14</strong> are respective DLU dimensions, <strong>4</strong> and <strong>8</strong> are horizontal and vertical dialog template units respectively, based on <a href=\"http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx\" rel=\"noreferrer\"><code>GetDialogBaseUnits()</code> function</a> documentation remarks.</p>\n\n<hr>\n\n<h2>Nothing's perfect</h2>\n\n<p><strong>BUT</strong> as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own.</p>\n\n<p>To get your own \"dialog\" base units, you have to retrieve current text metrics with <code>GetTextMetrics()</code> and use character height and average width (<code>tmHeight</code> and <code>tmAveCharWidth</code> of the <code>TEXTMETRIC</code> struct respectively) and translate them with MulDiv by your own, <strong>unless</strong> you are in a dialog, then <code>MapDialogRect()</code> will do all the job for you.</p>\n\n<p>Note that <code>tmAveCharWidth</code> only approximates the actual average character width so it's recommended to use a <a href=\"http://msdn.microsoft.com/en-us/library/dd144938.aspx\" rel=\"noreferrer\"><code>GetTextExtentPoint32()</code></a> function on an alphabetic character set instead.</p>\n\n<p>See:</p>\n\n<ul>\n<li><a href=\"http://support.microsoft.com/kb/145994\" rel=\"noreferrer\">How to calculate dialog box units based on the current font in Visual C++</a></li>\n<li><a href=\"http://support.microsoft.com/kb/125681\" rel=\"noreferrer\">How To Calculate Dialog Base Units with Non-System-Based Font</a></li>\n</ul>\n\n<hr>\n\n<h2>Simpler alternative</h2>\n\n<p>If buttons are the only control you want to resize automatically, you can also use <a href=\"http://msdn.microsoft.com/en-us/library/bb775961(VS.85).aspx\" rel=\"noreferrer\"><code>BCM_GETIDEALSIZE</code></a> message <a href=\"http://msdn.microsoft.com/en-us/library/bb761851(VS.85).aspx\" rel=\"noreferrer\"><code>Button_GetIdealSize()</code></a> macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text.</p>\n"
},
{
"answer_id": 59387,
"author": "Anders",
"author_id": 3501,
"author_profile": "https://Stackoverflow.com/users/3501",
"pm_score": 1,
"selected": false,
"text": "<p>@macbirdie: you should NOT use GetDialogBaseUnits(), it is based on the default system font (Ugly bitmap font). You should use MapDialogRect()</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58620",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5049/"
]
| How do I create a button control (with `CreateWindow` of a `BUTTON` window class) that has a standard system-wide size (especially height) that's consistent with the rest of Windows applications?
I should of course take DPI into account and probably other settings.
>
> **Remark:** Using `USE_CW_DEFAULT` for width and height results in a 0, 0 size button, so that's not a solution.
>
>
> | In the perfect, hassle-free world...
------------------------------------
To create a standard size button we would have to do this:
```
LONG units = GetDialogBaseUnits();
m_hButton = CreateWindow(TEXT("BUTTON"), TEXT("Close"),
WS_VISIBLE | WS_CHILD | BS_DEFPUSHBUTTON,
0, 0, MulDiv(LOWORD(units), 50, 4), MulDiv(HIWORD(units), 14, 8),
hwnd, NULL, hInst, NULL);
```
where **50** and **14** are respective DLU dimensions, **4** and **8** are horizontal and vertical dialog template units respectively, based on [`GetDialogBaseUnits()` function](http://msdn.microsoft.com/en-us/library/ms645475(VS.85).aspx) documentation remarks.
---
Nothing's perfect
-----------------
**BUT** as Anders pointed out, those metrics are based on the system font. If your window uses a shell dialog font or simply anything not making your eyes bleed, you're pretty much on your own.
To get your own "dialog" base units, you have to retrieve current text metrics with `GetTextMetrics()` and use character height and average width (`tmHeight` and `tmAveCharWidth` of the `TEXTMETRIC` struct respectively) and translate them with MulDiv by your own, **unless** you are in a dialog, then `MapDialogRect()` will do all the job for you.
Note that `tmAveCharWidth` only approximates the actual average character width so it's recommended to use a [`GetTextExtentPoint32()`](http://msdn.microsoft.com/en-us/library/dd144938.aspx) function on an alphabetic character set instead.
See:
* [How to calculate dialog box units based on the current font in Visual C++](http://support.microsoft.com/kb/145994)
* [How To Calculate Dialog Base Units with Non-System-Based Font](http://support.microsoft.com/kb/125681)
---
Simpler alternative
-------------------
If buttons are the only control you want to resize automatically, you can also use [`BCM_GETIDEALSIZE`](http://msdn.microsoft.com/en-us/library/bb775961(VS.85).aspx) message [`Button_GetIdealSize()`](http://msdn.microsoft.com/en-us/library/bb761851(VS.85).aspx) macro (Windows XP and up only) to retrieve optimal width and height that fits anything the button contains, though it looks pretty ugly without any margins applied around the button's text. |
58,621 | <p>How do I make an MD5 hash of a string with Delphi?</p>
| [
{
"answer_id": 58626,
"author": "devstopfix",
"author_id": 3366,
"author_profile": "https://Stackoverflow.com/users/3366",
"pm_score": 5,
"selected": false,
"text": "<p>If you want an MD5 digest and have the <a href=\"http://www.indyproject.org\" rel=\"nofollow noreferrer\">Indy</a> components installed, you can do this:</p>\n\n<pre><code>uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;\n\nwith TIdHashMessageDigest5.Create do\ntry\n Result := TIdHash128.AsHex(HashValue('Hello, world'));\nfinally\n Free;\nend;\n</code></pre>\n\n<p>Most popular algorithms are supported in the <a href=\"http://www.cityinthesky.co.uk/opensource/dcpcrypt/\" rel=\"nofollow noreferrer\">Delphi Cryptography Package</a>:</p>\n\n<ul>\n<li>Haval</li>\n<li>MD4, MD5</li>\n<li>RipeMD-128, RipeMD-160</li>\n<li>SHA-1, SHA-256, SHA-384, SHA-512,</li>\n<li>Tiger</li>\n</ul>\n\n<p><strong>Update</strong>\n<code>DCPCrypt</code> is now maintained by <a href=\"https://stackoverflow.com/users/84704/warren-p\">Warren Postma</a> and source can be found <a href=\"https://bitbucket.org/wpostma/dcpcrypt2010\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 59471,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use the WindowsCrypto API with Delphi:</p>\n\n<ul>\n<li><a href=\"http://www.davinciunltd.com/code/delphi-cryptography/\" rel=\"nofollow noreferrer\">General Crypto & Hash demo and resources</a></li>\n</ul>\n\n<p>There is a unit in there that wraps all the CryptoAPI. You can also use Lockbox, which is now open source. </p>\n\n<p>In the end you can support pretty much any Hash algorithms with Delphi. The Indy example is probably the closest you will get to natively in Delphi since Indy is included with most versions of Delphi. For the rest you will need to either use a library or write some more code to access the CryptoAPI or implement it yourself.</p>\n"
},
{
"answer_id": 83202,
"author": "Schalk Versteeg",
"author_id": 15724,
"author_profile": "https://Stackoverflow.com/users/15724",
"pm_score": 4,
"selected": false,
"text": "<p>I usually use DCPCrypt2 (<a href=\"http://www.cityinthesky.co.uk/opensource/dcpcrypt/\" rel=\"nofollow noreferrer\">Delphi Cryptography Package</a>) from David Barton (<a href=\"http://www.cityinthesky.co.uk/opensource/\" rel=\"nofollow noreferrer\">City in the Sky</a>).</p>\n\n<p>It is also contains the following Encryption Algorithms:</p>\n\n<ul>\n<li>Blowfish</li>\n<li>Cast 128</li>\n<li>Cast 256</li>\n<li>DES, 3DES</li>\n<li>Ice, Thin Ice, Ice2</li>\n<li>IDEA</li>\n<li>Mars</li>\n<li>Misty1</li>\n<li>RC2, RC4, RC5, RC6</li>\n<li>Rijndael (the new AES)</li>\n<li>Serpent</li>\n<li>Tea</li>\n<li>Twofish</li>\n</ul>\n\n<p><strong>Update</strong>\n<code>DCPCrypt</code> is now maintained by <a href=\"https://stackoverflow.com/users/84704/warren-p\">Warren Postma</a> and source can be found <a href=\"https://bitbucket.org/wpostma/dcpcrypt2010\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 7412013,
"author": "mjn",
"author_id": 80901,
"author_profile": "https://Stackoverflow.com/users/80901",
"pm_score": 3,
"selected": false,
"text": "<p>If all you want to do is use a dictionary, and you're not looking for security then:<br>\nIn Delphi 2009 and higher, hash values for strings can be created with</p>\n\n<p><strong><a href=\"http://docwiki.embarcadero.com/VCL/en/Generics.Defaults.BobJenkinsHash\" rel=\"nofollow\"><code>BobJenkinsHash</code></a><code>(Value, Length(Value) * SizeOf(Value), 0)</code></strong> </p>\n\n<p>where Value is a string. </p>\n\n<p><a href=\"http://docwiki.embarcadero.com/VCL/en/Generics.Defaults.BobJenkinsHash\" rel=\"nofollow\">http://docwiki.embarcadero.com/VCL/en/Generics.Defaults.BobJenkinsHash</a></p>\n"
},
{
"answer_id": 8505190,
"author": "Sean B. Durkin",
"author_id": 10823,
"author_profile": "https://Stackoverflow.com/users/10823",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://lockbox.seanbdurkin.id.au/tiki-index.php\" rel=\"nofollow\">TurboPower Lockbox</a> supports:</p>\n\n<ul>\n<li>MD-5,</li>\n<li>SHA-1 and</li>\n<li>the entire SHA-2 family including the recently published SHA-512/224 & SHA-512/256 hashes.</li>\n</ul>\n"
},
{
"answer_id": 18233500,
"author": "Stéphane B.",
"author_id": 281600,
"author_profile": "https://Stackoverflow.com/users/281600",
"pm_score": 4,
"selected": false,
"text": "<p>If you want an <strong>MD5 hash</strong> string as hexadeciamal and you have <strong>Delphi XE 1</strong> installed, so you have <strong>Indy 10</strong>.5.7 components you can do this:</p>\n\n<blockquote>\n <p>uses IdGlobal, IdHash, IdHashMessageDigest;</p>\n</blockquote>\n\n<pre><code>class function getMd5HashString(value: string): string;\nvar\n hashMessageDigest5 : TIdHashMessageDigest5;\nbegin\n hashMessageDigest5 := nil;\n try\n hashMessageDigest5 := TIdHashMessageDigest5.Create;\n Result := IdGlobal.IndyLowerCase ( hashMessageDigest5.HashStringAsHex ( value ) );\n finally\n hashMessageDigest5.Free;\n end;\nend;\n</code></pre>\n"
},
{
"answer_id": 21187716,
"author": "Arioch 'The",
"author_id": 976391,
"author_profile": "https://Stackoverflow.com/users/976391",
"pm_score": 3,
"selected": false,
"text": "<p>Spring For Delphi project - <a href=\"http://www.spring4d.org\" rel=\"noreferrer\">http://www.spring4d.org</a> - has implementation for a number of SHAxxx hashes, MD5 hash, and also number of CRC functions</p>\n"
},
{
"answer_id": 28132865,
"author": "StanE",
"author_id": 1854856,
"author_profile": "https://Stackoverflow.com/users/1854856",
"pm_score": 3,
"selected": false,
"text": "<p>This is a modification of devstopfix's answer which was accepted.</p>\n\n<p>In current Indy version you can hash strings and streams more easily. Example:</p>\n\n<pre><code>function MD5String(str: String): String;\nbegin\n with TIdHashMessageDigest5.Create do\n try\n Result := HashStringAsHex(str);\n finally\n Free;\n end;\nend;\n</code></pre>\n\n<p>Use <code>HashString</code>, <code>HashStringAsHex</code>, <code>HashBytes</code>, <code>HashBytesAsHex</code>, <code>HashStream</code>, <code>HashStreamAsHex</code>. The advantage is that you can also specify a text encoding</p>\n"
},
{
"answer_id": 60602595,
"author": "fpiette",
"author_id": 189103,
"author_profile": "https://Stackoverflow.com/users/189103",
"pm_score": 1,
"selected": false,
"text": "<p>Using ICS, you simply call StrMD5 function which is located in OverbytecsMD5 unit.</p>\n\n<p>Beside that specific function, there are a lot more MD5 function for other datatypes and scenarios. There are also other hash methods such as SHA.</p>\n"
},
{
"answer_id": 60603912,
"author": "Schneider Infosystems Ltd",
"author_id": 2685300,
"author_profile": "https://Stackoverflow.com/users/2685300",
"pm_score": 4,
"selected": false,
"text": "<p>Why not use the <code>system.Hash</code> unit from RTL, that contains also a hash algorithm for MD5 since Delphi Seattle?</p>\n\n<pre><code>MD5HashCode := THashMD5.GetHashString(ClearTextString);\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3366/"
]
| How do I make an MD5 hash of a string with Delphi? | If you want an MD5 digest and have the [Indy](http://www.indyproject.org) components installed, you can do this:
```
uses SysUtils, IdGlobal, IdHash, IdHashMessageDigest;
with TIdHashMessageDigest5.Create do
try
Result := TIdHash128.AsHex(HashValue('Hello, world'));
finally
Free;
end;
```
Most popular algorithms are supported in the [Delphi Cryptography Package](http://www.cityinthesky.co.uk/opensource/dcpcrypt/):
* Haval
* MD4, MD5
* RipeMD-128, RipeMD-160
* SHA-1, SHA-256, SHA-384, SHA-512,
* Tiger
**Update**
`DCPCrypt` is now maintained by [Warren Postma](https://stackoverflow.com/users/84704/warren-p) and source can be found [here](https://bitbucket.org/wpostma/dcpcrypt2010). |
58,622 | <p>I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have <code>/* .. */</code> comments, and also has its own self-documentation facility which seems to be the pythonic way to document.</p>
<p>Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of?</p>
| [
{
"answer_id": 58701,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 7,
"selected": true,
"text": "<p>This is <a href=\"http://www.doxygen.nl/manual/docblocks.html#pythonblocks\" rel=\"noreferrer\">documented on the doxygen website</a>, but to summarize here:</p>\n\n<p>You can use doxygen to document your Python code. You can either use the Python documentation string syntax:</p>\n\n<pre><code>\"\"\"@package docstring\nDocumentation for this module.\n\nMore details.\n\"\"\"\n\ndef func():\n \"\"\"Documentation for a function.\n\n More details.\n \"\"\"\n pass\n</code></pre>\n\n<p>In which case the comments will be extracted by doxygen, but you won't be able to use any of the <a href=\"http://www.doxygen.nl/manual/commands.html#cmd_intro\" rel=\"noreferrer\">special doxygen commands</a>.</p>\n\n<p><strong>Or</strong> you can (similar to C-style languages under doxygen) double up the comment marker (<code>#</code>) on the first line before the member:</p>\n\n<pre><code>## @package pyexample\n# Documentation for this module.\n#\n# More details.\n\n## Documentation for a function.\n#\n# More details.\ndef func():\n pass\n</code></pre>\n\n<p>In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting <code>OPTMIZE_OUTPUT_JAVA</code> to <code>YES</code>.</p>\n\n<p>Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or \"\"\" blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using \"\"\" to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands?</p>\n"
},
{
"answer_id": 59018,
"author": "Peter Hoffmann",
"author_id": 720,
"author_profile": "https://Stackoverflow.com/users/720",
"pm_score": 4,
"selected": false,
"text": "<p>An other very good documentation tool is <a href=\"http://www.sphinx-doc.org/en/master/index.html\" rel=\"nofollow noreferrer\">sphinx</a>. It will be used for the upcoming python 2.6 <a href=\"http://docs.python.org/dev/\" rel=\"nofollow noreferrer\">documentation</a> and is used by <a href=\"http://docs.djangoproject.com/en/dev/\" rel=\"nofollow noreferrer\">django</a> and a lot of other python projects.</p>\n\n<p>From the sphinx website:</p>\n\n<ul>\n<li><strong>Output formats</strong>: HTML (including Windows HTML Help) and LaTeX, for printable PDF versions</li>\n<li><strong>Extensive cross-references</strong>: semantic markup and automatic links for functions, classes, glossary terms and similar pieces of information</li>\n<li><strong>Hierarchical structure</strong>: easy definition of a document tree, with automatic links to siblings, parents and children</li>\n<li><strong>Automatic indices</strong>: general index as well as a module index</li>\n<li><strong>Code handling</strong>: automatic highlighting using the Pygments highlighter</li>\n<li><strong>Extensions</strong>: automatic testing of code snippets, inclusion of docstrings from Python modules, and more</li>\n</ul>\n"
},
{
"answer_id": 59955,
"author": "Allen",
"author_id": 6043,
"author_profile": "https://Stackoverflow.com/users/6043",
"pm_score": 5,
"selected": false,
"text": "<p>Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.</p>\n\n<p>For generating API docs from Python docstrings, the leading tools are <a href=\"https://github.com/BurntSushi/pdoc\" rel=\"noreferrer\">pdoc</a> and <a href=\"https://launchpad.net/pydoctor\" rel=\"noreferrer\">pydoctor</a>. Here's pydoctor's generated API docs for <a href=\"http://twistedmatrix.com/documents/current/api\" rel=\"noreferrer\">Twisted</a> and <a href=\"http://starship.python.net/crew/mwh/bzrlibapi/\" rel=\"noreferrer\">Bazaar</a>.</p>\n\n<p>Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the \"<a href=\"https://docs.python.org/2/library/pydoc.html\" rel=\"noreferrer\">pydoc</a>\" command line tool and as well as the <code>help()</code> function available in the interactive interpreter.</p>\n"
},
{
"answer_id": 497322,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>The <a href=\"https://pypi.python.org/pypi/doxypy/\" rel=\"noreferrer\">doxypy</a> input filter allows you to use pretty much all of Doxygen's formatting tags in a standard Python docstring format. I use it to document a large mixed C++ and Python game application framework, and it's working well.</p>\n"
},
{
"answer_id": 35377654,
"author": "Havok",
"author_id": 439494,
"author_profile": "https://Stackoverflow.com/users/439494",
"pm_score": 5,
"selected": false,
"text": "<p>In the end, you only have two options:</p>\n\n<p>You generate your content using Doxygen, or you generate your content using Sphinx*.</p>\n\n<ol>\n<li><p><strong>Doxygen</strong>: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using <a href=\"https://github.com/Feneric/doxypypy\" rel=\"noreferrer\">doxypypy</a>.</p></li>\n<li><p><strong>Sphinx</strong>: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like). </p>\n\n<ol>\n<li>For manual API documentation you have Sphinx <a href=\"http://www.sphinx-doc.org/en/stable/ext/autodoc.html\" rel=\"noreferrer\">autodoc</a>. This is great to write a user guide with embedded API generated elements.</li>\n<li>For semi-automatic you have Sphinx <a href=\"http://www.sphinx-doc.org/en/stable/ext/autosummary.html\" rel=\"noreferrer\">autosummary</a>. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the <code>autosummary_generate</code> config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.</li>\n<li>Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until <a href=\"http://autoapi.readthedocs.org/\" rel=\"noreferrer\">AutoAPI</a> came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).</li>\n</ol></li>\n</ol>\n\n<p>There are other options to note:</p>\n\n<ul>\n<li><a href=\"https://breathe.readthedocs.org/\" rel=\"noreferrer\">Breathe</a>: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.</li>\n<li><a href=\"https://github.com/twisted/pydoctor\" rel=\"noreferrer\">pydoctor</a>*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.</li>\n</ul>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2077/"
]
| I like Doxygen to create documentation of C or PHP code. I have an upcoming Python project and I think I remember that Python doesn't have `/* .. */` comments, and also has its own self-documentation facility which seems to be the pythonic way to document.
Since I'm familiar with Doxygen, how can I use it to produce my Python documentation? Is there anything in particular that I need to be aware of? | This is [documented on the doxygen website](http://www.doxygen.nl/manual/docblocks.html#pythonblocks), but to summarize here:
You can use doxygen to document your Python code. You can either use the Python documentation string syntax:
```
"""@package docstring
Documentation for this module.
More details.
"""
def func():
"""Documentation for a function.
More details.
"""
pass
```
In which case the comments will be extracted by doxygen, but you won't be able to use any of the [special doxygen commands](http://www.doxygen.nl/manual/commands.html#cmd_intro).
**Or** you can (similar to C-style languages under doxygen) double up the comment marker (`#`) on the first line before the member:
```
## @package pyexample
# Documentation for this module.
#
# More details.
## Documentation for a function.
#
# More details.
def func():
pass
```
In that case, you can use the special doxygen commands. There's no particular Python output mode, but you can apparently improve the results by setting `OPTMIZE_OUTPUT_JAVA` to `YES`.
Honestly, I'm a little surprised at the difference - it seems like once doxygen can detect the comments in ## blocks or """ blocks, most of the work would be done and you'd be able to use the special commands in either case. Maybe they expect people using """ to adhere to more Pythonic documentation practices and that would interfere with the special doxygen commands? |
58,630 | <p>I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).</p>
<p>When I test the e-mail, it gets eaten by my spam filter. One of the things that it's scoring badly on is because of the following problem:</p>
<pre>MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars</pre>
<p>I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem.</p>
<p>Can anyone point me in the right direction?</p>
<p>Thanks!</p>
| [
{
"answer_id": 58667,
"author": "pilif",
"author_id": 5083,
"author_profile": "https://Stackoverflow.com/users/5083",
"pm_score": 4,
"selected": true,
"text": "<p>Quoted printable expands 8 bit characters to \"={HEX-Code}\", thus making the messages longer. Maybe you are just hitting this limit?</p>\n\n<p>Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line.</p>\n\n<p>Or you just encode the email with Base64 - all mail client can handle that.</p>\n\n<p>Or you just set Content-Transfer-Encoding to 8bit and send the data unencoded. I know of no mail server unable to handle 8bit bytes these days.</p>\n"
},
{
"answer_id": 2446877,
"author": "kymg",
"author_id": 293938,
"author_profile": "https://Stackoverflow.com/users/293938",
"pm_score": 2,
"selected": false,
"text": "<p>This is a bug in the implementation of the Quoted-Printable encoding in System.Net.Mail.MailMessage, which has been there for a long time, but is apparently now fixed, as of .Net 4 Beta 2.</p>\n\n<p><a href=\"http://connect.microsoft.com/VisualStudio/feedback/details/156052/mailmessage-body-encoding-quoted-printable-violates-rfcs-soft-line-breaks-requirements\" rel=\"nofollow noreferrer\">http://connect.microsoft.com/VisualStudio/feedback/details/156052/mailmessage-body-encoding-quoted-printable-violates-rfcs-soft-line-breaks-requirements</a></p>\n\n<p>One work-around is to use Base64 encoding instead (even though it would not otherwise be good practice to send a plain-text MIME part in a non-human readable encoding like this). Asking the user of the class to manually split the lines of the message before sending it is not a general solution, as the modified message is not what they wanted to send (e.g. it might include a link which is longer than 76 chars, and so cannot be split). Quoted-Printable can handle messages with lines which are longer than 76 chars <em>before</em> encoding, as long as it is implemented correctly.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
]
| I have written some code in my VB.NET application to send an HTML e-mail (in this case, a lost password reminder).
When I test the e-mail, it gets eaten by my spam filter. One of the things that it's scoring badly on is because of the following problem:
```
MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars
```
I've been through the source of the e-mail, and I've broken each line longer than 76 characters into two lines with a CR+LF in between, but that hasn't fixed the problem.
Can anyone point me in the right direction?
Thanks! | Quoted printable expands 8 bit characters to "={HEX-Code}", thus making the messages longer. Maybe you are just hitting this limit?
Have you tried to break the message at, say, 70 characters? That should provide space for a couple of characters per line.
Or you just encode the email with Base64 - all mail client can handle that.
Or you just set Content-Transfer-Encoding to 8bit and send the data unencoded. I know of no mail server unable to handle 8bit bytes these days. |
58,649 | <p>I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...). </p>
<p>Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks!</p>
| [
{
"answer_id": 58662,
"author": "goldenmean",
"author_id": 2759376,
"author_profile": "https://Stackoverflow.com/users/2759376",
"pm_score": 3,
"selected": false,
"text": "<p>Getting EXIF data from a JPEG image involves:</p>\n\n<ol>\n<li>Seeking to the JPEG markers which mentions the beginning of the EXIF data,. e.g. normally oxFFE1 is the marker inserted while encoding EXIF data, which is a APPlication segment, where EXIF data goes. </li>\n<li>Parse all the data from say 0xFFE1 to 0xFFE2 . This data would be stream of bytes, in the JPEG encoded file. </li>\n<li>ASCII equivalent of these bytes would contain various information related to Image Date, Camera Model Name, Exposure etc...</li>\n</ol>\n"
},
{
"answer_id": 58669,
"author": "idursun",
"author_id": 5984,
"author_profile": "https://Stackoverflow.com/users/5984",
"pm_score": 3,
"selected": false,
"text": "<p>Image class has PropertyItems and PropertyIdList properties. You can use them.</p>\n"
},
{
"answer_id": 156640,
"author": "Dave Griffiths",
"author_id": 15379,
"author_profile": "https://Stackoverflow.com/users/15379",
"pm_score": 6,
"selected": true,
"text": "<p>Check out this <a href=\"https://www.drewnoakes.com/code/exif/\" rel=\"noreferrer\">metadata extractor</a>. <strike>It is written in Java but has also been ported to C#.</strike> I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.</p>\n\n<hr>\n\n<p><strong>EDIT</strong> <em>metadata-extractor</em> supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.</p>\n\n<p>It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...</p>\n\n<pre><code>var directories = ImageMetadataReader.ReadMetadata(imagePath);\n\n// print out all metadata\nforeach (var directory in directories)\nforeach (var tag in directory.Tags)\n Console.WriteLine($\"{directory.Name} - {tag.Name} = {tag.Description}\");\n\n// access the date time\nvar subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();\nvar dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);\n</code></pre>\n\n<p>It's available via <a href=\"https://www.nuget.org/packages/MetadataExtractor/\" rel=\"noreferrer\">NuGet</a> and the <a href=\"https://github.com/drewnoakes/metadata-extractor-dotnet\" rel=\"noreferrer\">code's on GitHub</a>.</p>\n"
},
{
"answer_id": 636622,
"author": "Joel in Gö",
"author_id": 6091,
"author_profile": "https://Stackoverflow.com/users/6091",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a link to another <a href=\"https://stackoverflow.com/questions/280003/how-do-i-retrieve-the-properties-of-a-photo-taken-on-a-digital-camera-using-net/636606#636606\">similar SO question</a>, which has an answer pointing to this good article on <a href=\"http://www.vsj.co.uk/dotnet/display.asp?id=649\" rel=\"nofollow noreferrer\">\"Reading, writing and photo metadata\"</a> in .Net.</p>\n"
},
{
"answer_id": 1268857,
"author": "Jan Zich",
"author_id": 15716,
"author_profile": "https://Stackoverflow.com/users/15716",
"pm_score": 6,
"selected": false,
"text": "<p>As suggested, you can use some 3rd party library, or do it manually (which is not that much work), but the simplest and the most flexible is to perhaps use the built-in functionality in .NET. For more see:</p>\n\n<ul>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.image.propertyitems.aspx\" rel=\"noreferrer\">System.Drawing.Image.PropertyItems</a> Property</p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/system.drawing.imaging.propertyitem.aspx\" rel=\"noreferrer\">System.Drawing.Imaging.PropertyItem</a> Class </p></li>\n<li><p><a href=\"http://msdn.microsoft.com/en-us/library/xddt0dz7.aspx\" rel=\"noreferrer\">How to: Read Image Metadata</a></p></li>\n</ul>\n\n<p>I say \"it’s the most flexible\" because .NET does not try to interpret or coalesce the data in any way. For each EXIF you basically get an array of bytes. This may be good or bad depending on how much control you actually want.</p>\n\n<p>Also, I should point out that the property list does not in fact directly correspond to the EXIF values. EXIF itself is stored in multiple tables with overlapping ID’s, but .NET puts everything in one list and redefines ID’s of some items. But as long as you don’t care about the precise EXIF ID’s, you should be fine with the .NET mapping.</p>\n\n<hr>\n\n<p><strong>Edit:</strong> It's possible to do it without loading the full image following this answer: <a href=\"https://stackoverflow.com/a/552642/2097240\">https://stackoverflow.com/a/552642/2097240</a></p>\n"
},
{
"answer_id": 7887165,
"author": "smola",
"author_id": 205607,
"author_profile": "https://Stackoverflow.com/users/205607",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <a href=\"https://github.com/mono/taglib-sharp\">TagLib#</a> which is used by applications such as <a href=\"http://f-spot.org/\">F-Spot</a>. Besides Exif, it will read a good amount of metadata formats for image, audio and video.</p>\n\n<p>I also like <a href=\"https://code.google.com/p/exif-utils/\">ExifUtils</a> API but it is buggy and is not actively developed.</p>\n"
},
{
"answer_id": 9123026,
"author": "Kirk Broadhurst",
"author_id": 146077,
"author_profile": "https://Stackoverflow.com/users/146077",
"pm_score": 2,
"selected": false,
"text": "<p>The command line tool <a href=\"http://www.sno.phy.queensu.ca/~phil/exiftool/\" rel=\"nofollow\">ExifTool by Phil Harvey</a> works with dozens of images formats - including plenty of proprietary RAW formats - and can manipulate a variety of metadata formats including EXIF, GPS, IPTC, XMP, JFIF.</p>\n\n<p>Very easy to use, lightweight, impressive application.</p>\n"
},
{
"answer_id": 63352062,
"author": "Shoaib Khan",
"author_id": 11795958,
"author_profile": "https://Stackoverflow.com/users/11795958",
"pm_score": 0,
"selected": false,
"text": "<p>Recently, I used this <a href=\"https://products.groupdocs.com/metadata/net\" rel=\"nofollow noreferrer\">.NET Metadata API</a>. I have also written a <a href=\"https://blog.groupdocs.com/2020/05/13/manage-exif-data-in-csharp-net-for-jpeg-png-tiff-webp-images/\" rel=\"nofollow noreferrer\">blog post</a> about it, that shows reading, updating, and removing the EXIF data from images using C#.</p>\n<pre><code>using (Metadata metadata = new Metadata("image.jpg"))\n{\n IExif root = metadata.GetRootPackage() as IExif;\n if (root != null && root.ExifPackage != null)\n {\n Console.WriteLine(root.ExifPackage.DateTime);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 74401570,
"author": "Gray Programmerz",
"author_id": 14919621,
"author_profile": "https://Stackoverflow.com/users/14919621",
"pm_score": 0,
"selected": false,
"text": "<p>fastest way is to use <a href=\"https://www.nuget.org/packages/WindowsAPICodePack-Shell/\" rel=\"nofollow noreferrer\">windows api codec</a> that doesn't open file and instead uses cached exif information</p>\n<pre><code>var prop = ShellFile.FromFilePath(f).Properties;\nvar Dimensions = prop.GetProperty("Dimensions").ValueAsObject.ToString(); \n//1280 x 800\n\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58649",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6091/"
]
| I would like to write a small program in C# which goes through my jpeg photos and, for example, sorts them into dated folders (using MY dating conventions, dammit...).
Does anyone know a relatively easy way to get at the EXIF data such as Date And Time or Exposure programatically?
Thanks! | Check out this [metadata extractor](https://www.drewnoakes.com/code/exif/). It is written in Java but has also been ported to C#. I have used the Java version to write a small utility to rename my jpeg files based on the date and model tags. Very easy to use.
---
**EDIT** *metadata-extractor* supports .NET too. It's a very fast and simple library for accessing metadata from images and videos.
It fully supports Exif, as well as IPTC, XMP and many other types of metadata from file types including JPEG, PNG, GIF, PNG, ICO, WebP, PSD, ...
```
var directories = ImageMetadataReader.ReadMetadata(imagePath);
// print out all metadata
foreach (var directory in directories)
foreach (var tag in directory.Tags)
Console.WriteLine($"{directory.Name} - {tag.Name} = {tag.Description}");
// access the date time
var subIfdDirectory = directories.OfType<ExifSubIfdDirectory>().FirstOrDefault();
var dateTime = subIfdDirectory?.GetDateTime(ExifDirectoryBase.TagDateTime);
```
It's available via [NuGet](https://www.nuget.org/packages/MetadataExtractor/) and the [code's on GitHub](https://github.com/drewnoakes/metadata-extractor-dotnet). |
58,670 | <p>Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher?
Open CD tray exists, but I can't seem to make it close especially under W2k. </p>
<p>I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK.</p>
| [
{
"answer_id": 58678,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.nirsoft.net/utils/nircmd.html\" rel=\"nofollow noreferrer\">Nircmd</a> is a very handy freeware command line utility with various options, including opening and closing the CD tray.</p>\n"
},
{
"answer_id": 58725,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 4,
"selected": true,
"text": "<p>Here is an easy way using the Win32 API:</p>\n\n<pre><code>\n[DllImport(\"winmm.dll\", EntryPoint = \"mciSendStringA\", CharSet = CharSet.Ansi)]\n protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback);\n\n public void OpenCloseCD(bool Open)\n {\n if (Open)\n {\n mciSendString(\"set cdaudio door open\", null, 0, IntPtr.Zero);\n }\n else\n {\n mciSendString(\"set cdaudio door closed\", null, 0, IntPtr.Zero);\n }\n}\n\n</code></pre>\n"
},
{
"answer_id": 77291,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 4,
"selected": false,
"text": "<p>I kind of like to use DeviceIOControl as it gives me the possibility to eject any kind of removable drive (such as USB and flash-disks as well as CD trays). Da codez to properly eject a disk using DeviceIOControl is (just add proper error-handling):</p>\n\n<pre><code>bool ejectDisk(TCHAR driveLetter)\n{\n TCHAR tmp[10];\n _stprintf(tmp, _T(\"\\\\\\\\.\\\\%c:\"), driveLetter);\n HANDLE handle = CreateFile(tmp, GENERIC_READ, FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);\n DWORD bytes = 0;\n DeviceIoControl(handle, FSCTL_LOCK_VOLUME, 0, 0, 0, 0, &bytes, 0);\n DeviceIoControl(handle, FSCTL_DISMOUNT_VOLUME, 0, 0, 0, 0, &bytes, 0);\n DeviceIoControl(handle, IOCTL_STORAGE_EJECT_MEDIA, 0, 0, 0, 0, &bytes, 0);\n CloseHandle(handle);\n return true;\n}\n</code></pre>\n"
},
{
"answer_id": 30512979,
"author": "James Johnston",
"author_id": 562766,
"author_profile": "https://Stackoverflow.com/users/562766",
"pm_score": 3,
"selected": false,
"text": "<p>I noticed that Andreas Magnusson's answer didn't quite work exactly the same as Explorer's 'Eject' button did. Specifically, the drive wasn't grayed out in Explorer using Andreas' code, but was if you used the Eject command. So I did some investigating.</p>\n<p>I ran API Monitor while running the Eject command from Explorer (Windows 7 SP1 64-bit). I also found a good (now-defunct) MSKB article 165721 titled <a href=\"http://web.archive.org/web/20150511141059/https://support.microsoft.com/en-us/kb/165721\" rel=\"nofollow noreferrer\" title=\"How To Ejecting Removable Media in Windows NT/Windows 2000/Windows XP\">How To Ejecting Removable Media in Windows NT/Windows 2000/Windows XP</a>. The most interesting part of the article is quoted below:</p>\n<blockquote>\n<ol>\n<li>Call CreateFile with GENERIC_READ|GENERIC_WRITE, FILE_SHARE_READ|FILE_SHARE_WRITE, and OPEN_EXISTING. The lpFileName parameter should be \\\\.\\X: (where X is the real drive letter). All other parameters can be zero.</li>\n<li>Lock the volume by issuing the FSCTL_LOCK_VOLUME IOCTL via DeviceIoControl. If any other application or the system is using the volume, this IOCTL fails. Once this function returns successfully, the application is guaranteed that the volume is not used by anything else in the system.</li>\n<li>Dismount the volume by issuing the FSCTL_DISMOUNT_VOLUME IOCTL. This causes the file system to remove all knowledge of the volume and to discard any internal information that it keeps regarding the volume.</li>\n<li>Make sure the media can be removed by issuing the IOCTL_STORAGE_MEDIA_REMOVAL IOCTL. Set the PreventMediaRemoval member of the PREVENT_MEDIA_REMOVAL structure to FALSE before calling this IOCTL. This stops the device from preventing the removal of the media.</li>\n<li>Eject the media with the IOCTL_STORAGE_EJECT_MEDIA IOCTL. If the device doesn't allow automatic ejection, then IOCTL_STORAGE_EJECT_MEDIA can be skipped and the user can be instructed to remove the media.</li>\n<li>Close the volume handle obtained in the first step or issue the FSCTL_UNLOCK_VOLUME IOCTL. This allows the drive to be used by other\nprocesses.</li>\n</ol>\n</blockquote>\n<p>Andreas's answer, the MSKB article, and my API sniffing of Explorer can be summarized as follows:</p>\n<ol>\n<li><code>CreateFile</code> called to open the volume. (All methods).</li>\n<li><code>DeviceIoControl</code> called with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364575%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>FSCTL_LOCK_VOLUME</code></a>. (All methods).</li>\n<li><code>DeviceIoControl</code> called with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa364562%28v=vs.85%29.aspx\" rel=\"nofollow noreferrer\"><code>FSCTL_DISMOUNT_VOLUME</code></a>. (Andreas's and MSKB methods only. Explorer does not call this for some reason. This IOCTL seems to be what affects whether the drive is grayed out in Explorer or not. I am not sure why Explorer doesn't call this).</li>\n<li><code>DeviceIoControl</code> called with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa363416(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>IOCTL_STORAGE_MEDIA_REMOVAL</code></a> and <code>PREVENT_MEDIA_REMOVAL</code> member set to <code>FALSE</code> (MSKB and Explorer methods. This step is missing from Andreas's answer).</li>\n<li><code>DeviceIoControl</code> called with <a href=\"https://msdn.microsoft.com/en-us/library/windows/desktop/aa363406(v=vs.85).aspx\" rel=\"nofollow noreferrer\"><code>IOCTL_STORAGE_EJECT_MEDIA</code></a> (Andreas and MSKB article) or <code>IOCTL_DISK_EJECT_MEDIA</code> (Explorer; note this IOCTL was obsoleted and replaced with the STORAGE IOCTL. Not sure why Explorer still uses the old one).</li>\n</ol>\n<p>To conclude, I decided to follow the procedure outlined in the MSKB article, as it seemed to be the most thorough and complete procedure, backed up with an MSKB article.</p>\n"
},
{
"answer_id": 32371540,
"author": "Slion",
"author_id": 3969362,
"author_profile": "https://Stackoverflow.com/users/3969362",
"pm_score": 1,
"selected": false,
"text": "<p>To close the drive tray do as described <a href=\"https://stackoverflow.com/a/30512979/3969362\">here</a> but instead of using DeviceIoControl with IOCTL_STORAGE_EJECT_MEDIA you need to call DeviceIoControl with IOCTL_STORAGE_LOAD_MEDIA.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3225/"
]
| Does anyone know a method to programmatically close the CD tray on Windows 2000 or higher?
Open CD tray exists, but I can't seem to make it close especially under W2k.
I am especially looking for a method to do this from a batch file, if possible, but API calls would be OK. | Here is an easy way using the Win32 API:
```
[DllImport("winmm.dll", EntryPoint = "mciSendStringA", CharSet = CharSet.Ansi)]
protected static extern int mciSendString(string lpstrCommand,StringBuilder lpstrReturnString,int uReturnLength,IntPtr hwndCallback);
public void OpenCloseCD(bool Open)
{
if (Open)
{
mciSendString("set cdaudio door open", null, 0, IntPtr.Zero);
}
else
{
mciSendString("set cdaudio door closed", null, 0, IntPtr.Zero);
}
}
``` |
58,697 | <p>The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort.</p>
<p>I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:*.* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often.</p>
<p>What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch. </p>
<p>Does anyone know of a way to do this? </p>
| [
{
"answer_id": 58700,
"author": "Edward Wilde",
"author_id": 5182,
"author_profile": "https://Stackoverflow.com/users/5182",
"pm_score": 4,
"selected": false,
"text": "<p>I find RoboCopy is a good alternative to xcopy. It supports high latency connections much better and supports resuming a copy.</p>\n\n<h3>References</h3>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Robocopy\" rel=\"noreferrer\">Wikipedia - robocopy</a></p>\n\n<h3>Downloads</h3>\n\n<p><strong>Edit</strong> Robocopy was introduced as a standard feature of Windows Vista and Windows Server 2008.</p>\n\n<ul>\n<li><p>Robocopy is shipped as part of the Windows Server 2003 resource kit and can be download from the <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=9d467a69-57ff-4ae7-96ee-b18c4790cffd&displaylang=en\" rel=\"noreferrer\">Microsoft download site</a>.</p></li>\n<li><p>A very simple GUI has also been release for RoboCopy on technet <a href=\"http://technet.microsoft.com/en-us/magazine/cc160891.aspx\" rel=\"noreferrer\">http://technet.microsoft.com/en-us/magazine/cc160891.aspx</a></p></li>\n</ul>\n"
},
{
"answer_id": 58708,
"author": "Raynet",
"author_id": 4294,
"author_profile": "https://Stackoverflow.com/users/4294",
"pm_score": 0,
"selected": false,
"text": "<p>I would suggest using <a href=\"http://optics.ph.unimelb.edu.au/help/rsync/rsync_pc1.html\" rel=\"nofollow noreferrer\">rsync</a>, several ports are available, but <a href=\"http://www.itefix.no/i2/node/10650\" rel=\"nofollow noreferrer\">cwrsync</a> seems to work nicely on Windows.</p>\n"
},
{
"answer_id": 58714,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a big fan of <a href=\"http://www.codesector.com/teracopy.php\" rel=\"nofollow noreferrer\">TeraCopy</a>. </p>\n"
},
{
"answer_id": 58715,
"author": "Swaroop C H",
"author_id": 4869,
"author_profile": "https://Stackoverflow.com/users/4869",
"pm_score": 0,
"selected": false,
"text": "<p>How about <a href=\"http://www.cis.upenn.edu/~bcpierce/unison/\" rel=\"nofollow noreferrer\">unison</a>?</p>\n"
},
{
"answer_id": 58729,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 4,
"selected": true,
"text": "<p>/D may be what you are looking for. I find it works quite fast for backing-up as existing files are not copied.</p>\n\n<pre><code>xcopy \"O:\\*.*\" N:\\Whatever /C /D /S /H \n\n/C Continues copying even if errors occur. \n/D:m-d-y Copies files changed on or after the specified date. \n If no date is given, copies only those files whose source time \n is newer than the destination time. \n/S Copies directories and subdirectories except empty ones. \n/H Copies hidden and system files also. \n</code></pre>\n\n<p>More information: <a href=\"http://www.computerhope.com/xcopyhlp.htm\" rel=\"noreferrer\">http://www.computerhope.com/xcopyhlp.htm</a></p>\n"
},
{
"answer_id": 58799,
"author": "Tall Jeff",
"author_id": 1553,
"author_profile": "https://Stackoverflow.com/users/1553",
"pm_score": 2,
"selected": false,
"text": "<p>It was not clear if you only wanted a command line tool, but Microsoft's free <a href=\"http://en.wikipedia.org/wiki/SyncToy\" rel=\"nofollow noreferrer\">SyncToy</a> program is great for maintaining a replication between a pair of volumes. It supports pushing changes in either or both directions. That is, it support several different types of replication modes.</p>\n"
},
{
"answer_id": 3719487,
"author": "Christopher Horenstein",
"author_id": 332815,
"author_profile": "https://Stackoverflow.com/users/332815",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.scootersoftware.com/index.php\" rel=\"nofollow noreferrer\">Beyond Compare 3</a> is the best utility I've seen for things like this. It makes everything really easy to assess, and really easy to manipulate.</p>\n"
},
{
"answer_id": 5280698,
"author": "Loren",
"author_id": 656316,
"author_profile": "https://Stackoverflow.com/users/656316",
"pm_score": 1,
"selected": false,
"text": "<p>XcopyGUI. A small, standalone GUI front-end for xcopy. Free. <a href=\"http://lorenstuff.weebly.com/\" rel=\"nofollow\">http://lorenstuff.weebly.com/</a></p>\n"
},
{
"answer_id": 10194265,
"author": "rud3y",
"author_id": 1010904,
"author_profile": "https://Stackoverflow.com/users/1010904",
"pm_score": 1,
"selected": false,
"text": "<pre><code>robocopy c:\\sourceDirectory\\*.* d:\\destinationDirectory\\*.* /R:5 /W:3 /Z /XX /TEE\n</code></pre>\n\n<p>This will work for your alternative to xCopy... best method imho</p>\n\n<p>Good luck!</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2757/"
]
| The situation: I have a pieceofcrapuous laptop. One of the things that make it pieceofcrapuous is that the battery is dead, and the power cable pulls out of the back with little effort.
I recently received a non-pieceofcrapuous laptop, and I am in the process of copying everything from old to new. I'm trying to xcopy c:\*.\* from the old machine to an external hard drive, but because the cord pulls out so frequently, the xcopy is interrupted fairly often.
What I need is a switch in XCopy that will copy eveything except for files that already exist in the destination folder -- the exact opposite of the behavior of the /U switch.
Does anyone know of a way to do this? | /D may be what you are looking for. I find it works quite fast for backing-up as existing files are not copied.
```
xcopy "O:\*.*" N:\Whatever /C /D /S /H
/C Continues copying even if errors occur.
/D:m-d-y Copies files changed on or after the specified date.
If no date is given, copies only those files whose source time
is newer than the destination time.
/S Copies directories and subdirectories except empty ones.
/H Copies hidden and system files also.
```
More information: <http://www.computerhope.com/xcopyhlp.htm> |
58,709 | <p>I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?</p>
<p>I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals.</p>
| [
{
"answer_id": 58716,
"author": "Eric Z Beard",
"author_id": 1219,
"author_profile": "https://Stackoverflow.com/users/1219",
"pm_score": 3,
"selected": false,
"text": "<p>You can either log to a table, by simply inserting a new row, or you can implement a CLR stored procedure to write to a file.</p>\n\n<p>Be careful with writing to a table, because if the action happens in a transaction and the transaction gets rolled back, your log entry will disappear.</p>\n"
},
{
"answer_id": 58719,
"author": "Unsliced",
"author_id": 2902,
"author_profile": "https://Stackoverflow.com/users/2902",
"pm_score": 3,
"selected": false,
"text": "<p>Logging from inside a SQL sproc would be better done to the database itself. T-SQL can write to files but it's not really designed for it. </p>\n"
},
{
"answer_id": 58722,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": 3,
"selected": false,
"text": "<p>I think writing to a log table would be my preference.</p>\n\n<p>Alternatively, as you are using 2005, you could write a simple SQLCLR procedure to wrap around the EventLog.</p>\n\n<p>Or you could use <strong>xp_logevent</strong> if you wanted to write to SQL log</p>\n"
},
{
"answer_id": 58723,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "<p>There's the <a href=\"http://msdn.microsoft.com/en-us/library/ms176047%28SQL.90%29.aspx\" rel=\"nofollow noreferrer\">PRINT</a> command, but I prefer logging into a table so you can query it.</p>\n"
},
{
"answer_id": 59017,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 0,
"selected": false,
"text": "<p>You could use output variables for passing back messages, but that relies on the proc executing without errors.</p>\n\n<pre><code>create procedure usp_LoggableProc \n\n@log varchar(max) OUTPUT \n\nas\n\n-- T-SQL statement here ...\n\nselect @log = @log + 'X is foo'\n</code></pre>\n\n<p>And then in your ADO code somehwere:</p>\n\n<pre><code>string log = (string)SqlCommand.Parameters[\"@log\"].Value;\n</code></pre>\n\n<p>You could use raiserror to create your own custom errors with the information that you require and that will be available to you through the usual SqlException Errors collection in your ADO code:</p>\n\n<pre><code>RAISERROR('X is Foo', 10, 1)\n</code></pre>\n\n<p>Hmmm but yeah, can't help feeling just for debugging and in your situation, just insert varchar messages to an error table like the others have suggested and select * from it when you're debugging.</p>\n"
},
{
"answer_id": 172808,
"author": "Pittsburgh DBA",
"author_id": 10224,
"author_profile": "https://Stackoverflow.com/users/10224",
"pm_score": 1,
"selected": false,
"text": "<p>You can write rows to a log table from within a stored procedure. As others have indicated, you could go out of your way to write to some text file or other log with CLR or xp_logevent, but it seems like you need more volume than would be practical for such uses.</p>\n\n<p>The tough cases occur (and it's these that you really need your log for) when transactions fail. Since any logging that occurs during these transactions will be rolled back along with the transaction that they are part of, it is best to have a logging API that your clients can use to log errors. This can be a simple DAL that either logs to the same database, or to a shared one.</p>\n"
},
{
"answer_id": 545415,
"author": "Jonas Engman",
"author_id": 4164,
"author_profile": "https://Stackoverflow.com/users/4164",
"pm_score": 4,
"selected": true,
"text": "<p>I solved this by writing a SQLCLR-procedure as Eric Z Beard suggested. The assembly must be signed with a strong name key file.</p>\n\n<pre><code>using System;\nusing System.Data;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class StoredProcedures\n{\n [Microsoft.SqlServer.Server.SqlProcedure]\n public static int Debug(string s)\n {\n System.Diagnostics.Debug.WriteLine(s);\n return 0;\n }\n }\n}\n</code></pre>\n\n<p>Created a key and a login:</p>\n\n<pre><code>USE [master]\nCREATE ASYMMETRIC KEY DebugProcKey FROM EXECUTABLE FILE =\n'C:\\..\\SqlServerProject1\\bin\\Debug\\SqlServerProject1.dll'\n\nCREATE LOGIN DebugProcLogin FROM ASYMMETRIC KEY DebugProcKey \n\nGRANT UNSAFE ASSEMBLY TO DebugProcLogin \n</code></pre>\n\n<p>Imported it into SQL Server:</p>\n\n<pre><code>USE [mydb]\nCREATE ASSEMBLY SqlServerProject1 FROM\n'C:\\..\\SqlServerProject1\\bin\\Debug\\SqlServerProject1.dll' \nWITH PERMISSION_SET = unsafe\n\nCREATE FUNCTION dbo.Debug( @message as nvarchar(200) )\nRETURNS int\nAS EXTERNAL NAME SqlServerProject1.[StoredProcedures].Debug\n</code></pre>\n\n<p>Then I was able to log in T-SQL procedures using</p>\n\n<pre><code>exec Debug @message = 'Hello World'\n</code></pre>\n"
},
{
"answer_id": 1765319,
"author": "Steve D",
"author_id": 214836,
"author_profile": "https://Stackoverflow.com/users/214836",
"pm_score": 1,
"selected": false,
"text": "<p><em>For what it's worth, I've found that when I don't assign an InfoMessage handler to my SqlConnection:</em></p>\n\n<pre><code>sqlConnection.InfoMessage += new SqlInfoMessageEventHandler(MySqlConnectionInfoMessageHandler);\n</code></pre>\n\n<p><em>where the signature of the InfoMessageHandler looks like this:</em></p>\n\n<pre><code>MySqlConnectionInfoMessageHandler(object sender, SqlInfoMessageEventArgs e)\n</code></pre>\n\n<p><em>then my PRINT statements in my Stored Procs do not appear in DbgView.</em></p>\n"
},
{
"answer_id": 1905922,
"author": "Daniel Pavic",
"author_id": 231908,
"author_profile": "https://Stackoverflow.com/users/231908",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to check <a href=\"http://log4tsql.codeplex.com/\" rel=\"nofollow noreferrer\" title=\"Raycoon Log4TSQL\">Log4TSQL</a>. It provides Database-Logging for Stored Procedures and Triggers in SQL Server 2005 - 2008. You have the possibility to set separate, independent log-levels on a per Procedure/Trigger basis.</p>\n"
},
{
"answer_id": 60612988,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use cmd commands with cmdshell</p>\n\n<p>I found this while searching for an answer to this question.\n<a href=\"https://www.databasejournal.com/features/mssql/article.php/1467601/A-general-logging-t-sql-process-to-write-to-txt-files.htm\" rel=\"nofollow noreferrer\">https://www.databasejournal.com/features/mssql/article.php/1467601/A-general-logging-t-sql-process-to-write-to-txt-files.htm</a></p>\n\n<pre><code>select @cmdtxt = \"echo \" + @logEntry + \" >> drive:\\path\\filename.txt\"\nexec master..xp_cmdshell @cmdtxt\n</code></pre>\n"
},
{
"answer_id": 69202552,
"author": "Curt",
"author_id": 1754010,
"author_profile": "https://Stackoverflow.com/users/1754010",
"pm_score": 0,
"selected": false,
"text": "<p>I've been searching for a way to do this, as I am trying to debug some complicated, chained, stored procedures, all that are called by an external API, and which operate in the context of a transaction.</p>\n<p>I'd been writing diagnostic messages into a logging file, but if the transaction rolls back, the new log entries disappear with the rollback. I found a way! And it works pretty well. And it has already saved me many, many hours of debugging time.</p>\n<ol>\n<li><p>Create a linked server to the same SQL instance, using the login's\nsecurity context. In my case, the simplest method was to use the\nlocalhost loop address, 127.0.0.1</p>\n</li>\n<li><p>Set the linked server to enable RPC, and to NOT "Enable Promotion of\nDistributed Transactions". This means that calls through that\nserver will take place outside of your transaction context.</p>\n</li>\n<li><p>In your logging procedure, (I have an example excerpted below) write\nto the log table using the procedure through loopback linked server\nif you are in a transaction. You can write to it the usual way\nif your are not. Writing though the linked server is considerably\nslower than direct DML.</p>\n</li>\n</ol>\n<p>Voila! My in-process logging survives the rollback, and I can find out what's happening internally when things are going south.</p>\n<p>I can't claim credit for thinking of this--I found the approach after some time with Google, but I'm so pleased with the result I felt like I had to share it.</p>\n<pre><code>USE TX\nGO\n\nCREATE PROCEDURE dbo.LogError(@errorSource Varchar(32), @msg Varchar(400))\nAS BEGIN\n SET NOCOUNT ON\n IF @@TRANCOUNT > 0 \n EXEC [127.0.0.1].TX.dbo.LogError @errorSource, @msg \n ELSE\n INSERT INTO TX.dbo.ErrorLog(source_module, message)\n SELECT @errorSource, @msg\n END\n GO\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58709",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4164/"
]
| I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?
I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit messages to DebugView from SysInternals. | I solved this by writing a SQLCLR-procedure as Eric Z Beard suggested. The assembly must be signed with a strong name key file.
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServer.Server.SqlProcedure]
public static int Debug(string s)
{
System.Diagnostics.Debug.WriteLine(s);
return 0;
}
}
}
```
Created a key and a login:
```
USE [master]
CREATE ASYMMETRIC KEY DebugProcKey FROM EXECUTABLE FILE =
'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll'
CREATE LOGIN DebugProcLogin FROM ASYMMETRIC KEY DebugProcKey
GRANT UNSAFE ASSEMBLY TO DebugProcLogin
```
Imported it into SQL Server:
```
USE [mydb]
CREATE ASSEMBLY SqlServerProject1 FROM
'C:\..\SqlServerProject1\bin\Debug\SqlServerProject1.dll'
WITH PERMISSION_SET = unsafe
CREATE FUNCTION dbo.Debug( @message as nvarchar(200) )
RETURNS int
AS EXTERNAL NAME SqlServerProject1.[StoredProcedures].Debug
```
Then I was able to log in T-SQL procedures using
```
exec Debug @message = 'Hello World'
``` |
58,711 | <p>I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:</p>
<pre><code>Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
</code></pre>
<p>This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C* library (In the case of GTK, Tk, wx, QT etc etc)</p>
<p>Shoes takes things from web devlopment (like <code>#f0c2f0</code> style colour notation, CSS layout techniques, like <code>:margin => 10</code>), and from ruby (extensively using blocks in sensible ways)</p>
<p>Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:</p>
<pre><code>def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
</code></pre>
<p>No where near as clean, and wouldn't be <em>nearly</em> as flexible, and I'm not even sure if it would be implementable.</p>
<p>Using decorators seems like an interesting way to map blocks of code to a specific action:</p>
<pre><code>class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
</code></pre>
<p>Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.</p>
<p>The scope of various stuff (say, the <code>la</code> label in the above example) could be rather complicated, but it seems doable in a fairly neat manner..</p>
| [
{
"answer_id": 58917,
"author": "Justin Voss",
"author_id": 5616,
"author_profile": "https://Stackoverflow.com/users/5616",
"pm_score": 4,
"selected": true,
"text": "<p>You could actually pull this off, but it would require using metaclasses, which are <em>deep</em> magic (there be dragons). If you want an intro to metaclasses, there's a series of <a href=\"http://www.ibm.com/developerworks/linux/library/l-pymeta.html\" rel=\"nofollow noreferrer\">articles from IBM</a> which manage to introduce the ideas without melting your brain.</p>\n\n<p>The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax.</p>\n"
},
{
"answer_id": 58990,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 2,
"selected": false,
"text": "<p>Maybe not as slick as the Ruby version, but how about something like this:</p>\n\n<pre><code>from Boots import App, Para, Button, alert\n\ndef Shoeless(App):\n t = Para(text = 'Not Clicked')\n b = Button(label = 'The label')\n\n def on_b_clicked(self):\n alert('You clicked the button!')\n self.t.text = 'Clicked!'\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/58711/how-would-you-design-a-very-pythonic-ui-framework#58917\">Like Justin said</a>, to implement this you would need to use a custom metaclass on class <code>App</code>, and a bunch of properties on <code>Para</code> and <code>Button</code>. This actually wouldn't be too hard.</p>\n\n<p>The problem you run into next is: how do you keep track of the <em>order</em> that things appear in the class definition? In Python 2.x, there is no way to know if <code>t</code> should be above <code>b</code> or the other way around, since you receive the contents of the class definition as a python <code>dict</code>.</p>\n\n<p>However, in Python 3.0 <a href=\"http://www.python.org/dev/peps/pep-3115/\" rel=\"nofollow noreferrer\">metaclasses are being changed</a> in a couple of (minor) ways. One of them is the <code>__prepare__</code> method, which allows you to supply your own custom dictionary-like object to be used instead -- this means you'll be able to track the order in which items are defined, and position them accordingly in the window.</p>\n"
},
{
"answer_id": 60563,
"author": "Toni Ruža",
"author_id": 6267,
"author_profile": "https://Stackoverflow.com/users/6267",
"pm_score": 2,
"selected": false,
"text": "<p>This could be an oversimplification, i don't think it would be a good idea to try to make a general purpose ui library this way. On the other hand you could use this approach (metaclasses and friends) to simplify the definition of certain classes of user interfaces for an existing ui library and depending of the application that could actually save you a significant amount of time and code lines.</p>\n"
},
{
"answer_id": 62780,
"author": "A Nony Mouse",
"author_id": 7182,
"author_profile": "https://Stackoverflow.com/users/7182",
"pm_score": 2,
"selected": false,
"text": "<p>With some Metaclass magic to keep the ordering I have the following working. I'm not sure how pythonic it is but it is good fun for creating simple things. </p>\n\n<pre><code>class w(Wndw):\n title='Hello World'\n class txt(Txt): # either a new class\n text='Insert name here'\n lbl=Lbl(text='Hello') # or an instance\n class greet(Bbt):\n text='Greet'\n def click(self): #on_click method\n self.frame.lbl.text='Hello %s.'%self.frame.txt.text\n\napp=w()\n</code></pre>\n"
},
{
"answer_id": 334828,
"author": "Alcides",
"author_id": 28516,
"author_profile": "https://Stackoverflow.com/users/28516",
"pm_score": 1,
"selected": false,
"text": "<p>I have this same problem. I wan to to create a wrapper around any GUI toolkit for Python that is easy to use, and inspired by Shoes, but needs to be a OOP approach (against ruby blocks).</p>\n\n<p>More information in: <a href=\"http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited\" rel=\"nofollow noreferrer\">http://wiki.alcidesfonseca.com/blog/python-universal-gui-revisited</a></p>\n\n<p>Anyone's welcome to join the project.</p>\n"
},
{
"answer_id": 334938,
"author": "llimllib",
"author_id": 42559,
"author_profile": "https://Stackoverflow.com/users/42559",
"pm_score": 2,
"selected": false,
"text": "<p>The only attempt to do this that I know of is <a href=\"http://zephyrfalcon.org/labs/dope_on_wax.html\" rel=\"nofollow noreferrer\">Hans Nowak's Wax</a> (which is unfortunately dead).</p>\n"
},
{
"answer_id": 335077,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>The closest you can get to rubyish blocks is the with statement from pep343: </p>\n\n<p><a href=\"http://www.python.org/dev/peps/pep-0343/\" rel=\"nofollow noreferrer\">http://www.python.org/dev/peps/pep-0343/</a></p>\n"
},
{
"answer_id": 335132,
"author": "Kris Kowal",
"author_id": 42586,
"author_profile": "https://Stackoverflow.com/users/42586",
"pm_score": 2,
"selected": false,
"text": "<p>I was never satisfied with David Mertz's articles at IBM on metaclsses so I recently wrote my own <a href=\"http://askawizard.blogspot.com/2008/09/metaclasses-python-saga-part-4_30.html\" rel=\"nofollow noreferrer\">metaclass article</a>. Enjoy.</p>\n"
},
{
"answer_id": 335358,
"author": "liori",
"author_id": 42610,
"author_profile": "https://Stackoverflow.com/users/42610",
"pm_score": 1,
"selected": false,
"text": "<p>If you really want to code UI, you could try to get something similar to django's ORM; sth like this to get a simple help browser:</p>\n\n<pre><code>class MyWindow(Window):\n class VBox:\n entry = Entry()\n bigtext = TextView()\n\n def on_entry_accepted(text):\n bigtext.value = eval(text).__doc__\n</code></pre>\n\n<p>The idea would be to interpret some containers (like windows) as simple classes, some containers (like tables, v/hboxes) recognized by object names, and simple widgets as objects.</p>\n\n<p>I dont think one would have to name all containers inside a window, so some shortcuts (like old-style classes being recognized as widgets by names) would be desirable.</p>\n\n<p>About the order of elements: in MyWindow above you don't have to track this (window is conceptually a one-slot container). In other containers you can try to keep track of the order assuming that each widget constructor have access to some global widget list. This is how it is done in django (AFAIK).</p>\n\n<p>Few hacks here, few tweaks there... There are still few things to think of, but I believe it is possible... and usable, as long as you don't build complicated UIs.</p>\n\n<p>However I am pretty happy with PyGTK+Glade. UI is just kind of data for me and it should be treated as data. There's just too much parameters to tweak (like spacing in different places) and it is better to manage that using a GUI tool. Therefore I build my UI in glade, save as xml and parse using gtk.glade.XML().</p>\n"
},
{
"answer_id": 335400,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 0,
"selected": false,
"text": "<p>Declarative is not necessarily more (or less) pythonic than functional IMHO. I think a layered approach would be the best (from buttom up):</p>\n\n<ol>\n<li>A native layer that accepts and returns python data types.</li>\n<li>A functional dynamic layer.</li>\n<li>One or more declarative/object-oriented layers.</li>\n</ol>\n\n<p>Similar to <a href=\"http://elixir.ematia.de/trac/wiki\" rel=\"nofollow noreferrer\">Elixir</a> + <a href=\"http://www.sqlalchemy.org/\" rel=\"nofollow noreferrer\">SQLAlchemy</a>.</p>\n"
},
{
"answer_id": 335443,
"author": "Suraj",
"author_id": 39446,
"author_profile": "https://Stackoverflow.com/users/39446",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I would try to implement <a href=\"http://docs.jquery.com/Main_Page\" rel=\"nofollow noreferrer\">JQuery</a> like API in a GUI framework.</p>\n\n<pre><code>class MyWindow(Window):\n contents = (\n para('Hello World!'),\n button('Click Me', id='ok'),\n para('Epilog'),\n )\n\n def __init__(self):\n self['#ok'].click(self.message)\n self['para'].hover(self.blend_in, self.blend_out)\n\n def message(self):\n print 'You clicked!'\n\n def blend_in(self, object):\n object.background = '#333333'\n\n def blend_out(self, object):\n object.background = 'WindowBackground'\n</code></pre>\n"
},
{
"answer_id": 335887,
"author": "Nick Retallack",
"author_id": 2653,
"author_profile": "https://Stackoverflow.com/users/2653",
"pm_score": 2,
"selected": false,
"text": "<p>This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new \"with\" statement.</p>\n\n<pre><code>with Shoes():\n t = Para(\"Not clicked!\")\n with Button(\"The Label\"):\n Alert(\"You clicked the button!\")\n t.replace(\"Clicked!\")\n</code></pre>\n\n<p>The hardest part is dealing with the fact that python will not give us anonymous functions with more than one statement in them. To get around that, we could create a list of commands and run through those...</p>\n\n<p>Anyway, here's the backend code I ran this with:</p>\n\n<pre><code>context = None\n\nclass Nestable(object):\n def __init__(self,caption=None):\n self.caption = caption\n self.things = []\n\n global context\n if context:\n context.add(self)\n\n def __enter__(self):\n global context\n self.parent = context\n context = self\n\n def __exit__(self, type, value, traceback):\n global context\n context = self.parent\n\n def add(self,thing):\n self.things.append(thing)\n print \"Adding a %s to %s\" % (thing,self)\n\n def __str__(self):\n return \"%s(%s)\" % (self.__class__.__name__, self.caption)\n\n\nclass Shoes(Nestable):\n pass\n\nclass Button(Nestable):\n pass\n\nclass Alert(Nestable):\n pass\n\nclass Para(Nestable):\n def replace(self,caption):\n Command(self,\"replace\",caption)\n\nclass Command(Nestable):\n def __init__(self, target, command, caption):\n self.command = command\n self.target = target\n Nestable.__init__(self,caption)\n\n def __str__(self):\n return \"Command(%s text of %s with \\\"%s\\\")\" % (self.command, self.target, self.caption)\n\n def execute(self):\n self.target.caption = self.caption\n</code></pre>\n"
},
{
"answer_id": 336089,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here's an approach that goes about GUI definitions a bit differently using class-based meta-programming rather than inheritance.</p>\n\n<p>This is largley Django/SQLAlchemy inspired in that it is heavily based on meta-programming and separates your GUI code from your \"code code\". I also think it should make heavy use of layout managers like Java does because when you're dropping code, no one wants to constantly tweak pixel alignment. I also think it would be cool if we could have CSS-like properties.</p>\n\n<p>Here is a rough brainstormed example that will show a column with a label on top, then a text box, then a button to click on the bottom which shows a message.</p>\n\n<pre>\nfrom happygui.controls import *\n\nMAIN_WINDOW = Window(width=\"500px\", height=\"350px\",\n my_layout=ColumnLayout(padding=\"10px\",\n my_label=Label(text=\"What's your name kiddo?\", bold=True, align=\"center\"),\n my_edit=EditBox(placeholder=\"\"),\n my_btn=Button(text=\"CLICK ME!\", on_click=Handler('module.file.btn_clicked')),\n ),\n)\nMAIN_WINDOW.show()\n\ndef btn_clicked(sender): # could easily be in a handlers.py file\n name = MAIN_WINDOW.my_layout.my_edit.text\n # same thing: name = sender.parent.my_edit.text\n # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text\n MessageBox(\"Your name is '%s'\" % ()).show(modal=True)\n</pre>\n\n<p>One cool thing to notice is the way you can reference the input of my_edit by saying <code>MAIN_WINDOW.my_layout.my_edit.text</code>. In the declaration for the window, I think it's important to be able to arbitrarily name controls in the function kwargs.</p>\n\n<p>Here is the same app only using absolute positioning (the controls will appear in different places because we're not using a fancy layout manager):</p>\n\n<pre>\nfrom happygui.controls import *\n\nMAIN_WINDOW = Window(width=\"500px\", height=\"350px\",\n my_label=Label(text=\"What's your name kiddo?\", bold=True, align=\"center\", x=\"10px\", y=\"10px\", width=\"300px\", height=\"100px\"),\n my_edit=EditBox(placeholder=\"\", x=\"10px\", y=\"110px\", width=\"300px\", height=\"100px\"),\n my_btn=Button(text=\"CLICK ME!\", on_click=Handler('module.file.btn_clicked'), x=\"10px\", y=\"210px\", width=\"300px\", height=\"100px\"),\n)\nMAIN_WINDOW.show()\n\ndef btn_clicked(sender): # could easily be in a handlers.py file\n name = MAIN_WINDOW.my_edit.text\n # same thing: name = sender.parent.my_edit.text\n # best practice, immune to structure change: MAIN_WINDOW.find('my_edit').text\n MessageBox(\"Your name is '%s'\" % ()).show(modal=True)\n</pre>\n\n<p>I'm not entirely sure yet if this is a super great approach, but I definitely think it's on the right path. I don't have time to explore this idea more, but if someone took this up as a project, I would love them.</p>\n"
},
{
"answer_id": 336525,
"author": "samuraisam",
"author_id": 42751,
"author_profile": "https://Stackoverflow.com/users/42751",
"pm_score": 2,
"selected": false,
"text": "<pre><code>## All you need is this class:\n\nclass MainWindow(Window):\n my_button = Button('Click Me')\n my_paragraph = Text('This is the text you wish to place')\n my_alert = AlertBox('What what what!!!')\n\n @my_button.clicked\n def my_button_clicked(self, button, event):\n self.my_paragraph.text.append('And now you clicked on it, the button that is.')\n\n @my_paragraph.text.changed\n def my_paragraph_text_changed(self, text, event):\n self.button.text = 'No more clicks!'\n\n @my_button.text.changed\n def my_button_text_changed(self, text, event):\n self.my_alert.show()\n\n\n## The Style class is automatically gnerated by the framework\n## but you can override it by defining it in the class:\n##\n## class MainWindow(Window):\n## class Style:\n## my_blah = {'style-info': 'value'}\n##\n## or like you see below:\n\nclass Style:\n my_button = {\n 'background-color': '#ccc',\n 'font-size': '14px'}\n my_paragraph = {\n 'background-color': '#fff',\n 'color': '#000',\n 'font-size': '14px',\n 'border': '1px solid black',\n 'border-radius': '3px'}\n\nMainWindow.Style = Style\n\n## The layout class is automatically generated\n## by the framework but you can override it by defining it\n## in the class, same as the Style class above, or by\n## defining it like this:\n\nclass MainLayout(Layout):\n def __init__(self, style):\n # It takes the custom or automatically generated style class upon instantiation\n style.window.pack(HBox().pack(style.my_paragraph, style.my_button))\n\nMainWindow.Layout = MainLayout\n\nif __name__ == '__main__':\n run(App(main=MainWindow))\n</code></pre>\n\n<p>It would be relatively easy to do in python with a bit of that metaclass python magic know how. Which I have. And a knowledge of PyGTK. Which I also have. Gets ideas?</p>\n"
},
{
"answer_id": 336583,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>If you use <a href=\"http://www.pygtk.org/\" rel=\"nofollow noreferrer\">PyGTK</a> with <a href=\"http://glade.gnome.org/\" rel=\"nofollow noreferrer\">glade</a> and <a href=\"http://www.pixelbeat.org/libs/libglade.py\" rel=\"nofollow noreferrer\">this glade wrapper</a>, then PyGTK actually becomes somewhat pythonic. A little at least.</p>\n\n<p>Basically, you create the GUI layout in Glade. You also specify event callbacks in glade. Then you write a class for your window like this:</p>\n\n<pre><code>class MyWindow(GladeWrapper):\n GladeWrapper.__init__(self, \"my_glade_file.xml\", \"mainWindow\")\n self.GtkWindow.show()\n\n def button_click_event (self, *args):\n self.button1.set_label(\"CLICKED\")\n</code></pre>\n\n<p>Here, I'm assuming that I have a GTK Button somewhere called <em>button1</em> and that I specified <em>button_click_event</em> as the <em>clicked</em> callback. The glade wrapper takes a lot of effort out of event mapping.</p>\n\n<p>If I were to design a Pythonic GUI library, I would support something similar, to aid rapid development. The only difference is that I would ensure that the widgets have a more pythonic interface too. The current PyGTK classes seem very C to me, except that I use foo.bar(...) instead of bar(foo, ...) though I'm not sure exactly what I'd do differently. Probably allow for a Django models style declarative means of specifying widgets and events in code and allowing you to access data though iterators (where it makes sense, eg widget lists perhaps), though I haven't really thought about it.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
]
| I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
```
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
```
This made me think - how would I design a similarly nice-to-use GUI framework in Python? One that doesn't have the usual tyings of basically being wrappers to a C\* library (In the case of GTK, Tk, wx, QT etc etc)
Shoes takes things from web devlopment (like `#f0c2f0` style colour notation, CSS layout techniques, like `:margin => 10`), and from ruby (extensively using blocks in sensible ways)
Python's lack of "rubyish blocks" makes a (metaphorically)-direct port impossible:
```
def Shoeless(Shoes.app):
self.t = para("Not clicked!")
def on_click_func(self):
alert("You clicked the button!")
self.t.replace("clicked!")
b = button("The label", click=self.on_click_func)
```
No where near as clean, and wouldn't be *nearly* as flexible, and I'm not even sure if it would be implementable.
Using decorators seems like an interesting way to map blocks of code to a specific action:
```
class BaseControl:
def __init__(self):
self.func = None
def clicked(self, func):
self.func = func
def __call__(self):
if self.func is not None:
self.func()
class Button(BaseControl):
pass
class Label(BaseControl):
pass
# The actual applications code (that the end-user would write)
class MyApp:
ok = Button()
la = Label()
@ok.clicked
def clickeryHappened():
print "OK Clicked!"
if __name__ == '__main__':
a = MyApp()
a.ok() # trigger the clicked action
```
Basically the decorator function stores the function, then when the action occurred (say, a click) the appropriate function would be executed.
The scope of various stuff (say, the `la` label in the above example) could be rather complicated, but it seems doable in a fairly neat manner.. | You could actually pull this off, but it would require using metaclasses, which are *deep* magic (there be dragons). If you want an intro to metaclasses, there's a series of [articles from IBM](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which manage to introduce the ideas without melting your brain.
The source code from an ORM like SQLObject might help, too, since it uses this same kind of declarative syntax. |
58,743 | <p>As an example take the following code:</p>
<pre><code>public enum ExampleEnum { FooBar, BarFoo }
public class ExampleClass : INotifyPropertyChanged
{
private ExampleEnum example;
public ExampleEnum ExampleProperty
{ get { return example; } { /* set and notify */; } }
}
</code></pre>
<p>I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:</p>
<pre><code><ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" />
</code></pre>
<p>Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.</p>
<p>Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.</p>
<p><strong>Edit</strong></p>
<p>So one question was answered: How do I populate the ComboBox with the right values.</p>
<p>Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:</p>
<pre><code><Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="ExampleEnumValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="ExampleEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
</code></pre>
<p>This I can use as an ItemsSource for my ComboBox:</p>
<pre><code><ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
</code></pre>
| [
{
"answer_id": 58766,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 5,
"selected": false,
"text": "<p>I don't know if it is possible in XAML-only but try the following:</p>\n\n<p>Give your ComboBox a name so you can access it in the codebehind: \"typesComboBox1\"</p>\n\n<p>Now try the following</p>\n\n<pre><code>typesComboBox1.ItemsSource = Enum.GetValues(typeof(ExampleEnum));\n</code></pre>\n"
},
{
"answer_id": 58819,
"author": "rudigrobler",
"author_id": 5147,
"author_profile": "https://Stackoverflow.com/users/5147",
"pm_score": 0,
"selected": false,
"text": "<p>Try using </p>\n\n<pre><code><ComboBox ItemsSource=\"{Binding Source={StaticResource ExampleEnumValues}}\"\n SelectedValue=\"{Binding Path=ExampleProperty}\" />\n</code></pre>\n"
},
{
"answer_id": 74011,
"author": "Greg",
"author_id": 11013,
"author_profile": "https://Stackoverflow.com/users/11013",
"pm_score": 3,
"selected": false,
"text": "<p>you can consider something like that:</p>\n\n<ol>\n<li><p>define a style for textblock, or any other control you want to use to display your enum:</p>\n\n<pre><code><Style x:Key=\"enumStyle\" TargetType=\"{x:Type TextBlock}\">\n <Setter Property=\"Text\" Value=\"&lt;NULL&gt;\"/>\n <Style.Triggers>\n <Trigger Property=\"Tag\">\n <Trigger.Value>\n <proj:YourEnum>Value1<proj:YourEnum>\n </Trigger.Value>\n <Setter Property=\"Text\" Value=\"{DynamicResource yourFriendlyValue1}\"/>\n </Trigger>\n <!-- add more triggers here to reflect your enum -->\n </Style.Triggers>\n</Style>\n</code></pre></li>\n<li><p>define your style for ComboBoxItem</p>\n\n<pre><code><Style TargetType=\"{x:Type ComboBoxItem}\">\n <Setter Property=\"ContentTemplate\">\n <Setter.Value>\n <DataTemplate>\n <TextBlock Tag=\"{Binding}\" Style=\"{StaticResource enumStyle}\"/>\n </DataTemplate>\n </Setter.Value>\n </Setter>\n</Style>\n</code></pre></li>\n<li><p>add a combobox and load it with your enum values:</p>\n\n<pre><code><ComboBox SelectedValue=\"{Binding Path=your property goes here}\" SelectedValuePath=\"Content\">\n <ComboBox.Items>\n <ComboBoxItem>\n <proj:YourEnum>Value1</proj:YourEnum>\n </ComboBoxItem>\n </ComboBox.Items>\n</ComboBox>\n</code></pre></li>\n</ol>\n\n<p>if your enum is large, you can of course do the same in code, sparing a lot of typing. \ni like that approach, since it makes localization easy - you define all the templates once, and then, you only update your string resource files.</p>\n"
},
{
"answer_id": 4398752,
"author": "Gregor Slavec",
"author_id": 355257,
"author_profile": "https://Stackoverflow.com/users/355257",
"pm_score": 8,
"selected": false,
"text": "<p>You can create a custom markup extension.</p>\n<p>Example of usage:</p>\n<pre><code>enum Status\n{\n [Description("Available.")]\n Available,\n [Description("Not here right now.")]\n Away,\n [Description("I don't have time right now.")]\n Busy\n}\n</code></pre>\n<p>At the top of your XAML:</p>\n<pre><code> xmlns:my="clr-namespace:namespace_to_enumeration_extension_class\n</code></pre>\n<p>and then...</p>\n<pre><code><ComboBox \n ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}" \n DisplayMemberPath="Description" \n SelectedValue="{Binding CurrentStatus}" \n SelectedValuePath="Value" /> \n</code></pre>\n<p>And the implementation...</p>\n<pre><code>public class EnumerationExtension : MarkupExtension\n {\n private Type _enumType;\n\n\n public EnumerationExtension(Type enumType)\n {\n if (enumType == null)\n throw new ArgumentNullException("enumType");\n\n EnumType = enumType;\n }\n\n public Type EnumType\n {\n get { return _enumType; }\n private set\n {\n if (_enumType == value)\n return;\n\n var enumType = Nullable.GetUnderlyingType(value) ?? value;\n\n if (enumType.IsEnum == false)\n throw new ArgumentException("Type must be an Enum.");\n\n _enumType = value;\n }\n }\n\n public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI\n {\n var enumValues = Enum.GetValues(EnumType);\n\n return (\n from object enumValue in enumValues\n select new EnumerationMember{\n Value = enumValue,\n Description = GetDescription(enumValue)\n }).ToArray();\n }\n\n private string GetDescription(object enumValue)\n {\n var descriptionAttribute = EnumType\n .GetField(enumValue.ToString())\n .GetCustomAttributes(typeof (DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute;\n\n\n return descriptionAttribute != null\n ? descriptionAttribute.Description\n : enumValue.ToString();\n }\n\n public class EnumerationMember\n {\n public string Description { get; set; }\n public object Value { get; set; }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 5803123,
"author": "user659130",
"author_id": 659130,
"author_profile": "https://Stackoverflow.com/users/659130",
"pm_score": 8,
"selected": false,
"text": "<p>In the viewmodel you can have:</p>\n\n<pre><code>public MyEnumType SelectedMyEnumType \n{\n get { return _selectedMyEnumType; }\n set { \n _selectedMyEnumType = value;\n OnPropertyChanged(\"SelectedMyEnumType\");\n }\n}\n\npublic IEnumerable<MyEnumType> MyEnumTypeValues\n{\n get\n {\n return Enum.GetValues(typeof(MyEnumType))\n .Cast<MyEnumType>();\n }\n}\n</code></pre>\n\n<p>In XAML the <code>ItemSource</code> binds to <code>MyEnumTypeValues</code> and <code>SelectedItem</code> binds to <code>SelectedMyEnumType</code>.</p>\n\n<pre><code><ComboBox SelectedItem=\"{Binding SelectedMyEnumType}\" ItemsSource=\"{Binding MyEnumTypeValues}\"></ComboBox>\n</code></pre>\n"
},
{
"answer_id": 7685443,
"author": "Martin Liversage",
"author_id": 98607,
"author_profile": "https://Stackoverflow.com/users/98607",
"pm_score": 5,
"selected": false,
"text": "<p>Based on the accepted but now deleted answer provided by <a href=\"http://www.ageektrapped.com/blog/the-missing-net-7-displaying-enums-in-wpf/\">ageektrapped</a> I created a slimmed down version without some of the more advanced features. All the code is included here to allow you to copy-paste it and not get blocked by link-rot.</p>\n\n<p>I use the <code>System.ComponentModel.DescriptionAttribute</code> which really is intended for design time descriptions. If you dislike using this attribute you may create your own but I think using this attribute really gets the job done. If you don't use the attribute the name will default to the name of the enum value in code.</p>\n\n<pre><code>public enum ExampleEnum {\n\n [Description(\"Foo Bar\")]\n FooBar,\n\n [Description(\"Bar Foo\")]\n BarFoo\n\n}\n</code></pre>\n\n<p>Here is the class used as the items source:</p>\n\n<pre><code>public class EnumItemsSource : Collection<String>, IValueConverter {\n\n Type type;\n\n IDictionary<Object, Object> valueToNameMap;\n\n IDictionary<Object, Object> nameToValueMap;\n\n public Type Type {\n get { return this.type; }\n set {\n if (!value.IsEnum)\n throw new ArgumentException(\"Type is not an enum.\", \"value\");\n this.type = value;\n Initialize();\n }\n }\n\n public Object Convert(Object value, Type targetType, Object parameter, CultureInfo culture) {\n return this.valueToNameMap[value];\n }\n\n public Object ConvertBack(Object value, Type targetType, Object parameter, CultureInfo culture) {\n return this.nameToValueMap[value];\n }\n\n void Initialize() {\n this.valueToNameMap = this.type\n .GetFields(BindingFlags.Static | BindingFlags.Public)\n .ToDictionary(fi => fi.GetValue(null), GetDescription);\n this.nameToValueMap = this.valueToNameMap\n .ToDictionary(kvp => kvp.Value, kvp => kvp.Key);\n Clear();\n foreach (String name in this.nameToValueMap.Keys)\n Add(name);\n }\n\n static Object GetDescription(FieldInfo fieldInfo) {\n var descriptionAttribute =\n (DescriptionAttribute) Attribute.GetCustomAttribute(fieldInfo, typeof(DescriptionAttribute));\n return descriptionAttribute != null ? descriptionAttribute.Description : fieldInfo.Name;\n }\n\n}\n</code></pre>\n\n<p>You can use it in XAML like this:</p>\n\n<pre><code><Windows.Resources>\n <local:EnumItemsSource\n x:Key=\"ExampleEnumItemsSource\"\n Type=\"{x:Type local:ExampleEnum}\"/>\n</Windows.Resources>\n<ComboBox\n ItemsSource=\"{StaticResource ExampleEnumItemsSource}\"\n SelectedValue=\"{Binding ExampleProperty, Converter={StaticResource ExampleEnumItemsSource}}\"/> \n</code></pre>\n"
},
{
"answer_id": 12415665,
"author": "CoperNick",
"author_id": 1457197,
"author_profile": "https://Stackoverflow.com/users/1457197",
"pm_score": 7,
"selected": false,
"text": "<p>I prefer not to use the name of enum in UI. I prefer use different value for user (<code>DisplayMemberPath</code>) and different for value (enum in this case) (<code>SelectedValuePath</code>). Those two values can be packed to <code>KeyValuePair</code> and stored in dictionary.</p>\n\n<p>XAML</p>\n\n<pre><code><ComboBox Name=\"fooBarComboBox\" \n ItemsSource=\"{Binding Path=ExampleEnumsWithCaptions}\" \n DisplayMemberPath=\"Value\" \n SelectedValuePath=\"Key\"\n SelectedValue=\"{Binding Path=ExampleProperty, Mode=TwoWay}\" > \n</code></pre>\n\n<p>C#</p>\n\n<pre><code>public Dictionary<ExampleEnum, string> ExampleEnumsWithCaptions { get; } =\n new Dictionary<ExampleEnum, string>()\n {\n {ExampleEnum.FooBar, \"Foo Bar\"},\n {ExampleEnum.BarFoo, \"Reversed Foo Bar\"},\n //{ExampleEnum.None, \"Hidden in UI\"},\n };\n\n\nprivate ExampleEnum example;\npublic ExampleEnum ExampleProperty\n{\n get { return example; }\n set { /* set and notify */; }\n}\n</code></pre>\n\n<p>EDIT: Compatible with the MVVM pattern.</p>\n"
},
{
"answer_id": 14976878,
"author": "Jack",
"author_id": 794594,
"author_profile": "https://Stackoverflow.com/users/794594",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a generic solution using a helper method.\nThis can also handle an enum of any underlying type (byte, sbyte, uint, long, etc.)</p>\n\n<p>Helper Method:</p>\n\n<pre><code>static IEnumerable<object> GetEnum<T>() {\n var type = typeof(T);\n var names = Enum.GetNames(type);\n var values = Enum.GetValues(type);\n var pairs =\n Enumerable.Range(0, names.Length)\n .Select(i => new {\n Name = names.GetValue(i)\n , Value = values.GetValue(i) })\n .OrderBy(pair => pair.Name);\n return pairs;\n}//method\n</code></pre>\n\n<p>View Model:</p>\n\n<pre><code>public IEnumerable<object> EnumSearchTypes {\n get {\n return GetEnum<SearchTypes>();\n }\n}//property\n</code></pre>\n\n<p>ComboBox:</p>\n\n<pre><code><ComboBox\n SelectedValue =\"{Binding SearchType}\"\n ItemsSource =\"{Binding EnumSearchTypes}\"\n DisplayMemberPath =\"Name\"\n SelectedValuePath =\"Value\"\n/>\n</code></pre>\n"
},
{
"answer_id": 28173443,
"author": "druss",
"author_id": 1246590,
"author_profile": "https://Stackoverflow.com/users/1246590",
"pm_score": 5,
"selected": false,
"text": "<p>Use ObjectDataProvider:</p>\n\n<pre><code><ObjectDataProvider x:Key=\"enumValues\"\n MethodName=\"GetValues\" ObjectType=\"{x:Type System:Enum}\">\n <ObjectDataProvider.MethodParameters>\n <x:Type TypeName=\"local:ExampleEnum\"/>\n </ObjectDataProvider.MethodParameters>\n </ObjectDataProvider>\n</code></pre>\n\n<p>and then bind to static resource:</p>\n\n<pre><code>ItemsSource=\"{Binding Source={StaticResource enumValues}}\"\n</code></pre>\n\n<p>Find this <a href=\"https://druss.co/2015/01/wpf-binding-itemssource-to-enum/\" rel=\"noreferrer\">solution at this blog</a></p>\n"
},
{
"answer_id": 31142863,
"author": "Contango",
"author_id": 107409,
"author_profile": "https://Stackoverflow.com/users/107409",
"pm_score": 1,
"selected": false,
"text": "<p>This is a <code>DevExpress</code> specific answer based on the top-voted answer by <code>Gregor S.</code> (currently it has 128 votes).</p>\n\n<p>This means we can keep the styling consistent across the entire application:</p>\n\n<p><img src=\"https://i.stack.imgur.com/khGqs.png\" alt=\"enter image description here\"></p>\n\n<p>Unfortunately, the original answer doesn't work with a <code>ComboBoxEdit</code> from DevExpress without some modifications.</p>\n\n<p>First, the XAML for the <code>ComboBoxEdit</code>:</p>\n\n<pre><code><dxe:ComboBoxEdit ItemsSource=\"{Binding Source={xamlExtensions:XamlExtensionEnumDropdown {x:myEnum:EnumFilter}}}\"\n SelectedItem=\"{Binding BrokerOrderBookingFilterSelected, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}\"\n DisplayMember=\"Description\"\n MinWidth=\"144\" Margin=\"5\" \n HorizontalAlignment=\"Left\"\n IsTextEditable=\"False\"\n ValidateOnTextInput=\"False\"\n AutoComplete=\"False\"\n IncrementalFiltering=\"True\"\n FilterCondition=\"Like\"\n ImmediatePopup=\"True\"/>\n</code></pre>\n\n<p>Needsless to say, you will need to point <code>xamlExtensions</code> at the namespace that contains the XAML extension class (which is defined below):</p>\n\n<pre><code>xmlns:xamlExtensions=\"clr-namespace:XamlExtensions\"\n</code></pre>\n\n<p>And we have to point <code>myEnum</code> at the namespace that contains the enum:</p>\n\n<pre><code>xmlns:myEnum=\"clr-namespace:MyNamespace\"\n</code></pre>\n\n<p>Then, the enum:</p>\n\n<pre><code>namespace MyNamespace\n{\n public enum EnumFilter\n {\n [Description(\"Free as a bird\")]\n Free = 0,\n\n [Description(\"I'm Somewhat Busy\")]\n SomewhatBusy = 1,\n\n [Description(\"I'm Really Busy\")]\n ReallyBusy = 2\n }\n}\n</code></pre>\n\n<p>The problem in with the XAML is that we can't use <code>SelectedItemValue</code>, as this throws an error as the setter is unaccessable (bit of an oversight on your part, <code>DevExpress</code>). So we have to modify our <code>ViewModel</code> to obtain the value directly from the object:</p>\n\n<pre><code>private EnumFilter _filterSelected = EnumFilter.All;\npublic object FilterSelected\n{\n get\n {\n return (EnumFilter)_filterSelected;\n }\n set\n {\n var x = (XamlExtensionEnumDropdown.EnumerationMember)value;\n if (x != null)\n {\n _filterSelected = (EnumFilter)x.Value;\n }\n OnPropertyChanged(\"FilterSelected\");\n }\n}\n</code></pre>\n\n<p>For completeness, here is the XAML extension from the original answer (slightly renamed):</p>\n\n<pre><code>namespace XamlExtensions\n{\n /// <summary>\n /// Intent: XAML markup extension to add support for enums into any dropdown box, see http://bit.ly/1g70oJy. We can name the items in the\n /// dropdown box by using the [Description] attribute on the enum values.\n /// </summary>\n public class XamlExtensionEnumDropdown : MarkupExtension\n {\n private Type _enumType;\n\n\n public XamlExtensionEnumDropdown(Type enumType)\n {\n if (enumType == null)\n {\n throw new ArgumentNullException(\"enumType\");\n }\n\n EnumType = enumType;\n }\n\n public Type EnumType\n {\n get { return _enumType; }\n private set\n {\n if (_enumType == value)\n {\n return;\n }\n\n var enumType = Nullable.GetUnderlyingType(value) ?? value;\n\n if (enumType.IsEnum == false)\n {\n throw new ArgumentException(\"Type must be an Enum.\");\n }\n\n _enumType = value;\n }\n }\n\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n var enumValues = Enum.GetValues(EnumType);\n\n return (\n from object enumValue in enumValues\n select new EnumerationMember\n {\n Value = enumValue,\n Description = GetDescription(enumValue)\n }).ToArray();\n }\n\n private string GetDescription(object enumValue)\n {\n var descriptionAttribute = EnumType\n .GetField(enumValue.ToString())\n .GetCustomAttributes(typeof (DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute;\n\n\n return descriptionAttribute != null\n ? descriptionAttribute.Description\n : enumValue.ToString();\n }\n\n #region Nested type: EnumerationMember\n public class EnumerationMember\n {\n public string Description { get; set; }\n public object Value { get; set; }\n }\n #endregion\n }\n}\n</code></pre>\n\n<p><em>Disclaimer: I have no affiliation with DevExpress. Telerik is also a great library.</em></p>\n"
},
{
"answer_id": 40537502,
"author": "LawMan",
"author_id": 2574087,
"author_profile": "https://Stackoverflow.com/users/2574087",
"pm_score": 0,
"selected": false,
"text": "<p>I've created an open source <a href=\"https://toastspopuphelpballoon.codeplex.com/\" rel=\"nofollow noreferrer\">CodePlex</a> project that does this. You can download the NuGet package from <a href=\"https://www.nuget.org/packages/Mantin.Controls.Wpf.EnumComboBox\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<pre><code><enumComboBox:EnumComboBox EnumType=\"{x:Type demoApplication:Status}\" SelectedValue=\"{Binding Status}\" />\n</code></pre>\n"
},
{
"answer_id": 43624661,
"author": "MotKohn",
"author_id": 5976576,
"author_profile": "https://Stackoverflow.com/users/5976576",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using a MVVM, based on @rudigrobler answer you can do the following:</p>\n\n<p>Add the following property to the <strong>ViewModel</strong> class</p>\n\n<pre><code>public Array ExampleEnumValues => Enum.GetValues(typeof(ExampleEnum));\n</code></pre>\n\n<p>Then in the XAML do the following:</p>\n\n<pre><code><ComboBox ItemsSource=\"{Binding ExampleEnumValues}\" ... />\n</code></pre>\n"
},
{
"answer_id": 45089218,
"author": "Nick",
"author_id": 862495,
"author_profile": "https://Stackoverflow.com/users/862495",
"pm_score": 3,
"selected": false,
"text": "<p>My favorite way to do this is with a <code>ValueConverter</code> so that the ItemsSource and SelectedValue both bind to the same property. This requires <strong>no additional properties</strong> to keep your ViewModel nice and clean.</p>\n\n<pre><code><ComboBox ItemsSource=\"{Binding Path=ExampleProperty, Converter={x:EnumToCollectionConverter}, Mode=OneTime}\"\n SelectedValuePath=\"Value\"\n DisplayMemberPath=\"Description\"\n SelectedValue=\"{Binding Path=ExampleProperty}\" />\n</code></pre>\n\n<p>And the definition of the Converter:</p>\n\n<pre><code>public static class EnumHelper\n{\n public static string Description(this Enum e)\n {\n return (e.GetType()\n .GetField(e.ToString())\n .GetCustomAttributes(typeof(DescriptionAttribute), false)\n .FirstOrDefault() as DescriptionAttribute)?.Description ?? e.ToString();\n }\n}\n\n[ValueConversion(typeof(Enum), typeof(IEnumerable<ValueDescription>))]\npublic class EnumToCollectionConverter : MarkupExtension, IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return Enum.GetValues(value.GetType())\n .Cast<Enum>()\n .Select(e => new ValueDescription() { Value = e, Description = e.Description()})\n .ToList();\n }\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n return null;\n }\n public override object ProvideValue(IServiceProvider serviceProvider)\n {\n return this;\n }\n}\n</code></pre>\n\n<p>This converter will work with any enum. <code>ValueDescription</code> is just a simple class with a <code>Value</code> property and a <code>Description</code> property. You could just as easily use a <code>Tuple</code> with <code>Item1</code> and <code>Item2</code>, or a <code>KeyValuePair</code> with <code>Key</code> and <code>Value</code> instead of Value and Description or any other class of your choice as long as it has can hold an enum value and string description of that enum value.</p>\n"
},
{
"answer_id": 65741894,
"author": "proa",
"author_id": 7564013,
"author_profile": "https://Stackoverflow.com/users/7564013",
"pm_score": 1,
"selected": false,
"text": "<p>Code</p>\n<pre><code> public enum RULE\n {\n [Description( "Любые, без ограничений" )]\n any,\n [Description( "Любые если будет три в ряд" )]\n anyThree,\n [Description( "Соседние, без ограничений" )]\n nearAny,\n [Description( "Соседние если будет три в ряд" )]\n nearThree\n }\n\n class ExtendRULE\n {\n public static object Values\n {\n get\n {\n List<object> list = new List<object>();\n foreach( RULE rule in Enum.GetValues( typeof( RULE ) ) )\n {\n string desc = rule.GetType().GetMember( rule.ToString() )[0].GetCustomAttribute<DescriptionAttribute>().Description;\n list.Add( new { value = rule, desc = desc } );\n }\n return list;\n }\n }\n }\n</code></pre>\n<p>XAML</p>\n<pre><code><StackPanel>\n <ListBox ItemsSource= "{Binding Source={x:Static model:ExtendRULE.Values}}" DisplayMemberPath="desc" SelectedValuePath="value" SelectedValue="{Binding SelectedRule}"/>\n <ComboBox ItemsSource="{Binding Source={x:Static model:ExtendRULE.Values}}" DisplayMemberPath="desc" SelectedValuePath="value" SelectedValue="{Binding SelectedRule}"/> \n</StackPanel>\n</code></pre>\n"
},
{
"answer_id": 70387321,
"author": "BionicCode",
"author_id": 3141792,
"author_profile": "https://Stackoverflow.com/users/3141792",
"pm_score": 1,
"selected": false,
"text": "<p>It's a pain to see all to see how certain overly complicated solutions become a "standard (anti-)pattern" for the most trivial problems: the overhead and complexity of implementing a <code>MarkupExtension</code> and especially decorating enum values with attributes should be avoided. Simply implement a data model.</p>\n<p>Generally, displaying the enumeration value names to the user is a bad idea. Enumerations are not meant to be displayed in the UI. They are constants that are used in a programmatic context. The value names are not meant for display. They are meant to address the engineer, hence the names usually use special semantics and vocabulary, same as scientific vocabulary is not meant to be understood by the public. Don't hesitate to create a dedicated source for the displayed values.</p>\n<p>The problem becomes more evident when localization gets involved.<br />\nThat's why all posted answers are simply over engeineered. They make a very simple problem look like a critical issue.<br />\nIt's a fact that the most trivial solution is the best. The subject of the original question is most definitely <em>not</em> an exception.<br />\nI highly recommend against any of the provided answers. Although they may work, they add unnecessary complexity to a trivial problem.</p>\n<p>Note, that you can always convert an enum to a list of its values or value names by calling the static <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.enum.getvalues?view=net-6.0#System_Enum_GetValues_System_Type_\" rel=\"nofollow noreferrer\"><code>Enum.GetValues</code></a> or <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.enum.getnames?view=net-6.0\" rel=\"nofollow noreferrer\"><code>Enum.GetNames</code></a>, which both return an <code>IEnumerable</code> that you can directly assign to the <code>ComboBox.ItemsSource</code> property e.g.,via data binding.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>IEnumerable<ExampleEnum> values = Enum.GetValues<ExampleEnum>();\nIEnumerable<string> names = Enum.GetNames<ExampleEnum>();\n</code></pre>\n<p>Usually, when defining an enumeration, you don't have UI in mind.<br />\nEnumeration value names are not chosen based on UI design rules.<br />\nUsually, UI labels and text in general are created by people with no developer or programmer background. They usually provide all the required translations to localize the application.<br />\nThere are many good reasons not to mix UI with the application.<br />\nYou would never design a class and name its properties with UI (e.g., <code>DataGrid</code> columns) in mind. You may want your column header to contain whitespaces etc.<br />\nSame reason why exception messages are directed at developers and not users. You definitely don't want to decorate every property, every exception, enum or whatever data type or member with attributes in order to provide a display name that makes sense to the user in a particular UI context.<br />\nYou don't want to have UI design bleed into your code base and polute your classes.<br />\nApplication and its user interface - this are two different problems.<br />\nAdding this abstract or virtual extra layer of separation allows e.g., to add enum values that should not be displayed. Or more general, modify code without having to break or modify the UI.</p>\n<p>Instead of using attributes and implementing loads of additional logic to extract their values (using reflection), you should use a <em>simple</em> <code>IValueConverter</code> or a dedicated class that provides those display values as a binding source.<br />\nStick to the most common pattern and implement a data model for the <code>ComboBox</code> items, where the class has a property of the enum type as member, that helps you to identify the <code>ComboBox.SelectedItem</code> (in case you need the enum value):</p>\n<p><strong>ExampleEnum.cs</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>// Define enumeration without minding any UI elements and context\npublic enum ExampleEnum \n{ \n FooBar = 0, \n BarFoo \n}\n</code></pre>\n<p><strong>ExampleClass.cs</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>// Define readable enum display values in the UI context.\n// Display names can come from a localizable resource.\npublic class BindingSource : INotifyPropertyChanged\n{\n public BindingSource()\n {\n ItemModels = new List<ItemModel> \n {\n new ItemModel { Label = "Foo Bar Display", Value = ExampleEnum.FooBar },\n new ItemModel { Label = "Bar Foo Display", Value = ExampleEnum.BarFoo }\n }\n }\n\n public List<ItemModel> ItemModels { get; }\n\n private ItemModel selectedItemModel;\n public ItemModel SelectedItemModel { get => selectedItemModel; => set and notify; }\n}\n</code></pre>\n<p><strong>ItemModel.cs</strong></p>\n<pre class=\"lang-cs prettyprint-override\"><code>public class ItemModel\n{ \n public string Label { get; set; }\n public ExampleEnum Value { get; set; }\n}\n</code></pre>\n<p><strong>MainWindow.xaml</strong></p>\n<pre class=\"lang-xml prettyprint-override\"><code><Window>\n <Window.DataContext>\n <BindingSource />\n </Window.DataContext>\n\n <ComboBox ItemsSource="{Binding ItemModels}"\n DisplayMemberName="DisplayValue"\n SelectedItem="{Binding SelectedItemModel}" />\n</Window>\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1733/"
]
| As an example take the following code:
```
public enum ExampleEnum { FooBar, BarFoo }
public class ExampleClass : INotifyPropertyChanged
{
private ExampleEnum example;
public ExampleEnum ExampleProperty
{ get { return example; } { /* set and notify */; } }
}
```
I want a to databind the property ExampleProperty to a ComboBox, so that it shows the options "FooBar" and "BarFoo" and works in mode TwoWay. Optimally I want my ComboBox definition to look something like this:
```
<ComboBox ItemsSource="What goes here?" SelectedItem="{Binding Path=ExampleProperty}" />
```
Currently I have handlers for the ComboBox.SelectionChanged and ExampleClass.PropertyChanged events installed in my Window where I do the binding manually.
Is there a better or some kind of canonical way? Would you usually use Converters and how would you populate the ComboBox with the right values? I don't even want to get started with i18n right now.
**Edit**
So one question was answered: How do I populate the ComboBox with the right values.
Retrieve Enum values as a list of strings via an ObjectDataProvider from the static Enum.GetValues method:
```
<Window.Resources>
<ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type sys:Enum}"
x:Key="ExampleEnumValues">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="ExampleEnum" />
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
```
This I can use as an ItemsSource for my ComboBox:
```
<ComboBox ItemsSource="{Binding Source={StaticResource ExampleEnumValues}}"/>
``` | You can create a custom markup extension.
Example of usage:
```
enum Status
{
[Description("Available.")]
Available,
[Description("Not here right now.")]
Away,
[Description("I don't have time right now.")]
Busy
}
```
At the top of your XAML:
```
xmlns:my="clr-namespace:namespace_to_enumeration_extension_class
```
and then...
```
<ComboBox
ItemsSource="{Binding Source={my:Enumeration {x:Type my:Status}}}"
DisplayMemberPath="Description"
SelectedValue="{Binding CurrentStatus}"
SelectedValuePath="Value" />
```
And the implementation...
```
public class EnumerationExtension : MarkupExtension
{
private Type _enumType;
public EnumerationExtension(Type enumType)
{
if (enumType == null)
throw new ArgumentNullException("enumType");
EnumType = enumType;
}
public Type EnumType
{
get { return _enumType; }
private set
{
if (_enumType == value)
return;
var enumType = Nullable.GetUnderlyingType(value) ?? value;
if (enumType.IsEnum == false)
throw new ArgumentException("Type must be an Enum.");
_enumType = value;
}
}
public override object ProvideValue(IServiceProvider serviceProvider) // or IXamlServiceProvider for UWP and WinUI
{
var enumValues = Enum.GetValues(EnumType);
return (
from object enumValue in enumValues
select new EnumerationMember{
Value = enumValue,
Description = GetDescription(enumValue)
}).ToArray();
}
private string GetDescription(object enumValue)
{
var descriptionAttribute = EnumType
.GetField(enumValue.ToString())
.GetCustomAttributes(typeof (DescriptionAttribute), false)
.FirstOrDefault() as DescriptionAttribute;
return descriptionAttribute != null
? descriptionAttribute.Description
: enumValue.ToString();
}
public class EnumerationMember
{
public string Description { get; set; }
public object Value { get; set; }
}
}
``` |
58,744 | <p>I want to copy the entire contents of a directory from one location to another in C#.</p>
<p>There doesn't appear to be a way to do this using <code>System.IO</code> classes without lots of recursion.</p>
<p>There is a method in VB that we can use if we add a reference to <code>Microsoft.VisualBasic</code>:</p>
<pre><code>new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
</code></pre>
<p>This seems like a rather ugly hack. Is there a better way?</p>
| [
{
"answer_id": 58759,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 6,
"selected": false,
"text": "<p>Or, if you want to go the hard way, add a reference to your project for Microsoft.VisualBasic and then use the following:</p>\n\n<pre><code>Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(fromDirectory, toDirectory);\n</code></pre>\n\n<p>However, using one of the recursive functions is a better way to go since it won't have to load the VB dll.</p>\n"
},
{
"answer_id": 58762,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Sorry for the previous code, it still had bugs :( (fell prey to the fastest gun problem) . Here it is tested and working. The key is the SearchOption.AllDirectories, which eliminates the need for explicit recursion.</p>\n\n<pre><code>string path = \"C:\\\\a\";\nstring[] dirs = Directory.GetDirectories(path, \"*.*\", SearchOption.AllDirectories);\nstring newpath = \"C:\\\\x\";\ntry\n{\n Directory.CreateDirectory(newpath);\n}\ncatch (IOException ex)\n{\n Console.WriteLine(ex.Message);\n}\nfor (int j = 0; j < dirs.Length; j++)\n{\n try\n {\n Directory.CreateDirectory(dirs[j].Replace(path, newpath));\n }\n catch (IOException ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n\nstring[] files = Directory.GetFiles(path, \"*.*\", SearchOption.AllDirectories);\nfor (int j = 0; j < files.Length; j++) \n{\n try\n {\n File.Copy(files[j], files[j].Replace(path, newpath));\n }\n catch (IOException ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 58770,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a utility class I've used for IO tasks like this.</p>\n\n<pre><code>using System;\nusing System.Runtime.InteropServices;\n\nnamespace MyNameSpace\n{\n public class ShellFileOperation\n {\n private static String StringArrayToMultiString(String[] stringArray)\n {\n String multiString = \"\";\n\n if (stringArray == null)\n return \"\";\n\n for (int i=0 ; i<stringArray.Length ; i++)\n multiString += stringArray[i] + '\\0';\n\n multiString += '\\0';\n\n return multiString;\n }\n\n public static bool Copy(string source, string dest)\n {\n return Copy(new String[] { source }, new String[] { dest });\n }\n\n public static bool Copy(String[] source, String[] dest)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_COPY;\n\n String multiSource = StringArrayToMultiString(source);\n String multiDest = StringArrayToMultiString(dest);\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = Marshal.StringToHGlobalUni(multiDest);\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n\n public static bool Move(string source, string dest)\n {\n return Move(new String[] { source }, new String[] { dest });\n }\n\n public static bool Delete(string file)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_DELETE;\n\n String multiSource = StringArrayToMultiString(new string[] { file });\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = IntPtr.Zero;\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_SILENT | (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION | (ushort)Win32.ShellFileOperationFlags.FOF_NOERRORUI | (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMMKDIR;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n\n public static bool Move(String[] source, String[] dest)\n {\n Win32.SHFILEOPSTRUCT FileOpStruct = new Win32.SHFILEOPSTRUCT();\n\n FileOpStruct.hwnd = IntPtr.Zero;\n FileOpStruct.wFunc = (uint)Win32.FO_MOVE;\n\n String multiSource = StringArrayToMultiString(source);\n String multiDest = StringArrayToMultiString(dest);\n FileOpStruct.pFrom = Marshal.StringToHGlobalUni(multiSource);\n FileOpStruct.pTo = Marshal.StringToHGlobalUni(multiDest);\n\n FileOpStruct.fFlags = (ushort)Win32.ShellFileOperationFlags.FOF_NOCONFIRMATION;\n FileOpStruct.lpszProgressTitle = \"\";\n FileOpStruct.fAnyOperationsAborted = 0;\n FileOpStruct.hNameMappings = IntPtr.Zero;\n\n int retval = Win32.SHFileOperation(ref FileOpStruct);\n\n if(retval != 0) return false;\n return true;\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 58779,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 8,
"selected": false,
"text": "<p>Hmm, I think I misunderstand the question but I'm going to risk it. What's wrong with the following straightforward method?</p>\n\n<pre><code>public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {\n foreach (DirectoryInfo dir in source.GetDirectories())\n CopyFilesRecursively(dir, target.CreateSubdirectory(dir.Name));\n foreach (FileInfo file in source.GetFiles())\n file.CopyTo(Path.Combine(target.FullName, file.Name));\n}\n</code></pre>\n\n<p><strong>EDIT</strong> Since this posting has garnered an impressive number of downvotes for such a simple answer to an equally simple question, let me add an explanation. <strong>Please</strong> <em>read this before downvoting</em>.</p>\n\n<p>First of all, <strong>this code is not intendend as a drop-in replacement</strong> to the code in the question. It is for illustration purpose only.</p>\n\n<p><code>Microsoft.VisualBasic.Devices.Computer.FileSystem.CopyDirectory</code> does some additional correctness tests (e.g. whether the source and target are valid directories, whether the source is a parent of the target etc.) that are missing from this answer. That code is probably also more optimized.</p>\n\n<p>That said, the code <em>works well</em>. It <em>has</em> (almost identically) been used in a mature software for years. Apart from the inherent fickleness present with all IO handlings (e.g. what happens if the user manually unplugs the USB drive while your code is writing to it?), there are no known problems.</p>\n\n<p>In particular, I’d like to point out that the use of recursion here is absolutely not a problem. Neither in theory (conceptually, it’s the most elegant solution) nor in practice: <em>this code will not overflow the stack</em>. The stack is large enough to handle even deeply nested file hierarchies. Long before stack space becomes a problem, the folder path length limitation kicks in.</p>\n\n<p>Notice that a <em>malicious user</em> might be able to break this assumption by using deeply-nested directories of one letter each. I haven’t tried this. But just to illustrate the point: in order to make this code overflow on a typical computer, the directories would have to be nested a few <em>thousand</em> times. This is simply not a realistic scenario.</p>\n"
},
{
"answer_id": 58820,
"author": "d4nt",
"author_id": 1039,
"author_profile": "https://Stackoverflow.com/users/1039",
"pm_score": 6,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>Process proc = new Process();\nproc.StartInfo.UseShellExecute = true;\nproc.StartInfo.FileName = Path.Combine(Environment.SystemDirectory, \"xcopy.exe\");\nproc.StartInfo.Arguments = @\"C:\\source C:\\destination /E /I\";\nproc.Start();\n</code></pre>\n\n<p>Your xcopy arguments may vary but you get the idea.</p>\n"
},
{
"answer_id": 690980,
"author": "Justin R.",
"author_id": 4593,
"author_profile": "https://Stackoverflow.com/users/4593",
"pm_score": 7,
"selected": false,
"text": "<p>Copied from <a href=\"http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx\" rel=\"noreferrer\">MSDN</a>:</p>\n\n<pre><code>using System;\nusing System.IO;\n\nclass CopyDir\n{\n public static void Copy(string sourceDirectory, string targetDirectory)\n {\n DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);\n DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);\n\n CopyAll(diSource, diTarget);\n }\n\n public static void CopyAll(DirectoryInfo source, DirectoryInfo target)\n {\n Directory.CreateDirectory(target.FullName);\n\n // Copy each file into the new directory.\n foreach (FileInfo fi in source.GetFiles())\n {\n Console.WriteLine(@\"Copying {0}\\{1}\", target.FullName, fi.Name);\n fi.CopyTo(Path.Combine(target.FullName, fi.Name), true);\n }\n\n // Copy each subdirectory using recursion.\n foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())\n {\n DirectoryInfo nextTargetSubDir =\n target.CreateSubdirectory(diSourceSubDir.Name);\n CopyAll(diSourceSubDir, nextTargetSubDir);\n }\n }\n\n public static void Main()\n {\n string sourceDirectory = @\"c:\\sourceDirectory\";\n string targetDirectory = @\"c:\\targetDirectory\";\n\n Copy(sourceDirectory, targetDirectory);\n }\n\n // Output will vary based on the contents of the source directory.\n}\n</code></pre>\n"
},
{
"answer_id": 2527714,
"author": "Jens Granlund",
"author_id": 214222,
"author_profile": "https://Stackoverflow.com/users/214222",
"pm_score": 4,
"selected": false,
"text": "<p>Copy folder recursively without recursion to avoid stack overflow.</p>\n\n<pre><code>public static void CopyDirectory(string source, string target)\n{\n var stack = new Stack<Folders>();\n stack.Push(new Folders(source, target));\n\n while (stack.Count > 0)\n {\n var folders = stack.Pop();\n Directory.CreateDirectory(folders.Target);\n foreach (var file in Directory.GetFiles(folders.Source, \"*.*\"))\n {\n File.Copy(file, Path.Combine(folders.Target, Path.GetFileName(file)));\n }\n\n foreach (var folder in Directory.GetDirectories(folders.Source))\n {\n stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));\n }\n }\n}\n\npublic class Folders\n{\n public string Source { get; private set; }\n public string Target { get; private set; }\n\n public Folders(string source, string target)\n {\n Source = source;\n Target = target;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3822913,
"author": "tboswell",
"author_id": 461882,
"author_profile": "https://Stackoverflow.com/users/461882",
"pm_score": 10,
"selected": true,
"text": "<p>Much easier</p>\n<pre><code>private static void CopyFilesRecursively(string sourcePath, string targetPath)\n{\n //Now Create all of the directories\n foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))\n {\n Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));\n }\n\n //Copy all the files & Replaces any files with the same name\n foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))\n {\n File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8022011,
"author": "eduardomozart",
"author_id": 1031340,
"author_profile": "https://Stackoverflow.com/users/1031340",
"pm_score": 5,
"selected": false,
"text": "<p>This site always have helped me out a lot, and now it's my turn to help the others with what I know.</p>\n\n<p>I hope that my code below be useful for someone.</p>\n\n<pre><code>string source_dir = @\"E:\\\";\nstring destination_dir = @\"C:\\\";\n\n// substring is to remove destination_dir absolute path (E:\\).\n\n// Create subdirectory structure in destination \n foreach (string dir in System.IO.Directory.GetDirectories(source_dir, \"*\", System.IO.SearchOption.AllDirectories))\n {\n System.IO.Directory.CreateDirectory(System.IO.Path.Combine(destination_dir, dir.Substring(source_dir.Length + 1)));\n // Example:\n // > C:\\sources (and not C:\\E:\\sources)\n }\n\n foreach (string file_name in System.IO.Directory.GetFiles(source_dir, \"*\", System.IO.SearchOption.AllDirectories))\n {\n System.IO.File.Copy(file_name, System.IO.Path.Combine(destination_dir, file_name.Substring(source_dir.Length + 1)));\n }\n</code></pre>\n"
},
{
"answer_id": 9127432,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 2,
"selected": false,
"text": "<p>A minor improvement on d4nt's answer, as you probably want to check for errors and not have to change xcopy paths if you're working on a server and development machine:</p>\n\n<pre><code>public void CopyFolder(string source, string destination)\n{\n string xcopyPath = Environment.GetEnvironmentVariable(\"WINDIR\") + @\"\\System32\\xcopy.exe\";\n ProcessStartInfo info = new ProcessStartInfo(xcopyPath);\n info.UseShellExecute = false;\n info.RedirectStandardOutput = true;\n info.Arguments = string.Format(\"\\\"{0}\\\" \\\"{1}\\\" /E /I\", source, destination);\n\n Process process = Process.Start(info);\n process.WaitForExit();\n string result = process.StandardOutput.ReadToEnd();\n\n if (process.ExitCode != 0)\n {\n // Or your own custom exception, or just return false if you prefer.\n throw new InvalidOperationException(string.Format(\"Failed to copy {0} to {1}: {2}\", source, destination, result));\n }\n}\n</code></pre>\n"
},
{
"answer_id": 12543017,
"author": "Khoi_Vjz_Boy",
"author_id": 1332062,
"author_profile": "https://Stackoverflow.com/users/1332062",
"pm_score": 2,
"selected": false,
"text": "<p>This is my code hope this help</p>\n\n<pre><code> private void KCOPY(string source, string destination)\n {\n if (IsFile(source))\n {\n string target = Path.Combine(destination, Path.GetFileName(source));\n File.Copy(source, target, true);\n }\n else\n {\n string fileName = Path.GetFileName(source);\n string target = System.IO.Path.Combine(destination, fileName);\n if (!System.IO.Directory.Exists(target))\n {\n System.IO.Directory.CreateDirectory(target);\n }\n\n List<string> files = GetAllFileAndFolder(source);\n\n foreach (string file in files)\n {\n KCOPY(file, target);\n }\n }\n }\n\n private List<string> GetAllFileAndFolder(string path)\n {\n List<string> allFile = new List<string>();\n foreach (string dir in Directory.GetDirectories(path))\n {\n allFile.Add(dir);\n }\n foreach (string file in Directory.GetFiles(path))\n {\n allFile.Add(file);\n }\n\n return allFile;\n }\n private bool IsFile(string path)\n {\n if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)\n {\n return false;\n }\n return true;\n }\n</code></pre>\n"
},
{
"answer_id": 15648301,
"author": "Daryl",
"author_id": 814454,
"author_profile": "https://Stackoverflow.com/users/814454",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an extension method for DirectoryInfo a la <a href=\"http://msdn.microsoft.com/en-us/library/5axsfwbc.aspx\" rel=\"nofollow\">FileInfo.CopyTo</a> (note the <code>overwrite</code> parameter):</p>\n\n<pre><code>public static DirectoryInfo CopyTo(this DirectoryInfo sourceDir, string destinationPath, bool overwrite = false)\n{\n var sourcePath = sourceDir.FullName;\n\n var destination = new DirectoryInfo(destinationPath);\n\n destination.Create();\n\n foreach (var sourceSubDirPath in Directory.EnumerateDirectories(sourcePath, \"*\", SearchOption.AllDirectories))\n Directory.CreateDirectory(sourceSubDirPath.Replace(sourcePath, destinationPath));\n\n foreach (var file in Directory.EnumerateFiles(sourcePath, \"*\", SearchOption.AllDirectories))\n File.Copy(file, file.Replace(sourcePath, destinationPath), overwrite);\n\n return destination;\n}\n</code></pre>\n"
},
{
"answer_id": 29463011,
"author": "toddmo",
"author_id": 1045881,
"author_profile": "https://Stackoverflow.com/users/1045881",
"pm_score": 2,
"selected": false,
"text": "<p>If you like Konrad's popular answer, but you want the <code>source</code> itself to be a folder under <code>target</code>, rather than putting it's children under the <code>target</code> folder, here's the code for that. It returns the newly created <code>DirectoryInfo</code>, which is handy:</p>\n\n<pre><code>public static DirectoryInfo CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target)\n{\n var newDirectoryInfo = target.CreateSubdirectory(source.Name);\n foreach (var fileInfo in source.GetFiles())\n fileInfo.CopyTo(Path.Combine(newDirectoryInfo.FullName, fileInfo.Name));\n\n foreach (var childDirectoryInfo in source.GetDirectories())\n CopyFilesRecursively(childDirectoryInfo, newDirectoryInfo);\n\n return newDirectoryInfo;\n}\n</code></pre>\n"
},
{
"answer_id": 35742118,
"author": "bh_earth0",
"author_id": 3137362,
"author_profile": "https://Stackoverflow.com/users/3137362",
"pm_score": 2,
"selected": false,
"text": "<p>tboswell 's replace Proof version (which is resilient to repeating pattern in filepath)</p>\n\n<pre><code>public static void copyAll(string SourcePath , string DestinationPath )\n{\n //Now Create all of the directories\n foreach (string dirPath in Directory.GetDirectories(SourcePath, \"*\", SearchOption.AllDirectories))\n Directory.CreateDirectory(Path.Combine(DestinationPath ,dirPath.Remove(0, SourcePath.Length )) );\n\n //Copy all the files & Replaces any files with the same name\n foreach (string newPath in Directory.GetFiles(SourcePath, \"*.*\", SearchOption.AllDirectories))\n File.Copy(newPath, Path.Combine(DestinationPath , newPath.Remove(0, SourcePath.Length)) , true);\n }\n</code></pre>\n"
},
{
"answer_id": 45199038,
"author": "iato",
"author_id": 5116032,
"author_profile": "https://Stackoverflow.com/users/5116032",
"pm_score": 2,
"selected": false,
"text": "<p>You can always use <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories\" rel=\"nofollow noreferrer\">this</a>, taken from Microsofts website. </p>\n\n<pre><code>static void Main()\n{\n // Copy from the current directory, include subdirectories.\n DirectoryCopy(\".\", @\".\\temp\", true);\n}\n\nprivate static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)\n{\n // Get the subdirectories for the specified directory.\n DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n\n if (!dir.Exists)\n {\n throw new DirectoryNotFoundException(\n \"Source directory does not exist or could not be found: \"\n + sourceDirName);\n }\n\n DirectoryInfo[] dirs = dir.GetDirectories();\n // If the destination directory doesn't exist, create it.\n if (!Directory.Exists(destDirName))\n {\n Directory.CreateDirectory(destDirName);\n }\n\n // Get the files in the directory and copy them to the new location.\n FileInfo[] files = dir.GetFiles();\n foreach (FileInfo file in files)\n {\n string temppath = Path.Combine(destDirName, file.Name);\n file.CopyTo(temppath, false);\n }\n\n // If copying subdirectories, copy them and their contents to new location.\n if (copySubDirs)\n {\n foreach (DirectoryInfo subdir in dirs)\n {\n string temppath = Path.Combine(destDirName, subdir.Name);\n DirectoryCopy(subdir.FullName, temppath, copySubDirs);\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45614470,
"author": "Ahmed Sabry",
"author_id": 4707576,
"author_profile": "https://Stackoverflow.com/users/4707576",
"pm_score": 1,
"selected": false,
"text": "<p>Use this class.</p>\n\n<pre><code>public static class Extensions\n{\n public static void CopyTo(this DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)\n {\n if (!source.Exists) return;\n if (!target.Exists) target.Create();\n\n Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) => \n CopyTo(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));\n\n foreach (var sourceFile in source.GetFiles())\n sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles);\n }\n public static void CopyTo(this DirectoryInfo source, string target, bool overwiteFiles = true)\n {\n CopyTo(source, new DirectoryInfo(target), overwiteFiles);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 46857070,
"author": "malballah",
"author_id": 7633869,
"author_profile": "https://Stackoverflow.com/users/7633869",
"pm_score": 0,
"selected": false,
"text": "<p>Better than any code (extension method to DirectoryInfo with recursion)</p>\n\n<pre><code>public static bool CopyTo(this DirectoryInfo source, string destination)\n {\n try\n {\n foreach (string dirPath in Directory.GetDirectories(source.FullName))\n {\n var newDirPath = dirPath.Replace(source.FullName, destination);\n Directory.CreateDirectory(newDirPath);\n new DirectoryInfo(dirPath).CopyTo(newDirPath);\n }\n //Copy all the files & Replaces any files with the same name\n foreach (string filePath in Directory.GetFiles(source.FullName))\n {\n File.Copy(filePath, filePath.Replace(source.FullName,destination), true);\n }\n return true;\n }\n catch (IOException exp)\n {\n return false;\n }\n }\n</code></pre>\n"
},
{
"answer_id": 49461959,
"author": "Termininja",
"author_id": 3618581,
"author_profile": "https://Stackoverflow.com/users/3618581",
"pm_score": 1,
"selected": false,
"text": "<p>One variant with only one loop for copying of all folders and files:</p>\n\n<pre><code>foreach (var f in Directory.GetFileSystemEntries(path, \"*\", SearchOption.AllDirectories))\n{\n var output = Regex.Replace(f, @\"^\" + path, newPath);\n if (File.Exists(f)) File.Copy(f, output, true);\n else Directory.CreateDirectory(output);\n}\n</code></pre>\n"
},
{
"answer_id": 51376395,
"author": "AlexanderD",
"author_id": 5214808,
"author_profile": "https://Stackoverflow.com/users/5214808",
"pm_score": 2,
"selected": false,
"text": "<p>It may not be performance-aware, but I'm using it for 30MB folders and it works flawlessly. Plus, I didn't like all the amount of code and recursion required for such an easy task.</p>\n<pre><code>var src = "c:\\src";\nvar dest = "c:\\dest";\nvar cmp = CompressionLevel.NoCompression;\nvar zip = source_folder + ".zip";\n\nZipFile.CreateFromDirectory(src, zip, cmp, includeBaseDirectory: false);\nZipFile.ExtractToDirectory(zip, dest_folder);\n\nFile.Delete(zip);\n</code></pre>\n<p><em>Note: ZipFile is available on .NET 4.5+ in the System.IO.Compression namespace</em></p>\n"
},
{
"answer_id": 53405237,
"author": "OKEEngine",
"author_id": 662649,
"author_profile": "https://Stackoverflow.com/users/662649",
"pm_score": 2,
"selected": false,
"text": "<p>My solution is basically a modification of @Termininja's answer, however I have enhanced it a bit and it appears to be more than 5 times faster than the accepted answer. </p>\n\n<pre><code>public static void CopyEntireDirectory(string path, string newPath)\n{\n Parallel.ForEach(Directory.GetFileSystemEntries(path, \"*\", SearchOption.AllDirectories)\n ,(fileName) =>\n {\n string output = Regex.Replace(fileName, \"^\" + Regex.Escape(path), newPath);\n if (File.Exists(fileName))\n {\n Directory.CreateDirectory(Path.GetDirectoryName(output));\n File.Copy(fileName, output, true);\n }\n else\n Directory.CreateDirectory(output);\n });\n}\n</code></pre>\n\n<p>EDIT: Modifying @Ahmed Sabry to full parallel foreach does produce a better result, however the code uses recursive function and its not ideal in some situation.</p>\n\n<pre><code>public static void CopyEntireDirectory(DirectoryInfo source, DirectoryInfo target, bool overwiteFiles = true)\n{\n if (!source.Exists) return;\n if (!target.Exists) target.Create();\n\n Parallel.ForEach(source.GetDirectories(), (sourceChildDirectory) =>\n CopyEntireDirectory(sourceChildDirectory, new DirectoryInfo(Path.Combine(target.FullName, sourceChildDirectory.Name))));\n\n Parallel.ForEach(source.GetFiles(), sourceFile =>\n sourceFile.CopyTo(Path.Combine(target.FullName, sourceFile.Name), overwiteFiles));\n}\n</code></pre>\n"
},
{
"answer_id": 55596428,
"author": "Lakmal",
"author_id": 1547297,
"author_profile": "https://Stackoverflow.com/users/1547297",
"pm_score": 0,
"selected": false,
"text": "<p>Copy and replace all files of the folder</p>\n\n<pre><code> public static void CopyAndReplaceAll(string SourcePath, string DestinationPath, string backupPath)\n {\n foreach (string dirPath in Directory.GetDirectories(SourcePath, \"*\", SearchOption.AllDirectories))\n {\n Directory.CreateDirectory($\"{DestinationPath}{dirPath.Remove(0, SourcePath.Length)}\");\n Directory.CreateDirectory($\"{backupPath}{dirPath.Remove(0, SourcePath.Length)}\");\n }\n foreach (string newPath in Directory.GetFiles(SourcePath, \"*.*\", SearchOption.AllDirectories))\n {\n if (!File.Exists($\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\"))\n File.Copy(newPath, $\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\");\n else\n File.Replace(newPath\n , $\"{ DestinationPath}{newPath.Remove(0, SourcePath.Length)}\"\n , $\"{ backupPath}{newPath.Remove(0, SourcePath.Length)}\", false);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 55981013,
"author": "Arash.Zandi",
"author_id": 3046588,
"author_profile": "https://Stackoverflow.com/users/3046588",
"pm_score": 0,
"selected": false,
"text": "<p>The code below is microsoft suggestion <a href=\"https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories\" rel=\"nofollow noreferrer\">how-to-copy-directories</a>\nand it is shared by dear <a href=\"https://stackoverflow.com/a/45199038/1951524\">@iato</a>\nbut it <strong>just copies sub directories and files of source folder recursively</strong> and <strong>doesn't copy the source folder it self</strong> (like right click -> copy ).</p>\n\n<p>but <strong>there is a tricky way</strong> below this answer :</p>\n\n<pre><code>private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs = true)\n {\n // Get the subdirectories for the specified directory.\n DirectoryInfo dir = new DirectoryInfo(sourceDirName);\n\n if (!dir.Exists)\n {\n throw new DirectoryNotFoundException(\n \"Source directory does not exist or could not be found: \"\n + sourceDirName);\n }\n\n DirectoryInfo[] dirs = dir.GetDirectories();\n // If the destination directory doesn't exist, create it.\n if (!Directory.Exists(destDirName))\n {\n Directory.CreateDirectory(destDirName);\n }\n\n // Get the files in the directory and copy them to the new location.\n FileInfo[] files = dir.GetFiles();\n foreach (FileInfo file in files)\n {\n string temppath = Path.Combine(destDirName, file.Name);\n file.CopyTo(temppath, false);\n }\n\n // If copying subdirectories, copy them and their contents to new location.\n if (copySubDirs)\n {\n foreach (DirectoryInfo subdir in dirs)\n {\n string temppath = Path.Combine(destDirName, subdir.Name);\n DirectoryCopy(subdir.FullName, temppath, copySubDirs);\n }\n }\n }\n</code></pre>\n\n<p>if you want to copy <strong>contents</strong> of <strong>source</strong> folder and <strong>subfolders</strong> recursively you can simply use it like this :</p>\n\n<pre><code>string source = @\"J:\\source\\\";\nstring dest= @\"J:\\destination\\\";\nDirectoryCopy(source, dest);\n</code></pre>\n\n<p>but if you want to copy <strong>the source directory it self</strong> (similar that you have right clicked on source folder and clicked copy then in the destination folder you clicked paste) you should use like this :</p>\n\n<pre><code> string source = @\"J:\\source\\\";\n string dest= @\"J:\\destination\\\";\n DirectoryCopy(source, Path.Combine(dest, new DirectoryInfo(source).Name));\n</code></pre>\n"
},
{
"answer_id": 67476219,
"author": "Rahul Shukla",
"author_id": 7160482,
"author_profile": "https://Stackoverflow.com/users/7160482",
"pm_score": 0,
"selected": false,
"text": "<p>Below code to copy all files from source to destination of given pattern in same folder structure:</p>\n<pre><code>public static void Copy()\n {\n string sourceDir = @"C:\\test\\source\\";\n string destination = @"C:\\test\\destination\\";\n\n string[] textFiles = Directory.GetFiles(sourceDir, "*.txt", SearchOption.AllDirectories);\n\n foreach (string textFile in textFiles)\n {\n string fileName = textFile.Substring(sourceDir.Length);\n string directoryPath = Path.Combine(destination, Path.GetDirectoryName(fileName));\n if (!Directory.Exists(directoryPath))\n Directory.CreateDirectory(directoryPath);\n\n File.Copy(textFile, Path.Combine(directoryPath, Path.GetFileName(textFile)), true);\n }\n }\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/LlIax.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/LlIax.png\" alt=\"enter image description here\" /></a></p>\n"
},
{
"answer_id": 69069991,
"author": "kofifus",
"author_id": 460084,
"author_profile": "https://Stackoverflow.com/users/460084",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a concise and efficient solution:</p>\n<pre><code>namespace System.IO {\n public static class ExtensionMethods {\n\n public static void CopyTo(this DirectoryInfo srcPath, string destPath) {\n Directory.CreateDirectory(destPath);\n Parallel.ForEach(srcPath.GetDirectories("*", SearchOption.AllDirectories), \n srcInfo => Directory.CreateDirectory($"{destPath}{srcInfo.FullName[srcPath.FullName.Length..]}"));\n Parallel.ForEach(srcPath.GetFiles("*", SearchOption.AllDirectories), \n srcInfo => File.Copy(srcInfo.FullName, $"{destPath}{srcInfo.FullName[srcPath.FullName.Length..]}", true));\n });\n }\n\n }\n}\n</code></pre>\n<p>To use:</p>\n<pre><code>new DirectoryInfo(sourcePath).CopyTo(destinationPath);\n</code></pre>\n"
},
{
"answer_id": 69789211,
"author": "M. Mennan Kara",
"author_id": 1301389,
"author_profile": "https://Stackoverflow.com/users/1301389",
"pm_score": 0,
"selected": false,
"text": "<p>Just wanted to add my version. It can handle both directories and files, and can overwrite or skip if destination file exists.</p>\n<pre><code>public static void Copy(\n string source,\n string destination,\n string pattern = "*",\n bool includeSubFolders = true,\n bool overwrite = true,\n bool overwriteOnlyIfSourceIsNewer = false)\n{\n if (File.Exists(source))\n {\n // Source is a file, copy and leave\n CopyFile(source, destination);\n return;\n }\n\n if (!Directory.Exists(source))\n {\n throw new DirectoryNotFoundException($"Source directory does not exists: `{source}`");\n }\n\n var files = Directory.GetFiles(\n source,\n pattern,\n includeSubFolders ?\n SearchOption.AllDirectories :\n SearchOption.TopDirectoryOnly);\n\n foreach (var file in files)\n {\n var newFile = file.Replace(source, destination);\n CopyFile(file, newFile, overwrite, overwriteOnlyIfSourceIsNewer);\n }\n}\n\nprivate static void CopyFile(\n string source,\n string destination,\n bool overwrite = true,\n bool overwriteIfSourceIsNewer = false)\n{\n if (!overwrite && File.Exists(destination))\n {\n return;\n }\n\n if (overwriteIfSourceIsNewer && File.Exists(destination))\n {\n var sourceLastModified = File.GetLastWriteTimeUtc(source);\n var destinationLastModified = File.GetLastWriteTimeUtc(destination);\n if (sourceLastModified <= destinationLastModified)\n {\n return;\n }\n\n CreateDirectory(destination);\n File.Copy(source, destination, overwrite);\n return;\n }\n\n CreateDirectory(destination);\n File.Copy(source, destination, overwrite);\n}\n\nprivate static void CreateDirectory(string filePath)\n{\n var targetDirectory = Path.GetDirectoryName(filePath);\n if (targetDirectory != null && !Directory.Exists(targetDirectory))\n {\n Directory.CreateDirectory(targetDirectory);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 70086547,
"author": "Rui Caramalho",
"author_id": 10756362,
"author_profile": "https://Stackoverflow.com/users/10756362",
"pm_score": 0,
"selected": false,
"text": "<p>Properties of this code:</p>\n<ul>\n<li>No parallel task, is less performant, but the idea is to treat file by file, so you can log or stop.</li>\n<li>Can skip hiddden files</li>\n<li>Can skip by modified date</li>\n<li>Can break or not (you chose) on a file copy error</li>\n<li>Uses Buffer of 64K for SMB and <code>FileShare.ReadWrite</code> to avoid locks</li>\n<li>Personalize your Exceptions Message</li>\n<li>For Windows</li>\n</ul>\n<blockquote>\n<p><em><strong>Notes</strong></em><br />\n<code>ExceptionToString()</code> is a personal extension that tries to get inner exceptions and display stack. Replace it for <code>ex.Message</code> or any other code.<br />\n<code>log4net.ILog _log</code> I use ==Log4net== You can make your Log in a different way.</p>\n</blockquote>\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Recursive Directory Copy\n/// </summary>\n/// <param name="fromPath"></param>\n/// <param name="toPath"></param>\n/// <param name="continueOnException">on error, continue to copy next file</param>\n/// <param name="skipHiddenFiles">To avoid files like thumbs.db</param>\n/// <param name="skipByModifiedDate">Does not copy if the destiny file has the same or more recent modified date</param>\n/// <remarks>\n/// </remarks>\npublic static void CopyEntireDirectory(string fromPath, string toPath, bool continueOnException = false, bool skipHiddenFiles = true, bool skipByModifiedDate = true)\n{\n log4net.ILog _log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n string nl = Environment.NewLine;\n\n string sourcePath = "";\n string destPath = "";\n string _exMsg = "";\n\n void TreateException(Exception ex)\n {\n _log.Warn(_exMsg);\n if (continueOnException == false)\n {\n throw new Exception($"{_exMsg}{nl}----{nl}{ex.ExceptionToString()}");\n }\n }\n\n try\n {\n foreach (string fileName in Directory.GetFileSystemEntries(fromPath, "*", SearchOption.AllDirectories))\n {\n sourcePath = fileName;\n destPath = Regex.Replace(fileName, "^" + Regex.Escape(fromPath), toPath);\n\n Directory.CreateDirectory(Path.GetDirectoryName(destPath));\n \n _log.Debug(FileCopyStream(sourcePath, destPath,skipHiddenFiles,skipByModifiedDate));\n }\n }\n // Directory must be less than 148 characters, File must be less than 261 characters\n catch (PathTooLongException)\n {\n throw new Exception($"Both paths must be less than 148 characters:{nl}{sourcePath}{nl}{destPath}");\n }\n // Not enough disk space. Cancel further copies\n catch (IOException ex) when ((ex.HResult & 0xFFFF) == 0x27 || (ex.HResult & 0xFFFF) == 0x70)\n {\n throw new Exception($"Not enough disk space:{nl}'{toPath}'");\n }\n // used by another process\n catch (IOException ex) when ((uint)ex.HResult == 0x80070020)\n {\n _exMsg = $"File is being used by another process:{nl}'{destPath}'{nl}{ex.Message}";\n TreateException(ex);\n }\n catch (UnauthorizedAccessException ex)\n {\n _exMsg = $"Unauthorized Access Exception:{nl}from:'{sourcePath}'{nl}to:{destPath}";\n TreateException(ex);\n }\n catch (Exception ex)\n {\n _exMsg = $"from:'{sourcePath}'{nl}to:{destPath}";\n TreateException(ex);\n }\n}\n\n/// <summary>\n/// File Copy using Stream 64K and trying to avoid locks with fileshare\n/// </summary>\n/// <param name="sourcePath"></param>\n/// <param name="destPath"></param>\n/// <param name="skipHiddenFiles">To avoid files like thumbs.db</param>\n/// <param name="skipByModifiedDate">Does not copy if the destiny file has the same or more recent modified date</param>\npublic static string FileCopyStream(string sourcePath, string destPath, bool skipHiddenFiles = true, bool skipByModifiedDate = true)\n{\n // Buffer should be 64K = 65536 bytes \n // Increasing the buffer size beyond 64k will not help in any circunstance,\n // as the underlying SMB protocol does not support buffer lengths beyond 64k."\n byte[] buffer = new byte[65536];\n\n if (!File.Exists(sourcePath))\n return $"is not a file: '{sourcePath}'";\n\n FileInfo sourcefileInfo = new FileInfo(sourcePath);\n FileInfo destFileInfo = null;\n if (File.Exists(destPath))\n destFileInfo = new FileInfo(destPath);\n\n if (skipHiddenFiles)\n {\n if (sourcefileInfo.Attributes.HasFlag(FileAttributes.Hidden))\n return $"Hidden File Not Copied: '{sourcePath}'";\n }\n\n using (FileStream input = sourcefileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n using (FileStream output = new FileStream(destPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite, buffer.Length))\n {\n if (skipByModifiedDate && destFileInfo != null)\n {\n if (destFileInfo.LastWriteTime < sourcefileInfo.LastWriteTime)\n {\n input.CopyTo(output, buffer.Length);\n destFileInfo.LastWriteTime = sourcefileInfo.LastWriteTime;\n return $"Replaced: '{sourcePath}'";\n }\n else\n {\n return $"NOT replaced (more recent or same file): '{sourcePath}'";\n }\n }\n else\n {\n input.CopyTo(output, buffer.Length);\n destFileInfo = new FileInfo(destPath);\n destFileInfo.LastWriteTime = sourcefileInfo.LastWriteTime;\n return $"New File: '{sourcePath}'";\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 73630610,
"author": "Rafi Henig",
"author_id": 9369606,
"author_profile": "https://Stackoverflow.com/users/9369606",
"pm_score": 0,
"selected": false,
"text": "<p>For UWP and Winui 3 (WindowsAppSdk) using <strong>Async</strong> API:</p>\n<pre><code>public async Task CopyAsync(StorageFolder source, StorageFolder dest)\n{\n foreach (var item in await source.GetItemsAsync())\n\n if (item is StorageFile file)\n await file.CopyAsync(dest);\n\n else if (item is StorageFolder folder)\n await CopyAsync(folder, await dest.CreateFolderAsync(folder.Name, CreationCollisionOption.OpenIfExists));\n}\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
]
| I want to copy the entire contents of a directory from one location to another in C#.
There doesn't appear to be a way to do this using `System.IO` classes without lots of recursion.
There is a method in VB that we can use if we add a reference to `Microsoft.VisualBasic`:
```
new Microsoft.VisualBasic.Devices.Computer().
FileSystem.CopyDirectory( sourceFolder, outputFolder );
```
This seems like a rather ugly hack. Is there a better way? | Much easier
```
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath));
}
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(sourcePath, "*.*",SearchOption.AllDirectories))
{
File.Copy(newPath, newPath.Replace(sourcePath, targetPath), true);
}
}
``` |
58,750 | <p>Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA?</p>
| [
{
"answer_id": 58756,
"author": "Matthias Winkelmann",
"author_id": 4494,
"author_profile": "https://Stackoverflow.com/users/4494",
"pm_score": 2,
"selected": false,
"text": "<p>No. But why don't you just use your webserver's logs? The value of GA is not in the data they collect, but the aggregation/analysis. That's why it's not called Google Raw Data.</p>\n"
},
{
"answer_id": 68766,
"author": "Shermozle",
"author_id": 10788,
"author_profile": "https://Stackoverflow.com/users/10788",
"pm_score": 5,
"selected": true,
"text": "<p>No you can't get the raw logs, but there's nothing stopping you from getting the exact same data logged to your own web server logs. Have a look at the <a href=\"https://ssl.google-analytics.com/urchin.js\" rel=\"noreferrer\">Urchin code</a> and borrow that, changing the following two lines to point to your web server instead.</p>\n\n<pre><code>var _ugifpath2=\"http://www.google-analytics.com/__utm.gif\";\nif (_udl.protocol==\"https:\") _ugifpath2=\"https://ssl.google-analytics.com/__utm.gif\";\n</code></pre>\n\n<p>You'll want to create a <code>__utm.gif</code> file so that they don't show up in the logs as 404s.</p>\n\n<p>Obviously you'll need to parse the variables out of the hits into your web server logs. The log line in Apache looks something like this. You'll have lots of \"fun\" parsing out all the various stuff you want from that, but everything Google Analytics gets from the basic JavaScript tagging comes in like this.</p>\n\n<pre><code>127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] \"GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0\" 200 35 \"http://www.mydomain.com/urlgoeshere/\" \"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19\"\n</code></pre>\n"
},
{
"answer_id": 76948,
"author": "Adam Hopkinson",
"author_id": 12280,
"author_profile": "https://Stackoverflow.com/users/12280",
"pm_score": 1,
"selected": false,
"text": "<p>You can get the Analytics data, but it'll take a bit of hacking.</p>\n\n<p>In any analytics report, click the 'email' button at the top of the screen. Set up the email to go to your address (or a new address on your server) and change the format to csv or xml.</p>\n\n<p>Then, you can use php (or another language) to check the email account, parse the email and import the attachment to your system.</p>\n\n<p>There's an article entitled 'Incoming mail and PHP' on evolt.org: <a href=\"http://evolt.org/incoming_mail_and_php\" rel=\"nofollow noreferrer\">http://evolt.org/incoming_mail_and_php</a></p>\n"
},
{
"answer_id": 641676,
"author": "MRG",
"author_id": 46281,
"author_profile": "https://Stackoverflow.com/users/46281",
"pm_score": 2,
"selected": false,
"text": "<p>Please have a look on this article which explains a hack to get Google analytics data.\n<a href=\"http://blogoscoped.com/archive/2008-01-17-n73.html\" rel=\"nofollow noreferrer\">http://blogoscoped.com/archive/2008-01-17-n73.html</a></p>\n\n<p>Also If you can wait for sometime then official Google analytics blog says that they are working on data export api but currently it is in Private Beta.\n<a href=\"http://analytics.blogspot.com/2008/10/more-enterprise-class-features-added-to.html\" rel=\"nofollow noreferrer\">http://analytics.blogspot.com/2008/10/more-enterprise-class-features-added-to.html</a></p>\n"
},
{
"answer_id": 11332938,
"author": "Jordan Brough",
"author_id": 58876,
"author_profile": "https://Stackoverflow.com/users/58876",
"pm_score": 2,
"selected": false,
"text": "<p>Not exactly the same as raw vs aggregated, but it seems that \"unsampled\" data is only available to Premium accounts: </p>\n\n<p>\"Unsampled Reports are only available in Premium accounts using the latest version of Google Analytics.\"<br>\n<a href=\"http://support.google.com/analytics/bin/answer.py?hl=en&answer=2601061\" rel=\"nofollow\">http://support.google.com/analytics/bin/answer.py?hl=en&answer=2601061</a></p>\n"
},
{
"answer_id": 15346499,
"author": "Kevin Borders",
"author_id": 1676044,
"author_profile": "https://Stackoverflow.com/users/1676044",
"pm_score": 0,
"selected": false,
"text": "<p>No, but there are other paid services like <a href=\"https://mixpanel.com/docs/api-documentation/data-export-api\" rel=\"nofollow\" title=\"Mixpanel Data Export API\">Mixpanel</a> and <a href=\"http://support.kissmetrics.com/apis/data/data-export-setup\" rel=\"nofollow\" title=\"KISSmetrics Data Export\">KISSmetrics</a> that have data export APIs. Much easier than trying to build your own analytics service, but costs money.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/370899/"
]
| Is it possible to obtain raw logs from Google Analytic? Is there any tool that can generate the raw logs from GA? | No you can't get the raw logs, but there's nothing stopping you from getting the exact same data logged to your own web server logs. Have a look at the [Urchin code](https://ssl.google-analytics.com/urchin.js) and borrow that, changing the following two lines to point to your web server instead.
```
var _ugifpath2="http://www.google-analytics.com/__utm.gif";
if (_udl.protocol=="https:") _ugifpath2="https://ssl.google-analytics.com/__utm.gif";
```
You'll want to create a `__utm.gif` file so that they don't show up in the logs as 404s.
Obviously you'll need to parse the variables out of the hits into your web server logs. The log line in Apache looks something like this. You'll have lots of "fun" parsing out all the various stuff you want from that, but everything Google Analytics gets from the basic JavaScript tagging comes in like this.
```
127.0.0.1 - - [02/Oct/2008:10:17:18 +1000] "GET /__utm.gif?utmwv=1.3&utmn=172543292&utmcs=ISO-8859-1&utmsr=1280x1024&utmsc=32-bit&utmul=en-us&utmje=1&utmfl=9.0%20%20r124&utmdt=My%20Web%20Page&utmhn=www.mydomain.com&utmhid=979599568&utmr=-&utmp=/urlgoeshere/&utmac=UA-1715941-2&utmcc=__utma%3D113887236.511203954.1220404968.1222846275.1222906638.33%3B%2B__utmz%3D113887236.1222393496.27.2.utmccn%3D(organic)%7Cutmcsr%3Dgoogle%7Cutmctr%3Dsapphire%2Btechnologies%2Bsite%253Arumble.net%7Cutmcmd%3Dorganic%3B%2B HTTP/1.0" 200 35 "http://www.mydomain.com/urlgoeshere/" "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.19 (KHTML, like Gecko) Chrome/0.2.153.1 Safari/525.19"
``` |
58,755 | <p>What is the best way to do per-user database connections in <code>Rails</code>? </p>
<p>I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible.</p>
| [
{
"answer_id": 58767,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001397\" rel=\"nofollow noreferrer\">ActiveRecord::Base.establish_connection</a>. That's how you connect to a different database server. I can't be of much more help since I don't know how you recognize the user or map it to it's database, but I suppose a master database will have that info (and the connection info should be on the database.yml file).</p>\n\n<p>Best of luck.</p>\n"
},
{
"answer_id": 59063,
"author": "Kevin Kaske",
"author_id": 2737,
"author_profile": "https://Stackoverflow.com/users/2737",
"pm_score": 4,
"selected": true,
"text": "<p>Put something like this in your application controller. I'm using the subdomain plus \"_clientdb\" to pick the name of the database. I have all the databases using the same username and password, so I can grab that from the db config file.</p>\n\n<p>Hope this helps!</p>\n\n<pre><code>class ApplicationController < ActionController::Base\n\n before_filter :hijack_db\n\n def hijack_db\n db_name = request.subdomains.first + \"_clientdb\"\n\n # lets manually connect to the proper db\n ActiveRecord::Base.establish_connection(\n :adapter => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['adapter'],\n :host => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['host'],\n :username => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['username'],\n :password => ActiveRecord::Base.configurations[ENV[\"RAILS_ENV\"]]['password'],\n :database => db_name\n )\n end\nend\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58755",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/624/"
]
| What is the best way to do per-user database connections in `Rails`?
I realize this is a poor Rails design practice, but we're gradually replacing an existing web application that uses one database per user. A complete redesign/rewrite is not feasible. | Put something like this in your application controller. I'm using the subdomain plus "\_clientdb" to pick the name of the database. I have all the databases using the same username and password, so I can grab that from the db config file.
Hope this helps!
```
class ApplicationController < ActionController::Base
before_filter :hijack_db
def hijack_db
db_name = request.subdomains.first + "_clientdb"
# lets manually connect to the proper db
ActiveRecord::Base.establish_connection(
:adapter => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['adapter'],
:host => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['host'],
:username => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['username'],
:password => ActiveRecord::Base.configurations[ENV["RAILS_ENV"]]['password'],
:database => db_name
)
end
end
``` |
58,774 | <p>I want to paste something I have cut from my desktop into a file open in Vi.</p>
<p>But if I paste the tabs embed on top of each other across the page.</p>
<p>I think it is some sort of visual mode change but can't find the command.</p>
| [
{
"answer_id": 58788,
"author": "JayG",
"author_id": 5823,
"author_profile": "https://Stackoverflow.com/users/5823",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using VIM, you can use \"*p (i.e. double quotes, asterisk, letter p).</p>\n"
},
{
"answer_id": 58794,
"author": "Antti Kissaniemi",
"author_id": 2948,
"author_profile": "https://Stackoverflow.com/users/2948",
"pm_score": 7,
"selected": true,
"text": "<h2>If you're using plain vi:</h2>\n<p>You probably have <code>autoindent</code> on. To turn it off while pasting:</p>\n<pre><code><Esc> :set noai\n\n<paste all you want>\n\n<Esc> :set ai\n</code></pre>\n<p>I have in my <code>.exrc</code> the following shortcuts:</p>\n<pre><code>map ^P :set noai^M\nmap ^N :set ai^M\n</code></pre>\n<p>Note that these have to be the actual control characters - insert them using <kbd>Ctrl</kbd>-<kbd>V</kbd> <kbd>Ctrl</kbd>-<kbd>P</kbd> and so on.</p>\n<h2>If you're using vim:</h2>\n<p>Use the <a href=\"http://www.vim.org/htmldoc/options.html#%27paste%27\" rel=\"noreferrer\"><code>paste</code></a> option. In addition to disabling <code>autoindent</code> it will also set other options such as <code>textwidth</code> and <code>wrapmargin</code> to paste-friendly defaults:</p>\n<pre><code><Esc> :set paste\n\n<paste all you want>\n\n<Esc> :set nopaste\n</code></pre>\n<p>You can also set a key to toggle the paste mode. My <code>.vimrc</code> has the following line:</p>\n<pre><code>set pastetoggle=<C-P> " Ctrl-P toggles paste mode\n</code></pre>\n"
},
{
"answer_id": 59804,
"author": "Edward Tanguay",
"author_id": 4639,
"author_profile": "https://Stackoverflow.com/users/4639",
"pm_score": 0,
"selected": false,
"text": "<p>I found that if I copy tabbed lines first into a text editor and then recopy them from there to vim, then the tabs are correct.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6096/"
]
| I want to paste something I have cut from my desktop into a file open in Vi.
But if I paste the tabs embed on top of each other across the page.
I think it is some sort of visual mode change but can't find the command. | If you're using plain vi:
-------------------------
You probably have `autoindent` on. To turn it off while pasting:
```
<Esc> :set noai
<paste all you want>
<Esc> :set ai
```
I have in my `.exrc` the following shortcuts:
```
map ^P :set noai^M
map ^N :set ai^M
```
Note that these have to be the actual control characters - insert them using `Ctrl`-`V` `Ctrl`-`P` and so on.
If you're using vim:
--------------------
Use the [`paste`](http://www.vim.org/htmldoc/options.html#%27paste%27) option. In addition to disabling `autoindent` it will also set other options such as `textwidth` and `wrapmargin` to paste-friendly defaults:
```
<Esc> :set paste
<paste all you want>
<Esc> :set nopaste
```
You can also set a key to toggle the paste mode. My `.vimrc` has the following line:
```
set pastetoggle=<C-P> " Ctrl-P toggles paste mode
``` |
58,831 | <p>My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:</p>
<pre><code>select PTNO,PTNM,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
</code></pre>
<p>and here it is after the fix:</p>
<pre><code>select PTNO,PTNM,PARTS.CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
</code></pre>
<p>The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS.
Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity.
Am I wrong, or just not thinking about this problem correctly?</p>
<p>Update:</p>
<p>Here's a revised example, where the ambiguity error is not thrown:</p>
<pre><code>CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER);
CREATE TABLE CATEGORIES(CATCD NUMBER);
CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER);
select PTNO,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD)
left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ;
</code></pre>
<p>Anybody have a clue?</p>
| [
{
"answer_id": 58896,
"author": "hollystyles",
"author_id": 2083160,
"author_profile": "https://Stackoverflow.com/users/2083160",
"pm_score": 0,
"selected": false,
"text": "<p>It is generally advised to be specific and fully qualify all column names anyway, as it saves the optimizer a little work. Certainly in SQL Server.</p>\n\n<p>From what I can gleen from the <a href=\"http://www.oracle.com/technology/index.html\" rel=\"nofollow noreferrer\">Oracle docs</a>, it seems it will only throw if you select the column name twice in the select list, or once in the select list and then again elsewhere like an order by clause.</p>\n\n<p>Perhaps you have uncovered an 'undocumented feature' :)</p>\n"
},
{
"answer_id": 58902,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 2,
"selected": false,
"text": "<p>Interesting in SQL server that throws an error (as it should)</p>\n\n<pre><code>select id\nfrom sysobjects s\nleft join syscolumns c on s.id = c.id\n</code></pre>\n\n<p>Server: Msg 209, Level 16, State 1, Line 1\nAmbiguous column name 'id'.</p>\n\n<pre><code>select id\nfrom sysobjects \nleft join syscolumns on sysobjects.id = syscolumns.id\n</code></pre>\n\n<p>Server: Msg 209, Level 16, State 1, Line 1\nAmbiguous column name 'id'.</p>\n"
},
{
"answer_id": 58907,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>Here's the query (simplified version) </p>\n</blockquote>\n\n<p>I think by simplifying the query you removed the real cause of the bug :-)</p>\n\n<p>What oracle version are you using? Oracle 10g ( 10.2.0.1.0 ) gives: </p>\n\n<pre><code>create table parts (ptno number , ptnm number , catcd number); \ncreate table CATEGORIES (catcd number);\n\nselect PTNO,PTNM,CATCD from PARTS \nleft join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);\n</code></pre>\n\n<p>I get ORA-00918: column ambiguously defined</p>\n"
},
{
"answer_id": 58924,
"author": "user2752",
"author_id": 2752,
"author_profile": "https://Stackoverflow.com/users/2752",
"pm_score": 1,
"selected": false,
"text": "<p>I am using Oracle 9.2.0.8.0. and it does give the error \"ORA-00918: column ambiguously defined\".</p>\n"
},
{
"answer_id": 58929,
"author": "Troels Arvin",
"author_id": 4462,
"author_profile": "https://Stackoverflow.com/users/4462",
"pm_score": 0,
"selected": false,
"text": "<p>Like HollyStyles, I cannot find anything in the Oracle docs which can explain what you are seeing.</p>\n\n<p>PostgreSQL, DB2, MySQL and MSSQL all refuse to run the first query, as it's ambiguous.</p>\n"
},
{
"answer_id": 58957,
"author": "Laith",
"author_id": 5961,
"author_profile": "https://Stackoverflow.com/users/5961",
"pm_score": 2,
"selected": false,
"text": "<p>From my experience if you create a query like this the data result will pull CATCD from the right side of the join not the left when there is a field overlap like this. </p>\n\n<p>So since this join will have all records from PARTS with only some pull through from CATEGORIES you will have NULL in the CATCD field any time there is no data on the right side.</p>\n\n<p>By explicitly defining the column as from PARTS (ie left side) you will get a non null value assuming that the field has data in PARTS.</p>\n\n<p>Remember that with LEFT JOIN you are only guarantied data in fields from the left table, there may well be empty columns to the right.</p>\n"
},
{
"answer_id": 58998,
"author": "Ovesh",
"author_id": 3751,
"author_profile": "https://Stackoverflow.com/users/3751",
"pm_score": 0,
"selected": false,
"text": "<p>@Pat: I get the same error here for your query. My query is just a little bit more complicated than what I originally posted. I'm working on a reproducible simple example now. </p>\n"
},
{
"answer_id": 59733,
"author": "Chris Ammerman",
"author_id": 2729,
"author_profile": "https://Stackoverflow.com/users/2729",
"pm_score": 2,
"selected": true,
"text": "<p>I'm afraid I can't tell you why you're not getting an exception, but I can postulate as to why it chose CATEGORIES' version of the column over PARTS' version.</p>\n\n<blockquote>\n <p>As far as I understood, in the case of left joins, the \"main\" table in the query (PARTS) has precedence in ambiguity</p>\n</blockquote>\n\n<p>It's not clear whether by \"main\" you mean simply the left table in a left join, or the \"driving\" table, as you see the query conceptually... But in either case, what you see as the \"main\" table in the query as you've written it will not necessarily be the \"main\" table in the actual execution of that query.</p>\n\n<p>My guess is that Oracle is simply using the column from the first table it hits in executing the query. And since most individual operations in SQL do not require one table to be hit before the other, the DBMS will decide at parse time which is the most efficient one to scan first. Try getting an execution plan for the query. I suspect it may reveal that it's hitting CATEGORIES first and then PARTS.</p>\n"
},
{
"answer_id": 64169,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 2,
"selected": false,
"text": "<p>This may be a bug in the Oracle optimizer. I can reproduce the same behavior on the query with 3 tables. Intuitively it does seem that it should produce an error. If I rewrite it in either of the following ways, it does generate an error:</p>\n\n<p>(1) Using old-style outer join</p>\n\n<pre><code>select ptno, catcd\nfrom parts, categories, sections\nwhere categories.catcd (+) = parts.catcd\n and sections.seccd (+) = parts.seccd\n</code></pre>\n\n<p>(2) Explicitly isolating the two joins</p>\n\n<pre><code>select ptno, catcd\nfrom (\n select ptno, seccd, catcd\n from parts\n left join categories on (categories.CATCD=parts.CATCD) \n)\nleft join sections on (sections.SECCD=parts.SECCD)\n</code></pre>\n\n<p>I used DBMS_XPLAN to get details on the execution of the query, which did show something interesting. The plan is basically to outer join PARTS and CATEGORIES, project that result set, then outer join it to SECTIONS. The interesting part is that in the projection of the first outer join, it is only including PTNO and SECCD -- it is NOT including the CATCD from either of the first two tables. Therefore the final result is getting CATCD from the third table.</p>\n\n<p>But I don't know whether this is a cause or an effect.</p>\n"
},
{
"answer_id": 84785,
"author": "Mike McAllister",
"author_id": 16247,
"author_profile": "https://Stackoverflow.com/users/16247",
"pm_score": 0,
"selected": false,
"text": "<p>A bigger question you should be asking yourself is - why do I have a category code in the parts table that doesn't exist in the categories table?</p>\n"
},
{
"answer_id": 93855,
"author": "Myto",
"author_id": 17827,
"author_profile": "https://Stackoverflow.com/users/17827",
"pm_score": 1,
"selected": false,
"text": "<p>This is a known bug with some Oracle versions when using ANSI-style joins. The correct behavior would be to get an ORA-00918 error.</p>\n\n<p>It's always best to specify your table names anyway; that way your queries don't break when you happen to add a new column with a name that is also used in another table.</p>\n"
},
{
"answer_id": 7030915,
"author": "steve godfrey",
"author_id": 711571,
"author_profile": "https://Stackoverflow.com/users/711571",
"pm_score": 0,
"selected": false,
"text": "<p>This is a bug in Oracle 9i. If you join more than 2 tables using ANSI notation, it will not detect ambiguities in column names, and can return the wrong column if an alias isn't used. </p>\n\n<p>As has been mentioned already, it is fixed in 10g, so if an alias isn't used, an error will be returned.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3751/"
]
| My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:
```
select PTNO,PTNM,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
and here it is after the fix:
```
select PTNO,PTNM,PARTS.CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS.
Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity.
Am I wrong, or just not thinking about this problem correctly?
Update:
Here's a revised example, where the ambiguity error is not thrown:
```
CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER);
CREATE TABLE CATEGORIES(CATCD NUMBER);
CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER);
select PTNO,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD)
left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ;
```
Anybody have a clue? | I'm afraid I can't tell you why you're not getting an exception, but I can postulate as to why it chose CATEGORIES' version of the column over PARTS' version.
>
> As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity
>
>
>
It's not clear whether by "main" you mean simply the left table in a left join, or the "driving" table, as you see the query conceptually... But in either case, what you see as the "main" table in the query as you've written it will not necessarily be the "main" table in the actual execution of that query.
My guess is that Oracle is simply using the column from the first table it hits in executing the query. And since most individual operations in SQL do not require one table to be hit before the other, the DBMS will decide at parse time which is the most efficient one to scan first. Try getting an execution plan for the query. I suspect it may reveal that it's hitting CATEGORIES first and then PARTS. |
58,841 | <p>How can I get precompiled headers working with GCC?</p>
<p>I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on <a href="https://en.wikipedia.org/wiki/Cygwin" rel="nofollow noreferrer">Cygwin</a> GCC 3.4.4 and using 4.0 on <a href="https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29" rel="nofollow noreferrer">Ubuntu</a>.</p>
| [
{
"answer_id": 58987,
"author": "Paul",
"author_id": 5841,
"author_profile": "https://Stackoverflow.com/users/5841",
"pm_score": 3,
"selected": false,
"text": "<p>I have managed to get precompiled headers working under gcc once in the past, and I recall having problems then as well. The thing to remember is that gcc will ignore the file (header.h.gch or similar) if certain conditions are not met, a list of which can be found on the <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html\" rel=\"noreferrer\">gcc precompiled header documentation page</a>.</p>\n\n<p>Generally it's safest to have your build system compile the .gch file as a first step, with the same command line options and executable as the rest of your source. This ensures the file is up to date and that there are no subtle differences.</p>\n\n<p>It's probably also a good idea to get it working with a contrived example first, just to remove the possibility that your problems are specific to source code in your project.</p>\n"
},
{
"answer_id": 60577,
"author": "simon",
"author_id": 4875,
"author_profile": "https://Stackoverflow.com/users/4875",
"pm_score": 3,
"selected": false,
"text": "<p>Call GCC the same way as if you call it for your source file, but with a header file.</p>\n<p>E.g.,</p>\n<pre><code>g++ $(CPPFLAGS) test.h\n</code></pre>\n<p>This generates a file called <em>test.h.gch</em>.</p>\n<p>Every time GCC searches for <em>test.h</em>, it looks first for <em>test.h.gch</em> and if it finds it it uses it automatically.</p>\n<p>More information can be found under <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html\" rel=\"nofollow noreferrer\">GCC Precompiled Headers</a>.</p>\n"
},
{
"answer_id": 1191407,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 6,
"selected": false,
"text": "<p><a href=\"http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html\" rel=\"noreferrer\">Firstly, see the documentation here</a>.</p>\n\n<p>You compile headers just like any other file but you put the output inside a file with a suffix of <code>.gch</code>. </p>\n\n<p>So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called <code>stdafx.h.gch</code> anytime you include <code>stdafx.h</code></p>\n\n<p>Example:</p>\n\n<p>stdafx.h:</p>\n\n<pre><code>#include <string>\n#include <stdio.h>\n</code></pre>\n\n<p>a.cpp:</p>\n\n<pre><code>#include \"stdafx.h\"\nint main(int argc, char**argv)\n{\n std::string s = \"Hi\";\n return 0;\n}\n</code></pre>\n\n<p>Then compile as:</p>\n\n<blockquote>\n <p><code>> g++ -c stdafx.h -o stdafx.h.gch</code><br>\n <code>> g++ a.cpp</code><br>\n <code>> ./a.out</code></p>\n</blockquote>\n\n<p>Your compilation will work even if you remove stdafx.h after step 1.</p>\n"
},
{
"answer_id": 2935536,
"author": "User1",
"author_id": 125380,
"author_profile": "https://Stackoverflow.com/users/125380",
"pm_score": 6,
"selected": false,
"text": "<p>I have definitely had success. First, I used the following code:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <boost/xpressive/xpressive.hpp>\n#include <iostream>\n\nusing namespace std;\nusing namespace boost::xpressive;\n\n// A simple regular expression test\nint main()\n{\n std::string hello("Hello, World!");\n\n sregex rex = sregex::compile( "(\\\\w+) (\\\\w+)!" );\n smatch what;\n\n if( regex_match( hello, what, rex ) )\n {\n std::cout << what[0] << '\\n'; // Whole match\n std::cout << what[1] << '\\n'; // First capture\n std::cout << what[2] << '\\n'; // Second capture\n }\n return 0;\n}\n</code></pre>\n<p>This was just a <em><a href=\"https://en.wikipedia.org/wiki/%22Hello,_World!%22_program\" rel=\"nofollow noreferrer\">Hello, World!</a></em> program <a href=\"http://www.boost.org/doc/libs/1_43_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.examples\" rel=\"nofollow noreferrer\">from Boost Xpressive</a>. First, I compiled with the <code>-H</code> option in GCC. It showed an enormous list of headers that it used. Then, I took a look at the compile flags my IDE (<a href=\"https://en.wikipedia.org/wiki/Code::Blocks\" rel=\"nofollow noreferrer\">Code::Blocks</a>) was producing and saw something like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -Wall -fexceptions -g -c main.cpp -o obj/Debug/main.o\n</code></pre>\n<p>So I wrote a command to compile the <em>Xpressive.hpp</em> file with the exact same flags:</p>\n<pre class=\"lang-none prettyprint-override\"><code>sudo g++ -Wall -fexceptions -g /usr/local/include/boost/xpressive/xpressive.hpp\n</code></pre>\n<p>I compiled the original code again with the <code>-H</code> and got this output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ -Wall -fexceptions -H -g -c main.cpp -o obj/Debug/main.o\n\n! /usr/local/include/boost/xpressive/xpressive.hpp.gch\nmain.cpp\n. /usr/include/c++/4.4/iostream\n.. /usr/include/c++/4.4/x86_64-linux-gnu/bits/c++config.h\n.. /usr/include/c++/4.4/ostream\n.. /usr/include/c++/4.4/istream\nmain.cpp\n</code></pre>\n<p>The ! means that the compiler was able to use the precompiled header. An x means it was not able to use it. Using the appropriate compiler flags is crucial. I took off the -H and ran some speed tests. The precompiled header had an improvement from 14 seconds to 11 seconds. Not bad, but not great.</p>\n<p>Note: Here's <a href=\"http://www.boost.org/doc/libs/1_43_0/doc/html/xpressive/user_s_guide.html#boost_xpressive.user_s_guide.examples\" rel=\"nofollow noreferrer\">the example</a>. I couldn't get it to work in the post.</p>\n<p>BTW: I'm using the following <em>g++</em>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3\n</code></pre>\n"
},
{
"answer_id": 10756166,
"author": "psaghelyi",
"author_id": 315527,
"author_profile": "https://Stackoverflow.com/users/315527",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>-x</code> specifier for C++ precompiled headers is <code>-x c++-header</code>, not <code>-x c++</code>. Example usage of PCH follows.</p>\n\n<p><code>pch.h</code>:</p>\n\n<pre><code>// Put your common include files here: Boost, STL as well as your project's headers.\n</code></pre>\n\n<p><code>main.cpp</code>:</p>\n\n<pre><code>#include \"pch.h\"\n// Use the PCH here.\n</code></pre>\n\n<p>Generate the PCH like this:</p>\n\n<pre class=\"lang-sh prettyprint-override\"><code>$ g++ -x c++-header -o pch.h.gch -c pch.h\n</code></pre>\n\n<p>The <code>pch.h.gch</code> must be in the same directory as the <code>pch.h</code> in order to be used, so make sure that you execute the above command from the directory where <code>pch.h</code> is.</p>\n"
},
{
"answer_id": 60571708,
"author": "Íhor Mé",
"author_id": 2617351,
"author_profile": "https://Stackoverflow.com/users/2617351",
"pm_score": 2,
"selected": false,
"text": "<p><em>Make sure to <code>-include your_header.h</code></em></p>\n<p>This is how I precompiled and used <code>bits/stdc++.h</code> collection.</p>\n<p>Code</p>\n<pre><code>#include <bits/stdc++.h>\n</code></pre>\n<p>Then I located the lib by compiling my file with -H and looking at output</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable\n</code></pre>\n<p>where I saw</p>\n<pre class=\"lang-none prettyprint-override\"><code>. /usr/include/x86_64-linux-gnu/c++/7/bits/stdc++.h\n</code></pre>\n<p>So I made a new directory <code>bits</code> inside of current one and copied <code>stdc++.h</code> from there.</p>\n<p>Then I ran</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ bits/stdc++.h -O3 -std=c++14 -pthread\n</code></pre>\n<p>which generated <code>bits/stdc++.gch</code></p>\n<p>Normally I compiled my code via</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ sol.cpp -O3 -pthread -lm -std=c++14 -o executable\n</code></pre>\n<p>, but I had to modify that to</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ sol.cpp -include bits/stdc++.h -O3 -pthread -lm -std=c++14 -o executable\n</code></pre>\n<p>as it only resolved to <code>.gch</code> file instead of <code>.h</code> with <strong><code>-include bits/stdc++.h</code></strong>\nThat was key for me. Other thing to keep in mind is that you have to compile <code>*.h</code> header file with almost the same parameters as you compile your <code>*.cpp</code>. When I didn't include <code>-O3</code> or <code>-pthread</code> it ignored the <code>*.gch</code> precompiled header.</p>\n<p>To check if everything's correct you can measure time difference via comparing result of</p>\n<pre class=\"lang-none prettyprint-override\"><code>time g++ sol.cpp ...\n</code></pre>\n<p>or run</p>\n<pre class=\"lang-none prettyprint-override\"><code>g++ sol.cpp -H -O3 -pthread -lm -std=c++14 -o executable\n</code></pre>\n<p>again and look for header paths and if you now get <code>!</code> before library path, for example</p>\n<pre class=\"lang-none prettyprint-override\"><code>! ./bits/stdc++.h.gch\n....\n</code></pre>\n"
},
{
"answer_id": 65730829,
"author": "Brad Robinson",
"author_id": 77002,
"author_profile": "https://Stackoverflow.com/users/77002",
"pm_score": 0,
"selected": false,
"text": "<p>A subtle tip about the file extension that tripped me up, because I wasn't paying close enough attention: the <code>.gch</code> extension is added to the precompiled file's full name; it doesn't replace <code>.h</code>. If you get it wrong, the compiler won't find it and silently does not work.</p>\n<p>precomp.h => precomp.<strong>h.gch</strong></p>\n<p>Not:</p>\n<p>precomp.h => precomp.<strong>gch</strong></p>\n<p>Use GCC's <code>-H</code> to check if it's finding/using it.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5200/"
]
| How can I get precompiled headers working with GCC?
I have had no luck in my attempts and I haven't seen many good examples for how to set it up. I've tried on [Cygwin](https://en.wikipedia.org/wiki/Cygwin) GCC 3.4.4 and using 4.0 on [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29). | [Firstly, see the documentation here](http://gcc.gnu.org/onlinedocs/gcc/Precompiled-Headers.html).
You compile headers just like any other file but you put the output inside a file with a suffix of `.gch`.
So for example if you precompile stdafx.h you will have a precompiled header that will be automatically searched for called `stdafx.h.gch` anytime you include `stdafx.h`
Example:
stdafx.h:
```
#include <string>
#include <stdio.h>
```
a.cpp:
```
#include "stdafx.h"
int main(int argc, char**argv)
{
std::string s = "Hi";
return 0;
}
```
Then compile as:
>
> `> g++ -c stdafx.h -o stdafx.h.gch`
>
> `> g++ a.cpp`
>
> `> ./a.out`
>
>
>
Your compilation will work even if you remove stdafx.h after step 1. |
58,851 | <p>I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes.</p>
| [
{
"answer_id": 58892,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": false,
"text": "<p>I just tried the following:</p>\n\n<pre><code> $ cat gdbtest.c\n int abc = 43;\n\n int main()\n {\n abc = 10;\n }\n $ gcc -g -o gdbtest gdbtest.c\n $ gdb gdbtest\n ...\n (gdb) watch abc\n Hardware watchpoint 1: abc\n (gdb) r\n Starting program: /home/mweerden/gdbtest \n ...\n\n Old value = 43\n New value = 10\n main () at gdbtest.c:6\n 6 }\n (gdb) quit\n</code></pre>\n\n<p>So it seems possible, but you do appear to need some hardware support.</p>\n"
},
{
"answer_id": 59146,
"author": "asksol",
"author_id": 5577,
"author_profile": "https://Stackoverflow.com/users/5577",
"pm_score": 9,
"selected": true,
"text": "<p><em>watch</em> only breaks on write, <em>rwatch</em> let you break on read, and <em>awatch</em> let you break on read/write.</p>\n\n<p>You can set read watchpoints on memory locations:</p>\n\n<pre><code>gdb$ rwatch *0xfeedface\nHardware read watchpoint 2: *0xfeedface\n</code></pre>\n\n<p>but one limitation applies to the rwatch and awatch commands; you can't use gdb variables\nin expressions:</p>\n\n<pre><code>gdb$ rwatch $ebx+0xec1a04f\nExpression cannot be implemented with read/access watchpoint.\n</code></pre>\n\n<p>So you have to expand them yourself: </p>\n\n<pre><code>gdb$ print $ebx \n$13 = 0x135700\ngdb$ rwatch *0x135700+0xec1a04f\nHardware read watchpoint 3: *0x135700 + 0xec1a04f\ngdb$ c\nHardware read watchpoint 3: *0x135700 + 0xec1a04f\n\nValue = 0xec34daf\n0x9527d6e7 in objc_msgSend ()\n</code></pre>\n\n<p><strong>Edit:</strong> Oh, and by the way. You need either hardware <strong>or software support</strong>. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the <em>can-use-hw-watchpoints</em> environment setting. </p>\n\n<pre><code>gdb$ show can-use-hw-watchpoints\nDebugger's willingness to use watchpoint hardware is 1.\n</code></pre>\n"
},
{
"answer_id": 966525,
"author": "Smirnov",
"author_id": 89207,
"author_profile": "https://Stackoverflow.com/users/89207",
"pm_score": 5,
"selected": false,
"text": "<p>Assuming the first answer is referring to the C-like syntax <code>(char *)(0x135700 +0xec1a04f)</code> then the answer to do <code>rwatch *0x135700+0xec1a04f</code> is incorrect. The correct syntax is <code>rwatch *(0x135700+0xec1a04f)</code>.</p>\n\n<p>The lack of <code>()</code>s there caused me a great deal of pain trying to use watchpoints myself.</p>\n"
},
{
"answer_id": 17325119,
"author": "higgs241",
"author_id": 2438536,
"author_profile": "https://Stackoverflow.com/users/2438536",
"pm_score": 2,
"selected": false,
"text": "<p>Use watch to see when a variable is written to, rwatch when it is read and awatch when it is read/written from/to, as noted above. However, please note that to use this command, you must break the program, and the variable must be in scope when you've broken the program:</p>\n\n<blockquote>\n <p>Use the watch command. The argument to the watch command is an\n expression that is evaluated. This implies that the variabel you want\n to set a watchpoint on must be in the current scope. So, to set a\n watchpoint on a non-global variable, you must have set a breakpoint\n that will stop your program when the variable is in scope. You set the\n watchpoint after the program breaks.</p>\n</blockquote>\n"
},
{
"answer_id": 31202563,
"author": "Paolo M",
"author_id": 2508150,
"author_profile": "https://Stackoverflow.com/users/2508150",
"pm_score": 5,
"selected": false,
"text": "<p>What you're looking for is called a <em>watchpoint</em>.</p>\n\n<p><strong>Usage</strong> </p>\n\n<p><code>(gdb) watch foo</code>: watch the value of <strong>variable</strong> <code>foo</code></p>\n\n<p><code>(gdb) watch *(int*)0x12345678</code>: watch the value pointed by an <strong>address</strong>, casted to whatever type you want</p>\n\n<p><code>(gdb) watch a*b + c/d</code>: watch an arbitrarily <strong>complex expression</strong>, valid in the program's native language</p>\n\n<p>Watchpoints are of three kinds:</p>\n\n<ul>\n<li><strong>watch</strong>: gdb will break when a <em>write</em> occurs</li>\n<li><strong>rwatch</strong>: gdb will break wnen a <em>read</em> occurs</li>\n<li><strong>awatch</strong>: gdb will break in <em>both cases</em></li>\n</ul>\n\n<p>You may choose the more appropriate for your needs.</p>\n\n<p>For more information, check <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html\" rel=\"noreferrer\">this</a> out.</p>\n"
},
{
"answer_id": 70610117,
"author": "Singh",
"author_id": 13032809,
"author_profile": "https://Stackoverflow.com/users/13032809",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to what has already been answered/commented by <a href=\"https://stackoverflow.com/users/5577/asksol\">asksol</a> and <a href=\"https://stackoverflow.com/users/2508150/paolo-m\">Paolo M</a></p>\n<p>I didn't at first read understand, why do we need to cast the results. Though I read this: <a href=\"https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html\" rel=\"nofollow noreferrer\">https://sourceware.org/gdb/onlinedocs/gdb/Set-Watchpoints.html</a>, yet it wasn't intuitive to me..</p>\n<p>So I did an experiment to make the result clearer:\nCode: (Let's say that int main() is at Line 3; int i=0 is at Line 5 and other code.. is from Line 10)</p>\n<pre><code>int main()\n{\nint i = 0;\nint j;\ni = 3840 // binary 1100 0000 0000 to take into account endianness\nother code..\n}\n</code></pre>\n<p>then i started gdb with the executable file\nin my first attempt, i set the breakpoint on the location of variable without casting, following were the results displayed</p>\n<pre><code>Thread 1 "testing2" h\nBreakpoint 2 at 0x10040109b: file testing2.c, line 10.\n(gdb) s\n7 i = 3840;\n(gdb) p i\n$1 = 0\n(gdb) p &i\n$2 = (int *) 0xffffcbfc\n(gdb) watch *0xffffcbfc\nHardware watchpoint 3: *0xffffcbfc\n(gdb) s\n[New Thread 13168.0xa74]\n\nThread 1 "testing2" hit Breakpoint 2, main () at testing2.c:10\n10 b = a;\n(gdb) p i\n$3 = 3840\n(gdb) p *0xffffcbfc\n$4 = 3840\n(gdb) p/t *0xffffcbfc\n$5 = 111100000000\n</code></pre>\n<p>as we could see breakpoint was hit for line 10 which was set by me. gdb didn't break because although variable i underwent change yet the location being watched didn't change (due to endianness, since it continued to remain all 0's)</p>\n<p>in my second attempt, i did the casting on the address of the variable to watch for all the sizeof(int) bytes. this time:</p>\n<pre><code>(gdb) p &i\n$6 = (int *) 0xffffcbfc\n(gdb) p i\n$7 = 0\n(gdb) watch *(int *) 0xffffcbfc\nHardware watchpoint 6: *(int *) 0xffffcbfc\n(gdb) b 10\nBreakpoint 7 at 0x10040109b: file testing2.c, line 10.\n(gdb) i b\nNum Type Disp Enb Address What\n6 hw watchpoint keep y *(int *) 0xffffcbfc\n7 breakpoint keep y 0x000000010040109b in main at testing2.c:10\n(gdb) n\n[New Thread 21508.0x3c30]\n\nThread 1 "testing2" hit Hardware watchpoint 6: *(int *) 0xffffcbfc\n\nOld value = 0\nNew value = 3840\n\nThread 1 "testing2" hit Breakpoint 7, main () at testing2.c:10\n10 b = a;\n</code></pre>\n<p>gdb break since it detected the value has changed.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3022/"
]
| I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes. | *watch* only breaks on write, *rwatch* let you break on read, and *awatch* let you break on read/write.
You can set read watchpoints on memory locations:
```
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
```
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables
in expressions:
```
gdb$ rwatch $ebx+0xec1a04f
Expression cannot be implemented with read/access watchpoint.
```
So you have to expand them yourself:
```
gdb$ print $ebx
$13 = 0x135700
gdb$ rwatch *0x135700+0xec1a04f
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
gdb$ c
Hardware read watchpoint 3: *0x135700 + 0xec1a04f
Value = 0xec34daf
0x9527d6e7 in objc_msgSend ()
```
**Edit:** Oh, and by the way. You need either hardware **or software support**. Software is obviously much slower. To find out if your OS supports hardware watchpoints you can see the *can-use-hw-watchpoints* environment setting.
```
gdb$ show can-use-hw-watchpoints
Debugger's willingness to use watchpoint hardware is 1.
``` |
58,872 | <p>I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill...</p>
<p>So what kind of transformations would you do with them?</p>
| [
{
"answer_id": 58885,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 6,
"selected": true,
"text": "<p>If you have data in columns in a text file with <code>M-x delete-rectangle</code> or <code>M-x kill-rectangle</code> you can delete a single column of data. Similarly, <code>M-x yank-rectangle</code> will paste in a column of text.</p>\n\n<p>For example, take the following text:</p>\n\n<pre><code>1. alligator alphorn\n2. baboon bugle\n3. crocodile cornet\n4. dog didgeridoo\n5. elephant euphonium \n6. fish flugelhorn \n7. gopher guitar\n</code></pre>\n\n<p>Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter <code>M-x kill-rectangle</code> and you immediately have:</p>\n\n<pre><code>1. alphorn\n2. bugle\n3. cornet\n4. didgeridoo\n5. euphonium \n6. flugelhorn\n7. guitar\n</code></pre>\n\n<p>Next put the mark at the end of the top line, add a few spaces if required and enter <code>M-x yank-rectangle</code> and ta-da! You have re-ordered the columns:</p>\n\n<pre><code>1. alphorn alligator \n2. bugle baboon \n3. cornet crocodile \n4. didgeridoo dog \n5. euphonium elephant \n6. flugelhorn fish \n7. guitar gopher \n</code></pre>\n"
},
{
"answer_id": 59523,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 4,
"selected": false,
"text": "<p>I like to use rectangle for 2 main purposes, inserting the same text on every line, or killing a column of text (similar to Dave Webb's answer).</p>\n\n<p>There are 2 useful shortcuts for these, <code>C-x r k</code> will kill a rectangle, and <code>C-x r t</code> to insert (there are other rectangle commands with a <code>C-x r</code> prefix, but these are the ones I use).</p>\n\n<p>So let's say you want to take some code and format it so that you can post it in a Stack Overflow post... you need to prefix with 4 spaces. So, go to the beginning of the first line, <code>C-SPC</code> to mark, then go to the beginning of the last line and <code>C-x r t <SPC> <SPC> <SPC> <SPC> <RET></code>, and there you have it! Then you can just copy and paste it into Stack Overflow. I have run into more complex situations where this is useful, where you actually have text you want to insert on every line at a particular place.</p>\n\n<p>So the other situation like Dave Webb's situation, if you want to kill a rectangle, use <code>C-x r k</code> though, because it's just a lot quicker ;-)</p>\n\n<p>Also, according to my <a href=\"http://refcards.com/docs/gildeas/gnu-emacs/emacs-refcard-a4.pdf\" rel=\"nofollow noreferrer\">reference card</a> that I printed out when I first started, you can do the following:</p>\n\n<ul>\n<li><code>C-x r r</code>: copy to a register</li>\n<li><code>C-x r y</code>: yank a rectangle</li>\n<li><code>C-x r o</code>: open a rectangle, shifting text right (whatever that means...)</li>\n<li><code>C-x r c</code>: blank out a rectangle (I assume that means replace it with spaces, but you'd have to try it out to see)</li>\n<li><code>C-x r t</code>: prefix with text (as described above)</li>\n<li><code>C-x r k</code>: killing (as described above)</li>\n</ul>\n"
},
{
"answer_id": 23968635,
"author": "Adobe",
"author_id": 788700,
"author_profile": "https://Stackoverflow.com/users/788700",
"pm_score": 1,
"selected": false,
"text": "<p>In emacs24+ there's also function for numbering lines:</p>\n\n<pre><code>(rectangle-number-lines START END START-AT &optional FORMAT)\n\nInsert numbers in front of the region-rectangle.\n\nSTART-AT, if non-nil, should be a number from which to begin\ncounting. FORMAT, if non-nil, should be a format string to pass\nto `format' along with the line count. When called interactively\nwith a prefix argument, prompt for START-AT and FORMAT.\n</code></pre>\n\n<p>It is binded to <kbd>C-x r N</kbd> by default. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3785/"
]
| I've read in several places that the rectangle functions in emacs are very useful. I've read a bit about them, and I can't quite figure why. I mean, when you want to kill a paragraph, you mark the first row/column and then the last one, and that's actually a rectangle, right? But you can still use the normal kill...
So what kind of transformations would you do with them? | If you have data in columns in a text file with `M-x delete-rectangle` or `M-x kill-rectangle` you can delete a single column of data. Similarly, `M-x yank-rectangle` will paste in a column of text.
For example, take the following text:
```
1. alligator alphorn
2. baboon bugle
3. crocodile cornet
4. dog didgeridoo
5. elephant euphonium
6. fish flugelhorn
7. gopher guitar
```
Select from the a of alligator to the g of guitar. The beginning and end of the selection mark out two opposite corners of the rectangle. Enter `M-x kill-rectangle` and you immediately have:
```
1. alphorn
2. bugle
3. cornet
4. didgeridoo
5. euphonium
6. flugelhorn
7. guitar
```
Next put the mark at the end of the top line, add a few spaces if required and enter `M-x yank-rectangle` and ta-da! You have re-ordered the columns:
```
1. alphorn alligator
2. bugle baboon
3. cornet crocodile
4. didgeridoo dog
5. euphonium elephant
6. flugelhorn fish
7. guitar gopher
``` |
58,916 | <p>Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company.
Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help.</p>
| [
{
"answer_id": 58943,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not answering your question, but foreign Keys <em>is</em> the way to go, why is it not an option?</p>\n\n<p>As for nested transactions they are:</p>\n\n<pre><code>BEGIN\n delete from Employee where departmentId = 1;\n BEGIN\n delete from Department where companyId = 2;\n BEGIN\n delete from Company where companyId = 2;\n END\n END\nEND\n</code></pre>\n\n<p>Programmatically it looks different of course, but that'd depend on the platform you are using</p>\n"
},
{
"answer_id": 58974,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not sure why you need nested transactions here. You only need one actual transaction:</p>\n\n<pre><code>BEGIN TRAN\n\nDELETE FROM Employee\n FROM Employee\n INNER JOIN Department ON Employee.DepartmentID = Department.DepartmentID\n INNER JOIN Company ON Department.CompanyID = Company.CompanyID\n WHERE Company.CompanyID = @CompanyID\n\nDELETE FROM Department\n FROM Department\n INNER JOIN Company ON Department.CompanyID = Company.CompanyID\n WHERE Company.CompanyID = @CompanyID\n\nDELETE FROM Company\n WHERE Company.CompanyID = @CompanyID\n\nCOMMIT TRAN\n</code></pre>\n\n<p>Note the double FROM, that is not a typo, it's the correct SQL syntax for performing a JOIN in a DELETE.</p>\n\n<p>Each statement is atomic, either the entire DELETE will succeed or fail, which isn't that important in this case because the entire batch will either succeed or fail.</p>\n\n<p>BTW- I think you had your relationships backwards. The Department would not have an EmployeeID, the Employee would have a DepartmentID.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1360/"
]
| Suppose I have a table called Companies that has a DepartmentID column. There's also a Departaments table that has as EmployeeID column. Of course I have an Employee table as well. The problem is that I want to delete a company, so first i have to delete all the employees for every departament and then all the departaments in the company.
Cascade Delete is not an option, therefore i wish to use nested transactions. I'm new to SQL so I would appreciate your help. | I'm not sure why you need nested transactions here. You only need one actual transaction:
```
BEGIN TRAN
DELETE FROM Employee
FROM Employee
INNER JOIN Department ON Employee.DepartmentID = Department.DepartmentID
INNER JOIN Company ON Department.CompanyID = Company.CompanyID
WHERE Company.CompanyID = @CompanyID
DELETE FROM Department
FROM Department
INNER JOIN Company ON Department.CompanyID = Company.CompanyID
WHERE Company.CompanyID = @CompanyID
DELETE FROM Company
WHERE Company.CompanyID = @CompanyID
COMMIT TRAN
```
Note the double FROM, that is not a typo, it's the correct SQL syntax for performing a JOIN in a DELETE.
Each statement is atomic, either the entire DELETE will succeed or fail, which isn't that important in this case because the entire batch will either succeed or fail.
BTW- I think you had your relationships backwards. The Department would not have an EmployeeID, the Employee would have a DepartmentID. |
58,925 | <p>I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control?</p>
| [
{
"answer_id": 58931,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 6,
"selected": true,
"text": "<p>This appears to work.</p>\n\n<pre><code>public string RenderControlToHtml(Control ControlToRender)\n{\n System.Text.StringBuilder sb = new System.Text.StringBuilder();\n System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);\n System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);\n ControlToRender.RenderControl(htmlWriter);\n return sb.ToString();\n}\n</code></pre>\n"
},
{
"answer_id": 59323,
"author": "a7drew",
"author_id": 4239,
"author_profile": "https://Stackoverflow.com/users/4239",
"pm_score": 3,
"selected": false,
"text": "<p>If your control is a web user control, this is how you can get to the HTML it emits from another page or handler:</p>\n\n<pre><code>public void GetHtmlFromMySweetControl(HttpContext context)\n{\n HttpRequest httpRequest = context.Request;\n HttpResponse httpResponse = context.Response;\n\n string foo = httpRequest[\"foo\"];\n\n Page pageHolder = new Page();\n string path = \"~/usercontrols/MySweetControl.ascx\";\n MySweetControl ctrl = (MySweetControl)pageHolder.LoadControl(path);\n ctrl.BindProducts(foo);\n pageHolder.Controls.Add(ctrl);\n\n StringWriter sw = new StringWriter();\n context.Server.Execute(pageHolder, sw, false);\n httpResponse.Write(sw.ToString());\n}\n</code></pre>\n"
},
{
"answer_id": 32765865,
"author": "avs099",
"author_id": 1246870,
"author_profile": "https://Stackoverflow.com/users/1246870",
"pm_score": 4,
"selected": false,
"text": "<p>Accepted answer by <code>David Basarab</code> will not work if control is not part of the page. <code>a7drew</code>'s answer seems unnecessary complex - no need in <code>Context</code> or <code>Server.Execute</code>.</p>\n\n<pre><code>private string RenderControl()\n{\n var sb = new System.Text.StringBuilder();\n using (var stWriter = new System.IO.StringWriter(sb))\n using (var htmlWriter = new HtmlTextWriter(stWriter))\n {\n var p = new Page();\n var ctrl = (YourControl)p.LoadControl(\"~/controls/building blocks/YourControl.ascx\");\n ctrl.Visible = true;\n\n // do your own init logic if needed\n\n p.Controls.Add(ctrl);\n ctrl.RenderControl(htmlWriter);\n return sb.ToString();\n }\n}\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58925",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2469/"
]
| I have any ASP.NET control. I want the HTML string how to do I get the HTML string of the control? | This appears to work.
```
public string RenderControlToHtml(Control ControlToRender)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
ControlToRender.RenderControl(htmlWriter);
return sb.ToString();
}
``` |
58,937 | <p>Using VB.NET, how do I toggle the state of Caps Lock? </p>
| [
{
"answer_id": 58941,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 4,
"selected": true,
"text": "<p>From: <a href=\"http://www.vbforums.com/showthread.php?referrerid=61394&t=537891\" rel=\"noreferrer\">http://www.vbforums.com/showthread.php?referrerid=61394&t=537891</a></p>\n\n<pre><code>Imports System.Runtime.InteropServices\n\nPublic Class Form2\n\n Private Declare Sub keybd_event Lib \"user32\" ( _\n ByVal bVk As Byte, _\n ByVal bScan As Byte, _\n ByVal dwFlags As Integer, _\n ByVal dwExtraInfo As Integer _\n )\n Private Const VK_CAPITAL As Integer = &H14\n Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1\n Private Const KEYEVENTF_KEYUP As Integer = &H2\n\n Private Sub Button1_Click( _\n ByVal sender As System.Object, _\n ByVal e As System.EventArgs _\n ) Handles Button1.Click\n\n ' Toggle CapsLock\n\n ' Simulate the Key Press\n keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)\n\n ' Simulate the Key Release\n keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)\n End Sub\n\nEnd Class \n</code></pre>\n"
},
{
"answer_id": 58942,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 3,
"selected": false,
"text": "<p>Try <a href=\"http://social.msdn.microsoft.com/forums/en-US/vbgeneral/thread/718c0860-ab1a-4a0a-98af-a101cdfecf4e/\" rel=\"noreferrer\">this</a>:</p>\n\n<pre><code>Public Class Form1\n Private Declare Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)\n Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load\n Call keybd_event(System.Windows.Forms.Keys.CapsLock, &H14, 1, 0)\n Call keybd_event(System.Windows.Forms.Keys.CapsLock, &H14, 3, 0)\n End Sub\nEnd Class\n</code></pre>\n"
},
{
"answer_id": 33616002,
"author": "Ben",
"author_id": 5543707,
"author_profile": "https://Stackoverflow.com/users/5543707",
"pm_score": 0,
"selected": false,
"text": "<p>I use this</p>\n\n<pre><code>Private Declare Sub keybd_event Lib \"user32\" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Integer, ByVal dwExtraInfo As Integer)\nPrivate Const KEYEVENTF_EXTENDEDKEY As Integer = &H1\nPrivate Const KEYEVENTF_KEYUP As Integer = &H2\n'put this where you want to turn caps lock on or off\nkeybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)\nkeybd_event(VK_NUMLOCK, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
]
| Using VB.NET, how do I toggle the state of Caps Lock? | From: <http://www.vbforums.com/showthread.php?referrerid=61394&t=537891>
```
Imports System.Runtime.InteropServices
Public Class Form2
Private Declare Sub keybd_event Lib "user32" ( _
ByVal bVk As Byte, _
ByVal bScan As Byte, _
ByVal dwFlags As Integer, _
ByVal dwExtraInfo As Integer _
)
Private Const VK_CAPITAL As Integer = &H14
Private Const KEYEVENTF_EXTENDEDKEY As Integer = &H1
Private Const KEYEVENTF_KEYUP As Integer = &H2
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
' Toggle CapsLock
' Simulate the Key Press
keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or 0, 0)
' Simulate the Key Release
keybd_event(VK_CAPITAL, &H45, KEYEVENTF_EXTENDEDKEY Or KEYEVENTF_KEYUP, 0)
End Sub
End Class
``` |
58,939 | <p>I'm trying to get an event to fire whenever a choice is made from a <code>JComboBox</code>.</p>
<p>The problem I'm having is that there is no obvious <code>addSelectionListener()</code> method.</p>
<p>I've tried to use <code>actionPerformed()</code>, but it never fires.</p>
<p>Short of overriding the model for the <code>JComboBox</code>, I'm out of ideas.</p>
<p>How do I get notified of a selection change on a <code>JComboBox</code>?**</p>
<p><strong>Edit:</strong> I have to apologize. It turns out I was using a misbehaving subclass of <code>JComboBox</code>, but I'll leave the question up since your answer is good.</p>
| [
{
"answer_id": 58963,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 9,
"selected": true,
"text": "<p>It should respond to <a href=\"http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html\" rel=\"noreferrer\">ActionListeners</a>, like this:</p>\n\n<pre><code>combo.addActionListener (new ActionListener () {\n public void actionPerformed(ActionEvent e) {\n doSomething();\n }\n});\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/a/58965/1429387\">@John Calsbeek</a> rightly points out that <code>addItemListener()</code> will work, too. You may get 2 <code>ItemEvents</code>, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!</p>\n"
},
{
"answer_id": 58965,
"author": "John Calsbeek",
"author_id": 5696,
"author_profile": "https://Stackoverflow.com/users/5696",
"pm_score": 5,
"selected": false,
"text": "<p>I would try the <code>itemStateChanged()</code> method of the <a href=\"http://java.sun.com/javase/6/docs/api/java/awt/event/ItemListener.html\" rel=\"noreferrer\"><code>ItemListener</code></a> interface if jodonnell's solution fails.</p>\n"
},
{
"answer_id": 2187058,
"author": "JavaKeith",
"author_id": 264662,
"author_profile": "https://Stackoverflow.com/users/264662",
"pm_score": 3,
"selected": false,
"text": "<p>You may try these</p>\n\n<pre><code> int selectedIndex = myComboBox.getSelectedIndex();\n</code></pre>\n\n<p>-or-</p>\n\n<pre><code>Object selectedObject = myComboBox.getSelectedItem();\n</code></pre>\n\n<p>-or-</p>\n\n<pre><code>String selectedValue = myComboBox.getSelectedValue().toString();\n</code></pre>\n"
},
{
"answer_id": 14424530,
"author": "Viacheslav",
"author_id": 1043067,
"author_profile": "https://Stackoverflow.com/users/1043067",
"pm_score": 7,
"selected": false,
"text": "<p>Code example of <code>ItemListener</code> implementation</p>\n\n<pre><code>class ItemChangeListener implements ItemListener{\n @Override\n public void itemStateChanged(ItemEvent event) {\n if (event.getStateChange() == ItemEvent.SELECTED) {\n Object item = event.getItem();\n // do something with object\n }\n } \n}\n</code></pre>\n\n<p>Now we will get only selected item.</p>\n\n<p>Then just add listener to your JComboBox</p>\n\n<pre><code>addItemListener(new ItemChangeListener());\n</code></pre>\n"
},
{
"answer_id": 14667156,
"author": "Craig Wayne",
"author_id": 1654250,
"author_profile": "https://Stackoverflow.com/users/1654250",
"pm_score": 2,
"selected": false,
"text": "<p>I was recently looking for this very same solution and managed to find a simple one without assigning specific variables for the last selected item and the new selected item. And this question, although very helpful, didn't provide the solution I needed. This solved my problem, I hope it solves yours and others. Thanks.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/14647439/how-to-get-previous-last-item-jcombobox\">How do I get the previous or last item?</a></p>\n"
},
{
"answer_id": 17846338,
"author": "Ahuramazda",
"author_id": 2581460,
"author_profile": "https://Stackoverflow.com/users/2581460",
"pm_score": 4,
"selected": false,
"text": "<p>Here is creating a ComboBox adding a listener for item selection change:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>JComboBox comboBox = new JComboBox();\n\ncomboBox.setBounds(84, 45, 150, 20);\ncontentPane.add(comboBox);\n\nJComboBox comboBox_1 = new JComboBox();\ncomboBox_1.setBounds(84, 97, 150, 20);\ncontentPane.add(comboBox_1);\ncomboBox.addItemListener(new ItemListener() {\n public void itemStateChanged(ItemEvent arg0) {\n //Do Something\n }\n});\n</code></pre>\n"
},
{
"answer_id": 64692212,
"author": "Mehmet Onar",
"author_id": 6573672,
"author_profile": "https://Stackoverflow.com/users/6573672",
"pm_score": 2,
"selected": false,
"text": "<p>you can do this with jdk >= 8</p>\n<pre><code>getComboBox().addItemListener(this::comboBoxitemStateChanged);\n</code></pre>\n<p>so</p>\n<pre><code>public void comboBoxitemStateChanged(ItemEvent e) {\n if (e.getStateChange() == ItemEvent.SELECTED) {\n YourObject selectedItem = (YourObject) e.getItem();\n //TODO your actitons\n }\n}\n</code></pre>\n"
},
{
"answer_id": 68821546,
"author": "EverCpp",
"author_id": 12048805,
"author_profile": "https://Stackoverflow.com/users/12048805",
"pm_score": 2,
"selected": false,
"text": "<p>I use this:</p>\n<pre><code> cb = new JComboBox<String>();\n cb.setBounds(10, 33, 46, 22);\n panelConfig.add(cb);\n for(int i = 0; i < 10; ++i)\n {\n cb.addItem(Integer.toString(i));\n }\n cb.addItemListener(new ItemListener()\n {\n @Override\n public void itemStateChanged(ItemEvent e)\n {\n if(e.getID() == temEvent.ITEM_STATE_CHANGED)\n {\n if(e.getStateChange() == ItemEvent.SELECTED)\n {\n JComboBox<String> cb = (JComboBox<String>) e.getSource();\n String newSelection = (String) cb.getSelectedItem();\n System.out.println("newSelection: " + newSelection);\n }\n }\n }\n });\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
]
| I'm trying to get an event to fire whenever a choice is made from a `JComboBox`.
The problem I'm having is that there is no obvious `addSelectionListener()` method.
I've tried to use `actionPerformed()`, but it never fires.
Short of overriding the model for the `JComboBox`, I'm out of ideas.
How do I get notified of a selection change on a `JComboBox`?\*\*
**Edit:** I have to apologize. It turns out I was using a misbehaving subclass of `JComboBox`, but I'll leave the question up since your answer is good. | It should respond to [ActionListeners](http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html), like this:
```
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
doSomething();
}
});
```
[@John Calsbeek](https://stackoverflow.com/a/58965/1429387) rightly points out that `addItemListener()` will work, too. You may get 2 `ItemEvents`, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types! |
58,940 | <p>I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?</p>
<pre><code>CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
</code></pre>
<p>I need to be able to iterate through both result sets individually.</p>
<p>EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.</p>
<p>The result sets returned by the procedures are not the same data types or number of columns.</p>
| [
{
"answer_id": 58960,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 0,
"selected": false,
"text": "<p>You could select them into temp tables or write table valued functions to return result sets. Are asking how to iterate through the result sets?</p>\n"
},
{
"answer_id": 58973,
"author": "Josef",
"author_id": 5581,
"author_profile": "https://Stackoverflow.com/users/5581",
"pm_score": 1,
"selected": false,
"text": "<p>There are two ways to do this easily. Either stick the results in a temp table and then reference the temp table from your sproc. The other alternative is to put the results into an XML variable that is used as an OUTPUT variable.</p>\n\n<p>There are, however, pros and cons to both of these options. With a temporary table, you'll need to add code to the script that creates the calling procedure to create the temporary table before modifying the procedure. Also, you should clean up the temp table at the end of the procedure.</p>\n\n<p>With the XML, it can be memory intensive and slow.</p>\n"
},
{
"answer_id": 59015,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 6,
"selected": true,
"text": "<p>The short answer is: you can't do it.</p>\n\n<p>From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.</p>\n\n<p>To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:</p>\n\n<pre><code>INSERT INTO #Table (...columns...)\nEXEC MySproc ...parameters...\n</code></pre>\n\n<p>You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded.</p>\n"
},
{
"answer_id": 67369,
"author": "Chris Wuestefeld",
"author_id": 10082,
"author_profile": "https://Stackoverflow.com/users/10082",
"pm_score": 2,
"selected": false,
"text": "<p>Note that there's an extra, undocumented limitation to the INSERT INTO ... EXEC statement: it cannot be nested. That is, the stored proc that the EXEC calls (or any that it calls in turn) cannot itself do an INSERT INTO ... EXEC. It appears that there's a single scratchpad per process that accumulates the result, and if they're nested you'll get an error when the caller opens this up, and then the callee tries to open it again.</p>\n\n<p>Matthieu, you'd need to maintain separate temp tables for each \"type\" of result. Also, if you're executing the same one multiple times, you might need to add an extra column to that result to indicate which call it resulted from.</p>\n"
},
{
"answer_id": 269976,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Sadly it is impossible to do this. The problem is, of course, that there is no SQL Syntax to allow it. It happens 'beneath the hood' of course, but you can't get at these other results in TSQL, only from the application via ODBC or whatever. </p>\n\n<p>There is a way round it, as with most things. The trick is to use ole automation in TSQL to create an ADODB object which opens each resultset in turn and write the results to the tables you nominate (or do whatever you want with the resultsets). you can also do it in DMO if you enjoy pain. </p>\n"
},
{
"answer_id": 879516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I was easily able to do this by creating a SQL2005 CLR stored procedure which contained an internal dataset.</p>\n\n<p>You see, a new SqlDataAdapter will .Fill a multiple-result-set sproc into a multiple-table dataset by default. The data in these tables can in turn be inserted into #Temp tables in the calling sproc you wish to write. <strong>dataset.ReadXmlSchema</strong> will show you the schema of each result set.</p>\n\n<p><strong>Step 1: Begin writing the sproc which will read the data from the multi-result-set sproc</strong></p>\n\n<p>a. Create a separate table for each result set according to the schema.</p>\n\n<pre><code>CREATE PROCEDURE [dbo].[usp_SF_Read] AS\nSET NOCOUNT ON;\nCREATE TABLE #Table01 (Document_ID VARCHAR(100)\n , Document_status_definition_uid INT\n , Document_status_Code VARCHAR(100) \n , Attachment_count INT\n , PRIMARY KEY (Document_ID));\n</code></pre>\n\n<p>b. At this point you may need to declare a cursor to repetitively call the CLR sproc you will create here:</p>\n\n<p><strong>Step 2: Make the CLR Sproc</strong></p>\n\n<pre><code>Partial Public Class StoredProcedures\n <Microsoft.SqlServer.Server.SqlProcedure()> _\n Public Shared Sub usp_SF_ReadSFIntoTables()\n\n End Sub\nEnd Class\n</code></pre>\n\n<p>a. Connect using <code>New SqlConnection(\"context connection=true\")</code>.</p>\n\n<p>b. Set up a command object (cmd) to contain the multiple-result-set sproc. </p>\n\n<p>c. Get all the data using the following:</p>\n\n<pre><code> Dim dataset As DataSet = New DataSet\n With New SqlDataAdapter(cmd)\n .Fill(dataset) ' get all the data.\n End With\n'you can use dataset.ReadXmlSchema at this point...\n</code></pre>\n\n<p>d. Iterate over each table and insert every row into the appropriate temp table (which you created in step one above).</p>\n\n<p><strong>Final note:</strong>\nIn my experience, you may wish to enforce some relationships between your tables so you know which batch each record came from.</p>\n\n<p>That's all there was to it!</p>\n\n<p>~ Shaun, Near Seattle</p>\n"
},
{
"answer_id": 7168255,
"author": "Daniel Barbalace",
"author_id": 908590,
"author_profile": "https://Stackoverflow.com/users/908590",
"pm_score": 3,
"selected": false,
"text": "<p>There is a kludge that you can do as well. Add an optional parameter N int to your sproc. Default the value of N to -1. If the value of N is -1, then do every one of your selects. Otherwise, do the Nth select and only the Nth select.</p>\n\n<p>For example,</p>\n\n<pre><code>if (N = -1 or N = 0)\n select ...\n\nif (N = -1 or N = 1)\n select ...\n</code></pre>\n\n<p>The callers of your sproc who do not specify N will get a result set with more than one tables. If you need to extract one or more of these tables from another sproc, simply call your sproc specifying a value for N. You'll have to call the sproc one time for each table you wish to extract. Inefficient if you need more than one table from the result set, but it does work in pure TSQL.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1836/"
]
| I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?
```
CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_address, order_number from order_table where order_id = @orderId
select item, number_of_items, cost from order_line where order_id = @orderId
END
```
I need to be able to iterate through both result sets individually.
EDIT: Just to clarify the question, I want to test the stored procedures. I have a set of stored procedures which are used from a VB.NET client, which return multiple result sets. These are not going to be changed to a table valued function, I can't in fact change the procedures at all. Changing the procedure is not an option.
The result sets returned by the procedures are not the same data types or number of columns. | The short answer is: you can't do it.
From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.
To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with the following syntax:
```
INSERT INTO #Table (...columns...)
EXEC MySproc ...parameters...
```
You can use the same syntax for a procedure that returns multiple results, but it will only process the first result, the rest will be discarded. |
58,969 | <p>I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.</p>
<p><b>Edit:</b> I should have said. I have a user class and I want to pass a different instance of this class to each unit test. </p>
| [
{
"answer_id": 58982,
"author": "Peter Bernier",
"author_id": 6112,
"author_profile": "https://Stackoverflow.com/users/6112",
"pm_score": 1,
"selected": false,
"text": "<p>If you're looking to test the actual UI, you could try using something like Selenium (www.openqa.org). It lets you write the code in PHP (which I'm assuming would work with phpUnit) to drive the browser..</p>\n\n<p>Another approach would be to have a common method that could be called by each test for your different user type. ie, something like 'ValidatePage', which you could then call from TestAdminUser or TestRegularUser and have the method simply perform the same basic validation of what you're expecting..</p>\n"
},
{
"answer_id": 63442,
"author": "Andrew Culver",
"author_id": 7549,
"author_profile": "https://Stackoverflow.com/users/7549",
"pm_score": 3,
"selected": true,
"text": "<p>If your various user classes inherit from a parent user class, then I recommend you use the same inheritance structure for your test case classes.</p>\n\n<p>Consider the following sample classes:</p>\n\n<pre><code>class User\n{\n public function commonFunctionality()\n {\n return 'Something';\n }\n\n public function modifiedFunctionality()\n {\n return 'One Thing';\n }\n}\n\nclass SpecialUser extends User\n{\n public function specialFunctionality()\n {\n return 'Nothing';\n }\n\n public function modifiedFunctionality()\n {\n return 'Another Thing';\n }\n}\n</code></pre>\n\n<p>You could do the following with your test case classes:</p>\n\n<pre><code>class Test_User extends PHPUnit_Framework_TestCase\n{\n public function create()\n {\n return new User();\n }\n\n public function testCommonFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Something', $user->commonFunctionality);\n }\n\n public function testModifiedFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('One Thing', $user->commonFunctionality);\n }\n}\n\nclass Test_SpecialUser extends Test_User\n{\n public function create() {\n return new SpecialUser();\n }\n\n public function testSpecialFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Nothing', $user->commonFunctionality);\n }\n\n public function testModifiedFunctionality()\n {\n $user = $this->create();\n $this->assertEquals('Another Thing', $user->commonFunctionality);\n }\n}\n</code></pre>\n\n<p>Because each test depends on a create method which you can override, and because the test methods are inherited from the parent test class, all tests for the parent class will be run against the child class, unless you override them to change the expected behavior.</p>\n\n<p>This has worked great in my limited experience.</p>\n"
},
{
"answer_id": 82752,
"author": "Paweł Hajdan",
"author_id": 9403,
"author_profile": "https://Stackoverflow.com/users/9403",
"pm_score": 1,
"selected": false,
"text": "<p>Just make sure you're not running into an <strong>anti-pattern</strong> here. Maybe you do too much work in the constructor? Or maybe these should be in fact different classes? Tests often give you clues about <strong>design of code.</strong> Listen to them.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4437/"
]
| I'm starting to learn how to use PHPUnit to test the website I'm working on. The problem I'm running into is that I have five different user types defined and I need to be able to test every class with the different types. I currently have a user class and I would like to pass this to each function but I can't figure out how to pass this or test the different errors that could come back as being correct or not.
**Edit:** I should have said. I have a user class and I want to pass a different instance of this class to each unit test. | If your various user classes inherit from a parent user class, then I recommend you use the same inheritance structure for your test case classes.
Consider the following sample classes:
```
class User
{
public function commonFunctionality()
{
return 'Something';
}
public function modifiedFunctionality()
{
return 'One Thing';
}
}
class SpecialUser extends User
{
public function specialFunctionality()
{
return 'Nothing';
}
public function modifiedFunctionality()
{
return 'Another Thing';
}
}
```
You could do the following with your test case classes:
```
class Test_User extends PHPUnit_Framework_TestCase
{
public function create()
{
return new User();
}
public function testCommonFunctionality()
{
$user = $this->create();
$this->assertEquals('Something', $user->commonFunctionality);
}
public function testModifiedFunctionality()
{
$user = $this->create();
$this->assertEquals('One Thing', $user->commonFunctionality);
}
}
class Test_SpecialUser extends Test_User
{
public function create() {
return new SpecialUser();
}
public function testSpecialFunctionality()
{
$user = $this->create();
$this->assertEquals('Nothing', $user->commonFunctionality);
}
public function testModifiedFunctionality()
{
$user = $this->create();
$this->assertEquals('Another Thing', $user->commonFunctionality);
}
}
```
Because each test depends on a create method which you can override, and because the test methods are inherited from the parent test class, all tests for the parent class will be run against the child class, unless you override them to change the expected behavior.
This has worked great in my limited experience. |
58,976 | <p>How do I find out whether or not Caps Lock is activated, using VB.NET?</p>
<p>This is a follow-up to my <a href="https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet">earlier question</a>.</p>
| [
{
"answer_id": 58991,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not an expert in VB.NET so only PInvoke comes to my mind:</p>\n\n<pre><code>Declare Function GetKeyState Lib \"user32\" \n Alias \"GetKeyState\" (ByValnVirtKey As Int32) As Int16\n\nPrivate Const VK_CAPSLOCK = &H14\n\nIf GetKeyState(VK_CAPSLOCK) = 1 Then ...\n</code></pre>\n"
},
{
"answer_id": 58993,
"author": "rp.",
"author_id": 2536,
"author_profile": "https://Stackoverflow.com/users/2536",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked.aspx\" rel=\"noreferrer\">Control.IsKeyLocked(Keys) Method - MSDN</a></p>\n\n<pre><code>Imports System\nImports System.Windows.Forms\nImports Microsoft.VisualBasic\n\nPublic Class CapsLockIndicator\n\n Public Shared Sub Main()\n if Control.IsKeyLocked(Keys.CapsLock) Then\n MessageBox.Show(\"The Caps Lock key is ON.\")\n Else\n MessageBox.Show(\"The Caps Lock key is OFF.\")\n End If\n End Sub 'Main\nEnd Class 'CapsLockIndicator\n</code></pre>\n\n<hr>\n\n<p>C# version:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>using System;\nusing System.Windows.Forms;\n\npublic class CapsLockIndicator\n{\n public static void Main()\n {\n if (Control.IsKeyLocked(Keys.CapsLock)) {\n MessageBox.Show(\"The Caps Lock key is ON.\");\n }\n else {\n MessageBox.Show(\"The Caps Lock key is OFF.\");\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 29317731,
"author": "JumboUser155",
"author_id": 4401083,
"author_profile": "https://Stackoverflow.com/users/4401083",
"pm_score": 2,
"selected": false,
"text": "<p>Create a Timer that is set to 5 milliseconds and is enabled.<br>\nThen make a label named <code>label1</code>. After, try the following code (in the timer event handler).</p>\n\n<pre><code>Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick\n If My.Computer.Keyboard.CapsLock = True Then\n Label1.Text = \"Caps Lock Enabled\"\n Else\n Label1.Text = \"Caps Lock Disabled\"\n End If\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 43073619,
"author": "Thomas Bailey",
"author_id": 6416987,
"author_profile": "https://Stackoverflow.com/users/6416987",
"pm_score": 0,
"selected": false,
"text": "<p>The solution posted by <a href=\"https://stackoverflow.com/a/58993/7444103\">.rp</a> works, but conflicts with the <code>Me.KeyDown</code> event handler.<br>\nI have a sub that calls a sign in function when enter is pressed (shown below).<br>\nThe <code>My.Computer.Keyboard.CapsLock</code> state works and does not conflict with <code>Me.Keydown</code>.</p>\n\n<pre><code>Private Sub WindowLogin_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown\n\n If Keyboard.IsKeyDown(Key.Enter) Then\n Call SignIn()\n End If\n\nEnd Sub\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/58976",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133/"
]
| How do I find out whether or not Caps Lock is activated, using VB.NET?
This is a follow-up to my [earlier question](https://stackoverflow.com/questions/58937/how-do-i-toggle-caps-lock-in-vbnet). | [Control.IsKeyLocked(Keys) Method - MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.iskeylocked.aspx)
```
Imports System
Imports System.Windows.Forms
Imports Microsoft.VisualBasic
Public Class CapsLockIndicator
Public Shared Sub Main()
if Control.IsKeyLocked(Keys.CapsLock) Then
MessageBox.Show("The Caps Lock key is ON.")
Else
MessageBox.Show("The Caps Lock key is OFF.")
End If
End Sub 'Main
End Class 'CapsLockIndicator
```
---
C# version:
```cs
using System;
using System.Windows.Forms;
public class CapsLockIndicator
{
public static void Main()
{
if (Control.IsKeyLocked(Keys.CapsLock)) {
MessageBox.Show("The Caps Lock key is ON.");
}
else {
MessageBox.Show("The Caps Lock key is OFF.");
}
}
}
``` |
59,013 | <p>Context:
I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain.</p>
<p>So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the</p>
<p>Problem:
Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors. </p>
<blockquote>
<p>There are fewer columns in the INSERT
statement than values specified in the
VALUES clause. The number of values in
the VALUES clause must match the
number of columns specified in the
INSERT statement. at
System.Data.SqlClient.SqlConnection.OnError(SqlException
exception, Boolean breakConnection)</p>
</blockquote>
<p>Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said:</p>
<blockquote>
<p>Looks like you have a combination of
code running under Spanish locale, and
SQL server under English locale. So
the SQL expects '15.28' and not
'15,28'</p>
</blockquote>
<p>Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?).</p>
<p>So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is</p>
<p>What are the places where localization is defined on a machine/user/domain basis?</p>
<p>I don't know all the places I must search for the culprit, so please help me to find it!</p>
| [
{
"answer_id": 59070,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can set it in the thread context in which your code is executing.</p>\n\n<p>System.Threading.Thread.CurrentThread.CurrentCulture</p>\n"
},
{
"answer_id": 59071,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 3,
"selected": true,
"text": "<p>There are two types of localisation in .NET, both the settings for the cultures can be found in these variables (fire up a .NET command line app on the machine to see what it says):</p>\n\n<p>System.Thread.CurrentThread.CurrentCulture\n&\nSystem.Thread.CurrentThread.CurrentUICulture</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx</a></p>\n\n<p>They relate to the settings in the control panel (in the regional settings part).\nCreate a .NET command line app, then just call ToString() on the above properties, that should tell you which property to look at.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>It turns out the setting for the locales per user are held here:</p>\n\n<pre><code>HKEY_CURRENT_USER\\Control Panel\\International\n</code></pre>\n\n<p>It might be worth inspecting the registry of the user with the spanish locale, and comparing it to one who is set to US or whichever locale you require.</p>\n"
},
{
"answer_id": 59106,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>Great, I created the console app and indeed, the app is not crazy, CurrentCulture is in spanish, but for THAT User in THAT machine only. If I run the console app as another user it returns english for all cultures.</p>\n\n<p>Should I open a new question asking where are user-wise locale settings?</p>\n"
},
{
"answer_id": 59147,
"author": "Ant",
"author_id": 3709,
"author_profile": "https://Stackoverflow.com/users/3709",
"pm_score": 0,
"selected": false,
"text": "<p>Well if it's user specific, check out the <em>Regional and Language Options</em> control panel.</p>\n\n<p><rant>On a side note, kick the developer for not being culture aware when using strings.</rant></p>\n"
},
{
"answer_id": 59162,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>Found out why it happened in that machine only. It was the only one where I actually logged into with that user, then the domain controller set the regional settings as spanish for it.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5190/"
]
| Context:
I'm in charge of running a service written in .NET. Proprietary application. It uses a SQL Server database. It ran as a user member of the Administrators group in the local machine. It worked alright before I added the machine to a domain.
So, I added the machine to a domain (Win 2003) and changed the user to a member of the Power Users group and now, the
Problem:
Some of the SQL sentences it tries to execute are "magically" in spanish localization (where , separates floating point numbers instead of .), leading to errors.
>
> There are fewer columns in the INSERT
> statement than values specified in the
> VALUES clause. The number of values in
> the VALUES clause must match the
> number of columns specified in the
> INSERT statement. at
> System.Data.SqlClient.SqlConnection.OnError(SqlException
> exception, Boolean breakConnection)
>
>
>
Operating System and Regional Settings in the machine are in English. I asked the provider of the application and he said:
>
> Looks like you have a combination of
> code running under Spanish locale, and
> SQL server under English locale. So
> the SQL expects '15.28' and not
> '15,28'
>
>
>
Which looks wrong to me in various levels (how can SQL Server distinguish between commas to separate arguments and commas belonging to a floating point number?).
So, the code seems to be grabbing the spanish locale from somewhere, I don't know if it's the user it runs as, or someplace else (global policy, maybe?). But the question is
What are the places where localization is defined on a machine/user/domain basis?
I don't know all the places I must search for the culprit, so please help me to find it! | There are two types of localisation in .NET, both the settings for the cultures can be found in these variables (fire up a .NET command line app on the machine to see what it says):
System.Thread.CurrentThread.CurrentCulture
&
System.Thread.CurrentThread.CurrentUICulture
<http://msdn.microsoft.com/en-us/library/system.threading.thread_members.aspx>
They relate to the settings in the control panel (in the regional settings part).
Create a .NET command line app, then just call ToString() on the above properties, that should tell you which property to look at.
**Edit:**
It turns out the setting for the locales per user are held here:
```
HKEY_CURRENT_USER\Control Panel\International
```
It might be worth inspecting the registry of the user with the spanish locale, and comparing it to one who is set to US or whichever locale you require. |
59,044 | <p>Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003)</p>
| [
{
"answer_id": 59055,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 8,
"selected": true,
"text": "<p>The following query replace each and every <code>a</code> character with a <code>b</code> character.</p>\n\n<pre><code>UPDATE \n YourTable\nSET \n Column1 = REPLACE(Column1,'a','b')\nWHERE \n Column1 LIKE '%a%'\n</code></pre>\n\n<p>This will not work on SQL server 2003.</p>\n"
},
{
"answer_id": 59057,
"author": "Jiaaro",
"author_id": 2908,
"author_profile": "https://Stackoverflow.com/users/2908",
"pm_score": 4,
"selected": false,
"text": "<p>like so:</p>\n\n<pre><code>BEGIN TRANSACTION; \nUPDATE table_name\n SET column_name=REPLACE(column_name,'text_to_find','replace_with_this'); \nCOMMIT TRANSACTION;\n</code></pre>\n\n<p>Example: Replaces <script... with <a ... to eliminate javascript vulnerabilities</p>\n\n<pre><code>BEGIN TRANSACTION; UPDATE testdb\nSET title=REPLACE(title,'script','a'); COMMIT TRANSACTION;\n</code></pre>\n"
},
{
"answer_id": 59474,
"author": "Joe Kuemerle",
"author_id": 4273,
"author_profile": "https://Stackoverflow.com/users/4273",
"pm_score": 0,
"selected": false,
"text": "<p>If you are working with SQL Server 2005 or later there is also a CLR library available at <a href=\"http://www.sqlsharp.com/\" rel=\"nofollow noreferrer\">http://www.sqlsharp.com/</a> that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.</p>\n"
},
{
"answer_id": 9707239,
"author": "Brian Moeskau",
"author_id": 108348,
"author_profile": "https://Stackoverflow.com/users/108348",
"pm_score": 3,
"selected": false,
"text": "<p>This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the <code>ntext</code> data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:</p>\n\n<blockquote>\n <p>Argument data type ntext is invalid for argument 1 of replace\n function.</p>\n</blockquote>\n\n<p>The simplest fix, if your column data fits within <code>nvarchar</code>, is to cast the column during replace. Borrowing the code from the <a href=\"https://stackoverflow.com/a/59055/108348\">accepted answer</a>:</p>\n\n<pre><code>UPDATE YourTable\nSET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')\nWHERE Column1 LIKE '%a%'\n</code></pre>\n\n<p>This worked perfectly for me. Thanks to <a href=\"http://www.sqlservercentral.com/Forums/FindPost316385.aspx\" rel=\"nofollow noreferrer\">this forum post</a> I found for the fix. Hopefully this helps someone else!</p>\n"
},
{
"answer_id": 31589027,
"author": "abc123",
"author_id": 1985032,
"author_profile": "https://Stackoverflow.com/users/1985032",
"pm_score": 2,
"selected": false,
"text": "<h2>The following will find and replace a string in every database (excluding system databases) on every table on the instance you are connected to:</h2>\n\n<p>Simply change <code>'Search String'</code> to whatever you seek and <code>'Replace String'</code> with whatever you want to replace it with.</p>\n\n<pre><code>--Getting all the databases and making a cursor\nDECLARE db_cursor CURSOR FOR \nSELECT name \nFROM master.dbo.sysdatabases \nWHERE name NOT IN ('master','model','msdb','tempdb') -- exclude these databases\n\nDECLARE @databaseName nvarchar(1000)\n--opening the cursor to move over the databases in this instance\nOPEN db_cursor\nFETCH NEXT FROM db_cursor INTO @databaseName \n\nWHILE @@FETCH_STATUS = 0 \nBEGIN\n PRINT @databaseName\n --Setting up temp table for the results of our search\n DECLARE @Results TABLE(TableName nvarchar(370), RealColumnName nvarchar(370), ColumnName nvarchar(370), ColumnValue nvarchar(3630))\n\n SET NOCOUNT ON\n\n DECLARE @SearchStr nvarchar(100), @ReplaceStr nvarchar(100), @SearchStr2 nvarchar(110)\n SET @SearchStr = 'Search String'\n SET @ReplaceStr = 'Replace String'\n SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')\n\n DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128)\n SET @TableName = ''\n\n --Looping over all the tables in the database\n WHILE @TableName IS NOT NULL\n BEGIN\n DECLARE @SQL nvarchar(2000)\n SET @ColumnName = ''\n DECLARE @result NVARCHAR(256)\n SET @SQL = 'USE ' + @databaseName + '\n SELECT @result = MIN(QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME))\n FROM [' + @databaseName + '].INFORMATION_SCHEMA.TABLES\n WHERE TABLE_TYPE = ''BASE TABLE'' AND TABLE_CATALOG = ''' + @databaseName + '''\n AND QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME) > ''' + @TableName + '''\n AND OBJECTPROPERTY(\n OBJECT_ID(\n QUOTENAME(TABLE_SCHEMA) + ''.'' + QUOTENAME(TABLE_NAME)\n ), ''IsMSShipped''\n ) = 0'\n EXEC master..sp_executesql @SQL, N'@result nvarchar(256) out', @result out\n\n SET @TableName = @result\n PRINT @TableName\n\n WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)\n BEGIN\n DECLARE @ColumnResult NVARCHAR(256)\n SET @SQL = '\n SELECT @ColumnResult = MIN(QUOTENAME(COLUMN_NAME))\n FROM [' + @databaseName + '].INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_SCHEMA = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 2)\n AND TABLE_NAME = PARSENAME(''[' + @databaseName + '].' + @TableName + ''', 1)\n AND DATA_TYPE IN (''char'', ''varchar'', ''nchar'', ''nvarchar'')\n AND TABLE_CATALOG = ''' + @databaseName + '''\n AND QUOTENAME(COLUMN_NAME) > ''' + @ColumnName + ''''\n PRINT @SQL\n EXEC master..sp_executesql @SQL, N'@ColumnResult nvarchar(256) out', @ColumnResult out\n SET @ColumnName = @ColumnResult \n\n PRINT @ColumnName\n\n IF @ColumnName IS NOT NULL\n BEGIN\n INSERT INTO @Results\n EXEC\n (\n 'USE ' + @databaseName + '\n SELECT ''' + @TableName + ''',''' + @ColumnName + ''',''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) \n FROM ' + @TableName + ' (NOLOCK) ' +\n ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2\n )\n END\n END\n END\n\n --Declaring another temporary table\n DECLARE @time_to_update TABLE(TableName nvarchar(370), RealColumnName nvarchar(370))\n\n INSERT INTO @time_to_update\n SELECT TableName, RealColumnName FROM @Results GROUP BY TableName, RealColumnName\n\n DECLARE @MyCursor CURSOR;\n BEGIN\n DECLARE @t nvarchar(370)\n DECLARE @c nvarchar(370)\n --Looping over the search results \n SET @MyCursor = CURSOR FOR\n SELECT TableName, RealColumnName FROM @time_to_update GROUP BY TableName, RealColumnName\n\n --Getting my variables from the first item\n OPEN @MyCursor \n FETCH NEXT FROM @MyCursor \n INTO @t, @c\n\n WHILE @@FETCH_STATUS = 0\n BEGIN\n -- Updating the old values with the new value\n DECLARE @sqlCommand varchar(1000)\n SET @sqlCommand = '\n USE ' + @databaseName + '\n UPDATE [' + @databaseName + '].' + @t + ' SET ' + @c + ' = REPLACE(' + @c + ', ''' + @SearchStr + ''', ''' + @ReplaceStr + ''') \n WHERE ' + @c + ' LIKE ''' + @SearchStr2 + ''''\n PRINT @sqlCommand\n BEGIN TRY\n EXEC (@sqlCommand)\n END TRY\n BEGIN CATCH\n PRINT ERROR_MESSAGE()\n END CATCH\n\n --Getting next row values\n FETCH NEXT FROM @MyCursor \n INTO @t, @c \n END;\n\n CLOSE @MyCursor ;\n DEALLOCATE @MyCursor;\n END;\n\n DELETE FROM @time_to_update\n DELETE FROM @Results\n\n FETCH NEXT FROM db_cursor INTO @databaseName\nEND \n\nCLOSE db_cursor \nDEALLOCATE db_cursor\n</code></pre>\n\n<p><strong><em>Note: this isn't ideal, nor is it optimized</em></strong></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908/"
]
| Question is pretty self explanitory. I want to do a simple find and replace, like you would in a text editor on the data in a column of my database (which is MsSQL on MS Windows server 2003) | The following query replace each and every `a` character with a `b` character.
```
UPDATE
YourTable
SET
Column1 = REPLACE(Column1,'a','b')
WHERE
Column1 LIKE '%a%'
```
This will not work on SQL server 2003. |
59,075 | <p>How do I save each sheet in an Excel workbook to separate <code>CSV</code> files with a macro?</p>
<p>I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate <code>CSV (comma separated file)</code>. Excel will not allow you to save all sheets to different <code>CSV</code> files.</p>
| [
{
"answer_id": 59078,
"author": "Alex Duggleby",
"author_id": 5790,
"author_profile": "https://Stackoverflow.com/users/5790",
"pm_score": 4,
"selected": false,
"text": "<p>And here's my solution should work with Excel > 2000, but tested only on 2007:</p>\n\n<pre><code>Private Sub SaveAllSheetsAsCSV()\nOn Error GoTo Heaven\n\n' each sheet reference\nDim Sheet As Worksheet\n' path to output to\nDim OutputPath As String\n' name of each csv\nDim OutputFile As String\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.EnableEvents = False\n\n' ask the user where to save\nOutputPath = InputBox(\"Enter a directory to save to\", \"Save to directory\", Path)\n\nIf OutputPath <> \"\" Then\n\n ' save for each sheet\n For Each Sheet In Sheets\n\n OutputFile = OutputPath & \"\\\" & Sheet.Name & \".csv\"\n\n ' make a copy to create a new book with this sheet\n ' otherwise you will always only get the first sheet\n Sheet.Copy\n ' this copy will now become active\n ActiveWorkbook.SaveAs FileName:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False\n ActiveWorkbook.Close\n Next\n\nEnd If\n\nFinally:\nApplication.ScreenUpdating = True\nApplication.DisplayAlerts = True\nApplication.EnableEvents = True\n\nExit Sub\n\nHeaven:\nMsgBox \"Couldn't save all sheets to CSV.\" & vbCrLf & _\n \"Source: \" & Err.Source & \" \" & vbCrLf & _\n \"Number: \" & Err.Number & \" \" & vbCrLf & _\n \"Description: \" & Err.Description & \" \" & vbCrLf\n\nGoTo Finally\nEnd Sub\n</code></pre>\n\n<p><em>(OT: I wonder if SO will replace some of my minor blogging)</em></p>\n"
},
{
"answer_id": 59114,
"author": "HigherAbstraction",
"author_id": 5945,
"author_profile": "https://Stackoverflow.com/users/5945",
"pm_score": 7,
"selected": true,
"text": "<p>Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes):</p>\n\n<pre><code>' ---------------------- Directory Choosing Helper Functions -----------------------\n' Excel and VBA do not provide any convenient directory chooser or file chooser\n' dialogs, but these functions will provide a reference to a system DLL\n' with the necessary capabilities\nPrivate Type BROWSEINFO ' used by the function GetFolderName\n hOwner As Long\n pidlRoot As Long\n pszDisplayName As String\n lpszTitle As String\n ulFlags As Long\n lpfn As Long\n lParam As Long\n iImage As Long\nEnd Type\n\nPrivate Declare Function SHGetPathFromIDList Lib \"shell32.dll\" _\n Alias \"SHGetPathFromIDListA\" (ByVal pidl As Long, ByVal pszPath As String) As Long\nPrivate Declare Function SHBrowseForFolder Lib \"shell32.dll\" _\n Alias \"SHBrowseForFolderA\" (lpBrowseInfo As BROWSEINFO) As Long\n\nFunction GetFolderName(Msg As String) As String\n ' returns the name of the folder selected by the user\n Dim bInfo As BROWSEINFO, path As String, r As Long\n Dim X As Long, pos As Integer\n bInfo.pidlRoot = 0& ' Root folder = Desktop\n If IsMissing(Msg) Then\n bInfo.lpszTitle = \"Select a folder.\"\n ' the dialog title\n Else\n bInfo.lpszTitle = Msg ' the dialog title\n End If\n bInfo.ulFlags = &H1 ' Type of directory to return\n X = SHBrowseForFolder(bInfo) ' display the dialog\n ' Parse the result\n path = Space$(512)\n r = SHGetPathFromIDList(ByVal X, ByVal path)\n If r Then\n pos = InStr(path, Chr$(0))\n GetFolderName = Left(path, pos - 1)\n Else\n GetFolderName = \"\"\n End If\nEnd Function\n'---------------------- END Directory Chooser Helper Functions ----------------------\n\nPublic Sub DoTheExport()\n Dim FName As Variant\n Dim Sep As String\n Dim wsSheet As Worksheet\n Dim nFileNum As Integer\n Dim csvPath As String\n\n\n Sep = InputBox(\"Enter a single delimiter character (e.g., comma or semi-colon)\", _\n \"Export To Text File\")\n 'csvPath = InputBox(\"Enter the full path to export CSV files to: \")\n\n csvPath = GetFolderName(\"Choose the folder to export CSV files to:\")\n If csvPath = \"\" Then\n MsgBox (\"You didn't choose an export directory. Nothing will be exported.\")\n Exit Sub\n End If\n\n For Each wsSheet In Worksheets\n wsSheet.Activate\n nFileNum = FreeFile\n Open csvPath & \"\\\" & _\n wsSheet.Name & \".csv\" For Output As #nFileNum\n ExportToTextFile CStr(nFileNum), Sep, False\n Close nFileNum\n Next wsSheet\n\nEnd Sub\n\n\n\nPublic Sub ExportToTextFile(nFileNum As Integer, _\n Sep As String, SelectionOnly As Boolean)\n\n Dim WholeLine As String\n Dim RowNdx As Long\n Dim ColNdx As Integer\n Dim StartRow As Long\n Dim EndRow As Long\n Dim StartCol As Integer\n Dim EndCol As Integer\n Dim CellValue As String\n\n Application.ScreenUpdating = False\n On Error GoTo EndMacro:\n\n If SelectionOnly = True Then\n With Selection\n StartRow = .Cells(1).Row\n StartCol = .Cells(1).Column\n EndRow = .Cells(.Cells.Count).Row\n EndCol = .Cells(.Cells.Count).Column\n End With\n Else\n With ActiveSheet.UsedRange\n StartRow = .Cells(1).Row\n StartCol = .Cells(1).Column\n EndRow = .Cells(.Cells.Count).Row\n EndCol = .Cells(.Cells.Count).Column\n End With\n End If\n\n For RowNdx = StartRow To EndRow\n WholeLine = \"\"\n For ColNdx = StartCol To EndCol\n If Cells(RowNdx, ColNdx).Value = \"\" Then\n CellValue = \"\"\n Else\n CellValue = Cells(RowNdx, ColNdx).Value\n End If\n WholeLine = WholeLine & CellValue & Sep\n Next ColNdx\n WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))\n Print #nFileNum, WholeLine\n Next RowNdx\n\nEndMacro:\n On Error GoTo 0\n Application.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 59906,
"author": "Graham",
"author_id": 1826,
"author_profile": "https://Stackoverflow.com/users/1826",
"pm_score": 7,
"selected": false,
"text": "<p>@AlexDuggleby: you don't need to copy the worksheets, you can save them directly. e.g.:</p>\n\n<pre><code>Public Sub SaveWorksheetsAsCsv()\nDim WS As Excel.Worksheet\nDim SaveToDirectory As String\n\n SaveToDirectory = \"C:\\\"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name, xlCSV\n Next\n\nEnd Sub\n</code></pre>\n\n<p>Only potential problem is that that leaves your workbook saved as the last csv file. If you need to keep the original workbook you will need to SaveAs it.</p>\n"
},
{
"answer_id": 62301,
"author": "Robert Mearns",
"author_id": 5050,
"author_profile": "https://Stackoverflow.com/users/5050",
"pm_score": 4,
"selected": false,
"text": "<p>Building on Graham's answer, the extra code saves the workbook back into it's original location in it's original format.</p>\n\n<pre><code>Public Sub SaveWorksheetsAsCsv()\n\nDim WS As Excel.Worksheet\nDim SaveToDirectory As String\n\nDim CurrentWorkbook As String\nDim CurrentFormat As Long\n\n CurrentWorkbook = ThisWorkbook.FullName\n CurrentFormat = ThisWorkbook.FileFormat\n' Store current details for the workbook\n\n SaveToDirectory = \"C:\\\"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name, xlCSV\n Next\n\n Application.DisplayAlerts = False\n ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat\n Application.DisplayAlerts = True\n' Temporarily turn alerts off to prevent the user being prompted\n' about overwriting the original file.\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 845345,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A small modification <a href=\"https://stackoverflow.com/questions/59075/macro-to-save-each-sheet-in-an-excel-workbook-to-separate-csv-files/59078#59078\" title=\"oh, right here then\">to answer from Alex</a> is turning on and off of auto calculation. </p>\n\n<p>Surprisingly the unmodified code was working fine with VLOOKUP but failed with OFFSET. Also turning auto calculation off speeds up the save drastically.</p>\n\n<pre><code>Public Sub SaveAllSheetsAsCSV()\nOn Error GoTo Heaven\n\n' each sheet reference\nDim Sheet As Worksheet\n' path to output to\nDim OutputPath As String\n' name of each csv\nDim OutputFile As String\n\nApplication.ScreenUpdating = False\nApplication.DisplayAlerts = False\nApplication.EnableEvents = False\n\n' Save the file in current director\nOutputPath = ThisWorkbook.Path\n\n\nIf OutputPath <> \"\" Then\nApplication.Calculation = xlCalculationManual\n\n' save for each sheet\nFor Each Sheet In Sheets\n\n OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & \".csv\"\n\n ' make a copy to create a new book with this sheet\n ' otherwise you will always only get the first sheet\n\n Sheet.Copy\n ' this copy will now become active\n ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV, CreateBackup:=False\n ActiveWorkbook.Close\nNext\n\nApplication.Calculation = xlCalculationAutomatic\n\nEnd If\n\nFinally:\nApplication.ScreenUpdating = True\nApplication.DisplayAlerts = True\nApplication.EnableEvents = True\n\nExit Sub\n\nHeaven:\nMsgBox \"Couldn't save all sheets to CSV.\" & vbCrLf & _\n \"Source: \" & Err.Source & \" \" & vbCrLf & _\n \"Number: \" & Err.Number & \" \" & vbCrLf & _\n \"Description: \" & Err.Description & \" \" & vbCrLf\n\nGoTo Finally\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 27858854,
"author": "Luigi",
"author_id": 2766120,
"author_profile": "https://Stackoverflow.com/users/2766120",
"pm_score": 1,
"selected": false,
"text": "<p>Please look into <a href=\"http://www.mrexcel.com/forum/excel-questions/265154-saving-multiple-sheets-separate-csv-files-visual-basic-applications.html\" rel=\"nofollow\">Von Pookie's answer</a>, all credits to him/her. </p>\n\n<pre><code> Sub asdf()\nDim ws As Worksheet, newWb As Workbook\n\nApplication.ScreenUpdating = False\nFor Each ws In Sheets(Array(\"EID Upload\", \"Wages with Locals Upload\", \"Wages without Local Upload\"))\n ws.Copy\n Set newWb = ActiveWorkbook\n With newWb\n .SaveAs ws.Name, xlCSV\n .Close (False)\n End With\nNext ws\nApplication.ScreenUpdating = True\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 61893912,
"author": "Żabojad",
"author_id": 1255091,
"author_profile": "https://Stackoverflow.com/users/1255091",
"pm_score": 2,
"selected": false,
"text": "<p>For Mac users like me, there are several gotchas:</p>\n\n<p>You cannot save to any directory you want. Only few of them can receive your saved files. More info <a href=\"https://www.rondebruin.nl/mac/mac034.htm\" rel=\"nofollow noreferrer\">there</a></p>\n\n<p>Here is a working script that you can copy paste in your excel for Mac:</p>\n\n<pre><code>Public Sub SaveWorksheetsAsCsv()\n\n Dim WS As Excel.Worksheet\n Dim SaveToDirectory As String\n\n SaveToDirectory = \"~/Library/Containers/com.microsoft.Excel/Data/\"\n\n For Each WS In ThisWorkbook.Worksheet\n WS.SaveAs SaveToDirectory & WS.Name & \".csv\", xlCSV\n Next\n\nEnd Sub\n\n</code></pre>\n"
},
{
"answer_id": 66285889,
"author": "Joshua Pinter",
"author_id": 293280,
"author_profile": "https://Stackoverflow.com/users/293280",
"pm_score": 2,
"selected": false,
"text": "<h2>Use Visual Basic to loop through worksheets and save <code>.csv</code> files.</h2>\n<ol>\n<li><p>Open up <code>.xlsx</code> file in Excel.</p>\n</li>\n<li><p>Press <kbd>option</kbd>+<kbd>F11</kbd></p>\n</li>\n<li><p><code>Insert</code> → <code>Module</code></p>\n</li>\n<li><p>Insert this into the module code:</p>\n<pre class=\"lang-vb prettyprint-override\"><code>Public Sub SaveWorksheetsAsCsv()\n\n Dim WS As Excel.Worksheet\n Dim SaveToDirectory As String\n\n SaveToDirectory = "./"\n\n For Each WS In ThisWorkbook.Worksheets\n WS.SaveAs SaveToDirectory & WS.Name & ".csv", xlCSV\n Next\n\nEnd Sub\n</code></pre>\n</li>\n<li><p>Run the module.</p>\n<p><em>(i.e. Click the play button at the top and then click "Run" on the dialog, if it pops up.)</em></p>\n</li>\n<li><p>Find your <code>.csv</code> files in <code>~/Library/Containers/com.microsoft.Excel/Data</code>.</p>\n<pre class=\"lang-sh prettyprint-override\"><code>open ~/Library/Containers/com.microsoft.Excel/Data\n</code></pre>\n</li>\n<li><p>Close <code>.xlsx</code> file.</p>\n</li>\n<li><p>Rinse and repeat for other <code>.xlsx</code> files.</p>\n</li>\n</ol>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59075",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5790/"
]
| How do I save each sheet in an Excel workbook to separate `CSV` files with a macro?
I have an excel with multiple sheets and I was looking for a macro that will save each sheet to a separate `CSV (comma separated file)`. Excel will not allow you to save all sheets to different `CSV` files. | Here is one that will give you a visual file chooser to pick the folder you want to save the files to and also lets you choose the CSV delimiter (I use pipes '|' because my fields contain commas and I don't want to deal with quotes):
```
' ---------------------- Directory Choosing Helper Functions -----------------------
' Excel and VBA do not provide any convenient directory chooser or file chooser
' dialogs, but these functions will provide a reference to a system DLL
' with the necessary capabilities
Private Type BROWSEINFO ' used by the function GetFolderName
hOwner As Long
pidlRoot As Long
pszDisplayName As String
lpszTitle As String
ulFlags As Long
lpfn As Long
lParam As Long
iImage As Long
End Type
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" _
Alias "SHGetPathFromIDListA" (ByVal pidl As Long, ByVal pszPath As String) As Long
Private Declare Function SHBrowseForFolder Lib "shell32.dll" _
Alias "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) As Long
Function GetFolderName(Msg As String) As String
' returns the name of the folder selected by the user
Dim bInfo As BROWSEINFO, path As String, r As Long
Dim X As Long, pos As Integer
bInfo.pidlRoot = 0& ' Root folder = Desktop
If IsMissing(Msg) Then
bInfo.lpszTitle = "Select a folder."
' the dialog title
Else
bInfo.lpszTitle = Msg ' the dialog title
End If
bInfo.ulFlags = &H1 ' Type of directory to return
X = SHBrowseForFolder(bInfo) ' display the dialog
' Parse the result
path = Space$(512)
r = SHGetPathFromIDList(ByVal X, ByVal path)
If r Then
pos = InStr(path, Chr$(0))
GetFolderName = Left(path, pos - 1)
Else
GetFolderName = ""
End If
End Function
'---------------------- END Directory Chooser Helper Functions ----------------------
Public Sub DoTheExport()
Dim FName As Variant
Dim Sep As String
Dim wsSheet As Worksheet
Dim nFileNum As Integer
Dim csvPath As String
Sep = InputBox("Enter a single delimiter character (e.g., comma or semi-colon)", _
"Export To Text File")
'csvPath = InputBox("Enter the full path to export CSV files to: ")
csvPath = GetFolderName("Choose the folder to export CSV files to:")
If csvPath = "" Then
MsgBox ("You didn't choose an export directory. Nothing will be exported.")
Exit Sub
End If
For Each wsSheet In Worksheets
wsSheet.Activate
nFileNum = FreeFile
Open csvPath & "\" & _
wsSheet.Name & ".csv" For Output As #nFileNum
ExportToTextFile CStr(nFileNum), Sep, False
Close nFileNum
Next wsSheet
End Sub
Public Sub ExportToTextFile(nFileNum As Integer, _
Sep As String, SelectionOnly As Boolean)
Dim WholeLine As String
Dim RowNdx As Long
Dim ColNdx As Integer
Dim StartRow As Long
Dim EndRow As Long
Dim StartCol As Integer
Dim EndCol As Integer
Dim CellValue As String
Application.ScreenUpdating = False
On Error GoTo EndMacro:
If SelectionOnly = True Then
With Selection
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
Else
With ActiveSheet.UsedRange
StartRow = .Cells(1).Row
StartCol = .Cells(1).Column
EndRow = .Cells(.Cells.Count).Row
EndCol = .Cells(.Cells.Count).Column
End With
End If
For RowNdx = StartRow To EndRow
WholeLine = ""
For ColNdx = StartCol To EndCol
If Cells(RowNdx, ColNdx).Value = "" Then
CellValue = ""
Else
CellValue = Cells(RowNdx, ColNdx).Value
End If
WholeLine = WholeLine & CellValue & Sep
Next ColNdx
WholeLine = Left(WholeLine, Len(WholeLine) - Len(Sep))
Print #nFileNum, WholeLine
Next RowNdx
EndMacro:
On Error GoTo 0
Application.ScreenUpdating = True
End Sub
``` |
59,099 | <p>Visually both of the following snippets produce the same UI. So why are there 2 controls..<br>
<strong>Snippet1</strong> </p>
<pre><code><TextBlock>Name:</TextBlock>
<TextBox Name="nameTextBox" />
</code></pre>
<p><strong>Snippet2</strong></p>
<pre><code><Label>Name:</Label>
<TextBox Name="nameTextBox" />
</code></pre>
<p>(<em>Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from <a href="https://rads.stackoverflow.com/amzn/click/com/0596510373" rel="noreferrer" rel="nofollow noreferrer">Programming WPF</a></em>) </p>
| [
{
"answer_id": 59104,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": false,
"text": "<p>Label has an important <strong>focus handling</strong> responsibility.Its purpose is to allow you to place a caption with an access key. It has a <strong>Target</strong> property, which indicates the target of the access key. Like this...</p>\n\n<pre><code><Label Target=\"{Binding ElementName=nameTextBox}\">_Name:</Label>\n<TextBox x:Name=\"nameTextBox\" />\n</code></pre>\n\n<p>In the absence of the Target property, the Label control does nothing useful. You'll just hear a beep if you press the access key indicating 'unable to process request'</p>\n"
},
{
"answer_id": 59629,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 8,
"selected": true,
"text": "<p>The WPF Textblock inherits from <strong>FrameworkElement</strong> instead of deriving from <strong>System.Windows.Control</strong> like the Label Control. This means that the Textblock is much more lightweight. The downside of using a textblock is no support for Access/Accerelator Keys and there is no link to other controls as target.</p>\n\n<p><strong><em>When you want to display text by itself use the TextBlock</em></strong>. The benefit is a light, performant way to display text.</p>\n\n<p><strong><em>When you want to associate text with another control like a TextBox use the Label control</em></strong>. The benefits are access keys and references to target control.</p>\n"
},
{
"answer_id": 1103456,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Label can be used as an alternative to TextBlock for situations where minimal text support is required such as the label for a control. Using Label can be advantageous because it requires even less resources (lighter weight) then a TextBlock. </p>\n"
},
{
"answer_id": 4058717,
"author": "Nam G VU",
"author_id": 248616,
"author_profile": "https://Stackoverflow.com/users/248616",
"pm_score": 2,
"selected": false,
"text": "<p>With <code>TextBlock</code> we can easily have multi-line support I guess - using <code>TextWrapping</code>. </p>\n\n<p>Using <code>Label</code> in such cases, e.g. displaying validation message, need to use <code><AccessKey></code> tags, which is less straight-forward than <code>TextBlock</code>.</p>\n\n<p>On the other hand, using <code>TextBlock</code> not allow us to set the <code>BorderBrush</code> property.</p>\n\n<p>So, to me, the two controls should be combined into a text-full-feature control.</p>\n"
},
{
"answer_id": 15239746,
"author": "Jon Crowell",
"author_id": 138938,
"author_profile": "https://Stackoverflow.com/users/138938",
"pm_score": 2,
"selected": false,
"text": "<p>The two biggest reasons for the confusion regarding TextBlocks and Labels are Windows Forms and common sense. </p>\n\n<ol>\n<li><p>When you wanted to slap a small bit of text on your form in Windows Forms, you used a Label, so it follows (incorrectly) that you would do the same thing with a WPF Label.</p></li>\n<li><p>Common sense would lead you to believe that a Label is lightweight and a TextBlock isn't, when the opposite is true.</p></li>\n</ol>\n\n<p>Note that you can put a TextBlock inside a Label.</p>\n"
},
{
"answer_id": 25827443,
"author": "iYadav",
"author_id": 1328637,
"author_profile": "https://Stackoverflow.com/users/1328637",
"pm_score": 2,
"selected": false,
"text": "<p>Label takes all kinds of data inputs like String, Number etc...\nTextBlock, as the name suggests, only accepts a Text string.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1695/"
]
| Visually both of the following snippets produce the same UI. So why are there 2 controls..
**Snippet1**
```
<TextBlock>Name:</TextBlock>
<TextBox Name="nameTextBox" />
```
**Snippet2**
```
<Label>Name:</Label>
<TextBox Name="nameTextBox" />
```
(*Well I am gonna answer this myself... thought this is a useful tidbit I learnt today from [Programming WPF](https://rads.stackoverflow.com/amzn/click/com/0596510373)*) | The WPF Textblock inherits from **FrameworkElement** instead of deriving from **System.Windows.Control** like the Label Control. This means that the Textblock is much more lightweight. The downside of using a textblock is no support for Access/Accerelator Keys and there is no link to other controls as target.
***When you want to display text by itself use the TextBlock***. The benefit is a light, performant way to display text.
***When you want to associate text with another control like a TextBox use the Label control***. The benefits are access keys and references to target control. |
59,102 | <p>Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?</p>
<p>Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)</p>
<p>Example 2 - combined parameter:
function convertTemperature("c-f", 22)</p>
<p>The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.</p>
<p>Thoughts?</p>
| [
{
"answer_id": 59108,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "<p>Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this:</p>\n\n<pre><code>convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)\n</code></pre>\n"
},
{
"answer_id": 59110,
"author": "Kilhoffer",
"author_id": 5469,
"author_profile": "https://Stackoverflow.com/users/5469",
"pm_score": 0,
"selected": false,
"text": "<p>My vote is two parameters for conversion types, one for the value (as in your first example). I would use enums instead of string literals, however.</p>\n"
},
{
"answer_id": 59112,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Use enums, if your language allows it, for the unit specifications.</p>\n\n<p>I'd say the code inside would be easier with two. I'd have a table with pre-add, multiplty, and post-add, and run the value through the item for one unit, and then through the item for the other unit in reverse. Basically converting the input temperature to a common base value inside, and then out to the other unit. This entire function would be table-driven.</p>\n"
},
{
"answer_id": 59117,
"author": "Adam Wright",
"author_id": 1200,
"author_profile": "https://Stackoverflow.com/users/1200",
"pm_score": 1,
"selected": false,
"text": "<p>Depends how many conversions you are going to have. I'd probably choose one parameter, given as an enum: Consider this expanded version of conversion.</p>\n\n<pre><code>enum Conversion\n{\n CelsiusToFahrenheit,\n FahrenheitToCelsius,\n KilosToPounds\n}\n\nConvert(Conversion conversion, X from);\n</code></pre>\n\n<p>You now have sane type safety at point of call - one cannot give correctly typed parameters that give an incorrect runtime result. Consider the alternative.</p>\n\n<pre><code>enum Units\n{\n Pounds,\n Kilos,\n Celcius,\n Farenheight\n}\n\nConvert(Unit from, Unit to, X fromAmount);\n</code></pre>\n\n<p>I can type safely call</p>\n\n<pre><code>Convert(Pounds, Celcius, 5, 10);\n</code></pre>\n\n<p>But the result is meaningless, and you'll have to fail at runtime. Yes, I know you're only dealing with temperature at the moment, but the general concept still holds (I believe).</p>\n"
},
{
"answer_id": 59118,
"author": "DaveK",
"author_id": 4244,
"author_profile": "https://Stackoverflow.com/users/4244",
"pm_score": 1,
"selected": false,
"text": "<p>I would make an enumeration out of the temperature types and pass in the 2 scale parameters. Something like (in c#):</p>\n\n<p><pre><code>\npublic void ConvertTemperature(TemperatureTypeEnum SourceTemp,\n TemperatureTypeEnum TargetTemp, \n decimal Temperature)\n{}\n</pre></code></p>\n"
},
{
"answer_id": 59123,
"author": "millenomi",
"author_id": 6061,
"author_profile": "https://Stackoverflow.com/users/6061",
"pm_score": 2,
"selected": false,
"text": "<p>A few things:</p>\n\n<ul>\n<li><p>I'd use an enumerated type that a syntax checker or compiler can check rather than a string that can be mistyped. In Pseudo-PHP:</p>\n\n<p>define ('kCelsius', 0); define ('kFarenheit', 1); define ('kKelvin', 2);\n$a = ConvertTemperature(22, kCelsius, kFarenheit);</p></li>\n</ul>\n\n<p>Also, it seems more natural to me to place the thing you operate on, in this case the temperature to be converted, <em>first</em>. It gives a logical ordering to your parameters (convert -- what? from? to?) and thus helps with mnemonics.</p>\n"
},
{
"answer_id": 59124,
"author": "Paul Stephenson",
"author_id": 5536,
"author_profile": "https://Stackoverflow.com/users/5536",
"pm_score": 1,
"selected": false,
"text": "<p>I would choose </p>\n\n<blockquote>\n <p>Example 1 - separate parameters: function convertTemperature(\"celsius\", \"fahrenheit\", 22)</p>\n</blockquote>\n\n<p>Otherwise within your function definition you would have to parse \"c-f\" into \"celsius\" and \"fahrenheit\" anyway to get the required conversion scales, which could get messy.</p>\n\n<p>If you're providing something like Google's search box to users, having handy shortcuts like \"c-f\" is nice for them. Underneath, though, I would convert \"c-f\" into \"celsius\" and \"fahrenheit\" in an outer function before calling convertTemperature() as above.</p>\n"
},
{
"answer_id": 59126,
"author": "aku",
"author_id": 1196,
"author_profile": "https://Stackoverflow.com/users/1196",
"pm_score": 1,
"selected": false,
"text": "<p>In this case single parameters looks totally obscure;</p>\n\n<p>Function convert <em>temperature</em> from <em>one scale</em> to <em>another scale</em>.<br>\nIMO it's more natural to pass source and target scales as separate parameters. I definitely don't want to try to grasp format of first argument.</p>\n"
},
{
"answer_id": 59131,
"author": "Rob Rolnick",
"author_id": 4798,
"author_profile": "https://Stackoverflow.com/users/4798",
"pm_score": 2,
"selected": false,
"text": "<p>When writing such designs, I like to think to myself, \"If I needed to add an extra unit, what would design would make it the easiest to do so?\" Doing this, I come to the conclusion that enums would be easiest for the following reasons:</p>\n\n<p>1) Adding new values is easy.\n2) I avoid doing string comparison</p>\n\n<p>However, how do you write the conversion method? 3p2 is 6. So that means there are 6 different combinations of celsius, Fahrenheit, and kelvin. What if I wanted to add a new temperate format \"foo\"? That would mean 4p2 which is 12! Two more? 5p2 = 20 combination. Three more? 6p2 = 30 combinations! </p>\n\n<p>You can quickly see how each additional modification requires more and more changes to the code. For this reason I don't do direct conversions! Instead, I do an intermediate conversion. I'd pick one temperature, say Kelvin. And initially, I'd convert to kelvin. I'd then convert kelvin to the desired temperature. Yes, It does result in an extra calculation. However, it makes scalling the code a ton easier. adding adding a new temperature unit will always result in only two new modifications to the code. Easy.</p>\n"
},
{
"answer_id": 59137,
"author": "Isaac Moses",
"author_id": 179,
"author_profile": "https://Stackoverflow.com/users/179",
"pm_score": 2,
"selected": false,
"text": "<p>Your function will be much more robust if you use the first approach. If you need to add another scale, that's one more parameter value to handle. In the second approach, adding another scale means adding as many values as you already had scales on the list, times 2. (For example, to add K to C and F, you'd have to add K-C, K-F, C-K, and C-F.)</p>\n\n<p>A decent way to structure your program would be to first convert whatever comes in to an arbitrarily chosen intermediate scale, and then convert from that intermediate scale to the outgoing scale.</p>\n\n<p>A better way would be to have a little library of slopes and intercepts for the various scales, and just look up the numbers for the incoming and outgoing scales and do the calculation in one generic step.</p>\n"
},
{
"answer_id": 59142,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 3,
"selected": false,
"text": "<p>Depends on the language.</p>\n\n<p>Generally, I'd use separate arguments with enums.</p>\n\n<p>If it's an object oriented language, then I'd recommend a temperature class, with the temperature stored internally however you like and then functions to output it in whatever units are needed:</p>\n\n<p>temp.celsius(); // returns the temperature of object temp in celsius</p>\n"
},
{
"answer_id": 59176,
"author": "Jay Bazuzi",
"author_id": 5314,
"author_profile": "https://Stackoverflow.com/users/5314",
"pm_score": 1,
"selected": false,
"text": "<p>I'm always on the lookout for ways to use objects to solve my programming problems. I hope this means that I'm more OO than when I was only using functions to solve problems, but that remains to be seen.</p>\n\n<p>In C#:</p>\n\n<pre><code>interface ITemperature\n{\n CelciusTemperature ToCelcius();\n FarenheitTemperature ToFarenheit();\n}\n\nstruct FarenheitTemperature : ITemperature\n{\n public readonly int Value;\n public FarenheitTemperature(int value)\n {\n this.Value = value;\n }\n\n public FarenheitTemperature ToFarenheit() { return this; }\n public CelciusTemperature ToCelcius()\n {\n return new CelciusTemperature((this.Value - 32) * 5 / 9);\n }\n\n}\n\nstruct CelciusTemperature\n{\n public readonly int Value;\n public CelciusTemperature(int value)\n {\n this.Value = value;\n }\n\n public CelciusTemperature ToCelcius() { return this; }\n public FarenheitTemperature ToFarenheit()\n {\n return new FarenheitTemperature(this.Value * 9 / 5 + 32);\n }\n}\n</code></pre>\n\n<p>and some tests:</p>\n\n<pre><code> // Freezing\n Debug.Assert(new FarenheitTemperature(32).ToCelcius().Equals(new CelciusTemperature(0)));\n Debug.Assert(new CelciusTemperature(0).ToFarenheit().Equals(new FarenheitTemperature(32)));\n\n // crossover\n Debug.Assert(new FarenheitTemperature(-40).ToCelcius().Equals(new CelciusTemperature(-40)));\n Debug.Assert(new CelciusTemperature(-40).ToFarenheit().Equals(new FarenheitTemperature(-40)));\n</code></pre>\n\n<p>and an example of a bug that this approach avoids:</p>\n\n<pre><code> CelciusTemperature theOutbackInAMidnightOilSong = new CelciusTemperature(45);\n FarenheitTemperature x = theOutbackInAMidnightOilSong; // ERROR: Cannot implicitly convert type 'CelciusTemperature' to 'FarenheitTemperature'\n</code></pre>\n\n<p>Adding Kelvin conversions is left as an exercise.</p>\n"
},
{
"answer_id": 59201,
"author": "wcm",
"author_id": 2173,
"author_profile": "https://Stackoverflow.com/users/2173",
"pm_score": 2,
"selected": false,
"text": "<p>In C# (and probaly Java) it would be best to create a Temperature class that stores temperatures privately as Celcius (or whatever) and which has Celcius, Fahrenheit, and Kelvin properties that do all the conversions for you in their get and set statements?</p>\n"
},
{
"answer_id": 59219,
"author": "Tyler",
"author_id": 3561,
"author_profile": "https://Stackoverflow.com/users/3561",
"pm_score": 1,
"selected": false,
"text": "<p>By the way, it doesn't have to be more work to implement the three-parameter version, as suggested in the question statement.</p>\n\n<p>These are all linear functions, so you can implement something like</p>\n\n<pre><code>float LinearConvert(float in, float scale, float add, bool invert);\n</code></pre>\n\n<p>where the last bool indicates if you want to do the forward transform or reverse it.</p>\n\n<p>Within your conversion technique, you can have a scale/add pair for X -> Kelvin. When you get a request to convert format X to Y, you can first run X -> Kelvin, then Kelvin -> Y by reversing the Y -> Kelvin process (by flipping the last bool to LinearConvert).</p>\n\n<p>This technique gives you something like 4 lines of real code in your convert function, and one piece of data for every type you need to convert between.</p>\n"
},
{
"answer_id": 59275,
"author": "Joel Gauvreau",
"author_id": 4789,
"author_profile": "https://Stackoverflow.com/users/4789",
"pm_score": 1,
"selected": false,
"text": "<p>Similar to what @Rob @wcm and @David explained... </p>\n\n<pre><code>public class Temperature\n{\n private double celcius;\n\n public static Temperature FromFarenheit(double farenheit)\n {\n return new Temperature { Farhenheit = farenheit };\n }\n\n public static Temperature FromCelcius(double celcius)\n {\n return new Temperature { Celcius = celcius };\n }\n\n public static Temperature FromKelvin(double kelvin)\n {\n return new Temperature { Kelvin = kelvin };\n }\n\n private double kelvinToCelcius(double kelvin)\n {\n return 1; // insert formula here\n }\n\n private double celciusToKelvin(double celcius)\n {\n return 1; // insert formula here\n }\n\n private double farhenheitToCelcius(double farhenheit)\n {\n return 1; // insert formula here\n }\n\n private double celciusToFarenheit(double kelvin)\n {\n return 1; // insert formula here\n }\n\n public double Kelvin\n {\n get { return celciusToKelvin(celcius); }\n set { celcius = kelvinToCelcius(value); }\n }\n\n public double Celcius\n {\n get { return celcius; }\n set { celcius = value; }\n }\n\n public double Farhenheit\n {\n get { return celciusToFarenheit(celcius); }\n set { celcius = farhenheitToCelcius(value); }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 59536,
"author": "Jon Ericson",
"author_id": 1438,
"author_profile": "https://Stackoverflow.com/users/1438",
"pm_score": 1,
"selected": false,
"text": "<p>I think I'd go whole hog one direction or another. You could write a mini-language that does any sort of conversion like <strong>units</strong> does:</p>\n\n<pre><code>$ units 'tempF(-40)' tempC\n -40\n</code></pre>\n\n<p>Or use individual functions like the recent <a href=\"http://search.cpan.org/~mopy/Convert-Temperature-0.03/\" rel=\"nofollow noreferrer\">Convert::Temperature</a> Perl module does:</p>\n\n<pre><code>use Convert::Temperature;\n\nmy $c = new Convert::Temperature();\n\nmy $res = $c->from_fahr_to_cel('59');\n</code></pre>\n\n<p>But that brings up an important point---does the language you are using already have conversion functions? If so, what coding convention do they use? So if the language is C, it would be best to follow the example of the atoi and strtod library functions (untested):</p>\n\n<pre><code>double fahrtocel(double tempF){\n return ((tempF-32)*(5/9));\n}\n\ndouble celtofahr(double tempC){\n return ((9/5)*tempC + 32);\n}\n</code></pre>\n\n<hr>\n\n<p>In writing this post, I ran across a <a href=\"http://www.leancrew.com/all-this/2008/04/emacs-lisp-as-a-scripting-language/\" rel=\"nofollow noreferrer\">very interesting post</a> on using emacs to convert dates. The take-away for this topic is that it uses the one function-per-conversion style. Also, conversions can be very obscure. I tend to do date calculations using SQL because it seems unlikely there are many bugs in that code. In the future, I'm going to look into using emacs.</p>\n"
},
{
"answer_id": 60250,
"author": "Scott",
"author_id": 6126,
"author_profile": "https://Stackoverflow.com/users/6126",
"pm_score": 0,
"selected": false,
"text": "<p>I wish there was some way to accept multiple answers. Based on everyone's recommendations, I think I will stick with the multiple parameters, changing the strings to enums/constants, and moving the value to be converted to the first position in the parameter list. Inside the function, I'll use Kelvin as a common middle ground.</p>\n\n<p>Previously I had written individual functions for each conversion and the overall convertTemperature() function was merely a wrapper with nested switch statements. I'm writing in both classic ASP and PHP, but I wanted to leave the question open to any language.</p>\n"
},
{
"answer_id": 4451615,
"author": "Alix Axel",
"author_id": 89771,
"author_profile": "https://Stackoverflow.com/users/89771",
"pm_score": 1,
"selected": false,
"text": "<p>Here is my take on this (using PHP):</p>\n\n<pre><code>function Temperature($value, $input, $output)\n{\n $value = floatval($value);\n\n if (isset($input, $output) === true)\n {\n switch ($input)\n {\n case 'K': $value = $value - 273.15; break; // Kelvin\n case 'F': $value = ($value - 32) * (5 / 9); break; // Fahrenheit\n case 'R': $value = ($value - 491.67) * (5 / 9); break; // Rankine\n }\n\n switch ($output)\n {\n case 'K': $value = $value + 273.15; break; // Kelvin\n case 'F': $value = $value * (9 / 5) + 32; break; // Fahrenheit\n case 'R': $value = ($value + 273.15) * (9 / 5); break; // Rankine\n }\n }\n\n return $value;\n}\n</code></pre>\n\n<p>Basically the <code>$input</code> value is converted to the standard Celsius scale and then converted back again to the <code>$output</code> scale - one function to rule them all. =)</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6126/"
]
| Let's say that I'm writing a function to convert between temperature scales. I want to support at least Celsius, Fahrenheit, and Kelvin. Is it better to pass the source scale and target scale as separate parameters of the function, or some sort of combined parameter?
Example 1 - separate parameters:
function convertTemperature("celsius", "fahrenheit", 22)
Example 2 - combined parameter:
function convertTemperature("c-f", 22)
The code inside the function is probably where it counts. With two parameters, the logic to determine what formula we're going to use is slightly more complicated, but a single parameter doesn't feel right somehow.
Thoughts? | Go with the first option, but rather than allow literal strings (which are error prone), take constant values or an enumeration if your language supports it, like this:
```
convertTemperature (TempScale.CELSIUS, TempScale.FAHRENHEIT, 22)
``` |
59,107 | <p>I'm converting an application to use Java 1.5 and have found the following method:</p>
<pre><code> /**
* Compare two Comparables, treat nulls as -infinity.
* @param o1
* @param o2
* @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2
*/
protected static int nullCompare(Comparable o1, Comparable o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1;
}
} else if (o2 == null) {
return 1;
} else {
return o1.compareTo(o2);
}
}
</code></pre>
<p>Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how? </p>
<p>I thought the following would do the trick:</p>
<pre><code>protected static <T extends Comparable> int nullCompare(T o1, T o2) {
</code></pre>
<p>but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line:</p>
<pre><code>return o1.compareTo(o2);
</code></pre>
| [
{
"answer_id": 59119,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "<p>Change it to:</p>\n\n<pre><code>protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>You need that because Comparable is itself a generic type.</p>\n"
},
{
"answer_id": 85739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an odd case:</p>\n\n<pre><code>static class A {\n ...\n}\n\nstatic class B extends A implements Comparable<A> {\n public int compareTo(A o) {\n return ...;\n }\n}\n</code></pre>\n\n<p>Luckily code like the one above is rare, but nullCompare() will not support comparison of Bs unless it is stated that Comparable may apply to T <em>or any superclass thereof</em>:</p>\n\n<pre><code>protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>Even though most people will never benefit from the above tweak, it may come in handy when designing APIs for exported libraries.</p>\n"
},
{
"answer_id": 115539,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure that genericizing this method makes sense. Currently the method works on any kind of Comparable; if you genericize it you will have to implement it (with exactly the same code) multiple times. Sometimes it is possible to compare two objects that don't have a common ancestor, and any generic version won't allow this.</p>\n\n<p>By adding generics you won't add any safety to the code; any problems of safety will occur in the call to compareTo. What I would suggest is simply suppressing the warning. It's not really warning you about anything useful.</p>\n"
},
{
"answer_id": 227885,
"author": "mjlee",
"author_id": 2829,
"author_profile": "https://Stackoverflow.com/users/2829",
"pm_score": 2,
"selected": false,
"text": "<p>Cannot edit so I have to post my answer.</p>\n\n<p>You need to declare nested type parameter since Comparable is generic.</p>\n\n<pre><code>protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>Please note that <strong>Comparable< ? super T ></strong>, which makes more flexible. You will see the same method definition on Collections.sort</p>\n\n<pre><code>public static <T extends Comparable<? super T>> void sort(List<T> list) {\n</code></pre>\n"
},
{
"answer_id": 815484,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 0,
"selected": false,
"text": "<p>To make it even more general, you could even allow it to work for two different types. =P</p>\n\n<pre><code> /**\n * Compare two Comparables, treat nulls as -infinity.\n * @param o1\n * @param o2\n * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2\n */\n protected static <T> int nullCompare(Comparable<? super T> o1, T o2) {\n if (o1 == null) {\n if (o2 == null) {\n return 0;\n } else {\n return -1;\n }\n } else if (o2 == null) {\n return 1;\n } else {\n return o1.compareTo(o2);\n }\n }\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4389/"
]
| I'm converting an application to use Java 1.5 and have found the following method:
```
/**
* Compare two Comparables, treat nulls as -infinity.
* @param o1
* @param o2
* @return -1 if o1<o2, 0 if o1==o2, 1 if o1>o2
*/
protected static int nullCompare(Comparable o1, Comparable o2) {
if (o1 == null) {
if (o2 == null) {
return 0;
} else {
return -1;
}
} else if (o2 == null) {
return 1;
} else {
return o1.compareTo(o2);
}
}
```
Ideally I would like to make the method take two Comparables of the same type, is it possible to convert this and how?
I thought the following would do the trick:
```
protected static <T extends Comparable> int nullCompare(T o1, T o2) {
```
but it has failed to get rid of a warning in IntelliJ "Unchecked call to 'compareTo(T)' as a member of raw type 'java.lang.Comparable'" on the line:
```
return o1.compareTo(o2);
``` | Change it to:
```
protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {
```
You need that because Comparable is itself a generic type. |
59,120 | <p>I am getting this error now that I hit version number 1.256.0:
Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####'</p>
<p>The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com:
The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<a href="http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx</a>)</p>
<p>Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.</p>
<p>Does anyone have any ideas on why this would be failing now?</p>
| [
{
"answer_id": 59119,
"author": "jodonnell",
"author_id": 4223,
"author_profile": "https://Stackoverflow.com/users/4223",
"pm_score": 5,
"selected": true,
"text": "<p>Change it to:</p>\n\n<pre><code>protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>You need that because Comparable is itself a generic type.</p>\n"
},
{
"answer_id": 85739,
"author": "volley",
"author_id": 13905,
"author_profile": "https://Stackoverflow.com/users/13905",
"pm_score": 3,
"selected": false,
"text": "<p>Here's an odd case:</p>\n\n<pre><code>static class A {\n ...\n}\n\nstatic class B extends A implements Comparable<A> {\n public int compareTo(A o) {\n return ...;\n }\n}\n</code></pre>\n\n<p>Luckily code like the one above is rare, but nullCompare() will not support comparison of Bs unless it is stated that Comparable may apply to T <em>or any superclass thereof</em>:</p>\n\n<pre><code>protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>Even though most people will never benefit from the above tweak, it may come in handy when designing APIs for exported libraries.</p>\n"
},
{
"answer_id": 115539,
"author": "DJClayworth",
"author_id": 19276,
"author_profile": "https://Stackoverflow.com/users/19276",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure that genericizing this method makes sense. Currently the method works on any kind of Comparable; if you genericize it you will have to implement it (with exactly the same code) multiple times. Sometimes it is possible to compare two objects that don't have a common ancestor, and any generic version won't allow this.</p>\n\n<p>By adding generics you won't add any safety to the code; any problems of safety will occur in the call to compareTo. What I would suggest is simply suppressing the warning. It's not really warning you about anything useful.</p>\n"
},
{
"answer_id": 227885,
"author": "mjlee",
"author_id": 2829,
"author_profile": "https://Stackoverflow.com/users/2829",
"pm_score": 2,
"selected": false,
"text": "<p>Cannot edit so I have to post my answer.</p>\n\n<p>You need to declare nested type parameter since Comparable is generic.</p>\n\n<pre><code>protected static <T extends Comparable<? super T>> int nullCompare(T o1, T o2) {\n</code></pre>\n\n<p>Please note that <strong>Comparable< ? super T ></strong>, which makes more flexible. You will see the same method definition on Collections.sort</p>\n\n<pre><code>public static <T extends Comparable<? super T>> void sort(List<T> list) {\n</code></pre>\n"
},
{
"answer_id": 815484,
"author": "newacct",
"author_id": 86989,
"author_profile": "https://Stackoverflow.com/users/86989",
"pm_score": 0,
"selected": false,
"text": "<p>To make it even more general, you could even allow it to work for two different types. =P</p>\n\n<pre><code> /**\n * Compare two Comparables, treat nulls as -infinity.\n * @param o1\n * @param o2\n * @return -1 if o1&lt;o2, 0 if o1==o2, 1 if o1&gt;o2\n */\n protected static <T> int nullCompare(Comparable<? super T> o1, T o2) {\n if (o1 == null) {\n if (o2 == null) {\n return 0;\n } else {\n return -1;\n }\n } else if (o2 == null) {\n return 1;\n } else {\n return o1.compareTo(o2);\n }\n }\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5967/"
]
| I am getting this error now that I hit version number 1.256.0:
Error 4 Invalid product version '1.256.0'. Must be of format '##.##.####'
The installer was fine with 1.255.0 but something with 256 (2^8) it doesn't like. I found this stated on msdn.com:
The Version property must be formatted as N.N.N, where each N represents at least one and no more than four digits. (<http://msdn.microsoft.com/en-us/library/d3ywkte8(VS.80).aspx>)
Which would make me believe there is nothing wrong 1.256.0 because it meets the rules stated above.
Does anyone have any ideas on why this would be failing now? | Change it to:
```
protected static <T extends Comparable<T>> int nullCompare(T o1, T o2) {
```
You need that because Comparable is itself a generic type. |
59,166 | <p>So I have an object which has some fields, doesn't really matter what.
I have a generic list of these objects.</p>
<pre><code>List<MyObject> myObjects = new List<MyObject>();
myObjects.Add(myObject1);
myObjects.Add(myObject2);
myObjects.Add(myObject3);
</code></pre>
<p>So I want to remove objects from my list based on some criteria.
For instance, <code>myObject.X >= 10.</code>
I would like to use the <code>RemoveAll(Predicate<T> match)</code> method for to do this.</p>
<p>I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place.</p>
| [
{
"answer_id": 59172,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 7,
"selected": true,
"text": "<p>There's two options, an explicit delegate or a delegate disguised as a lamba construct:</p>\n<p>explicit delegate</p>\n<pre><code>myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });\n</code></pre>\n<p>lambda</p>\n<pre><code>myObjects.RemoveAll(m => m.X >= 10);\n</code></pre>\n<hr />\n<p>Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs</p>\n"
},
{
"answer_id": 59174,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 4,
"selected": false,
"text": "<p>The lambda C# 3.0 way:</p>\n\n<pre><code>myObjects.RemoveAll(m => m.x >= 10);\n</code></pre>\n\n<p>The anonymous delegate C# 2.0 way:</p>\n\n<pre><code>myObjects.RemoveAll(delegate (MyObject m) {\n return m.x >= 10;\n});\n</code></pre>\n\n<p>And, for the VB guys, the VB 9.0 lambda way:</p>\n\n<pre><code>myObjects.RemoveAll(Function(m) m.x >= 10)\n</code></pre>\n\n<p>Unfortunately, VB doesn't support an anonymous delegate.</p>\n"
},
{
"answer_id": 59177,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "<pre><code> //C# 2.0\n RemoveAll(delegate(Foo o){ return o.X >= 10; });\n</code></pre>\n\n<p>or</p>\n\n<pre><code> //C# 3.0\n RemoveAll(o => o.X >= 10);\n</code></pre>\n\n<p>or</p>\n\n<pre><code> Predicate<Foo> matches = delegate(Foo o){ return o.X >= 10; });\n //or Predicate<Foo> matches = o => o.X >= 10;\n RemoveAll(matches);\n</code></pre>\n"
},
{
"answer_id": 47375389,
"author": "Nayas Subramanian",
"author_id": 4315441,
"author_profile": "https://Stackoverflow.com/users/4315441",
"pm_score": 1,
"selected": false,
"text": "<p>Predicate is a delegate which takes an param and returns a boolean.</p>\n\n<p>We can do the same in following ways</p>\n\n<p>1) <strong>Using inline Lambda expression</strong></p>\n\n<pre><code>RemoveAll(p=> p.x > 2);\n</code></pre>\n\n<p>2) <strong>Using anonymous function</strong></p>\n\n<pre><code>RemoveAll(delegate(myObject obj){\n\n return obj.x >=10;\n})\n</code></pre>\n\n<p>3) <strong>Using Predicate delegate</strong></p>\n\n<pre><code>Predicate<myObject> matches = new Predicate<myObject>(IsEmployeeIsValid);\nRemoveAll(matches);\n\nPredicate<Foo> matches = delegate(Foo o){ return o.X >= 20; });\nRemoveAll(matches);\n</code></pre>\n\n<p>3) <strong>Declaring a delegate explicitily and pointing to a function</strong></p>\n\n<pre><code>public delegate bool IsInValidEmployee (Employee emp);\n\nIsInValidEmployee invalidEmployeeDelegate = new IsInValidEmployee(IsEmployeeInValid);\nmyObjects.RemoveAll(myObject=>invalidEmployeeDelegate(myObject);\n</code></pre>\n\n<p>// Actual function</p>\n\n<pre><code>public static bool IsEmployeeInValid(Employee emp)\n{\n if (emp.Id > 0 )\n return true;\n else\n return false;\n}\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59166",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/454247/"
]
| So I have an object which has some fields, doesn't really matter what.
I have a generic list of these objects.
```
List<MyObject> myObjects = new List<MyObject>();
myObjects.Add(myObject1);
myObjects.Add(myObject2);
myObjects.Add(myObject3);
```
So I want to remove objects from my list based on some criteria.
For instance, `myObject.X >= 10.`
I would like to use the `RemoveAll(Predicate<T> match)` method for to do this.
I know I can define a delegate which can be passed into RemoveAll, but I would like to know how to define this inline with an anonymous delegate, instead of creating a bunch of delegate functions which are only used in once place. | There's two options, an explicit delegate or a delegate disguised as a lamba construct:
explicit delegate
```
myObjects.RemoveAll(delegate (MyObject m) { return m.X >= 10; });
```
lambda
```
myObjects.RemoveAll(m => m.X >= 10);
```
---
Performance wise both are equal. As a matter of fact, both language constructs generate the same IL when compiled. This is because C# 3.0 is basically an extension on C# 2.0, so it compiles to C# 2.0 constructs |
59,181 | <p>I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error. </p>
<p>Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem</p>
<p>From the browser </p>
<p><a href="https://Myserver/MyApp/Services/MyService.svc" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc</a> displays the service metadata</p>
<p>however </p>
<p><a href="https://Myserver/MyApp/Services/MyService.svc/jsdebug" rel="nofollow noreferrer">https://Myserver/MyApp/Services/MyService.svc/jsdebug</a> results in a 404.</p>
<p>The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file.</p>
<p>Any ideas?</p>
<p>TIA</p>
| [
{
"answer_id": 59764,
"author": "rams",
"author_id": 3635,
"author_profile": "https://Stackoverflow.com/users/3635",
"pm_score": 5,
"selected": true,
"text": "<p>Figured it out!</p>\n\n<p>Here is the services configuration section from web.config</p>\n\n<p>Look at the bindingConfiguration attribute on the endpoint. The value \"webBinding\" points to the binding name=\"webBinding\" tag in the bindings and that is what tells the service to use Transport level security it HTTPS. In my case the attribute value was empty causing the webservice request to the /js or /jsdebug file over HTTPS to fail and throw a 404 error.</p>\n\n<pre><code><services>\n <service name=\"MyService\">\n <endpoint address=\"\" behaviorConfiguration=\"MyServiceAspNetAjaxBehavior\" binding=\"webHttpBinding\" bindingConfiguration=\"webBinding\" contract=\"Services.MyService\" />\n </service>\n </services>\n <bindings>\n <webHttpBinding>\n <binding name=\"webBinding\">\n <security mode=\"Transport\">\n </security>\n </binding>\n </webHttpBinding>\n </bindings>\n</code></pre>\n\n<p>Note that the bindingConfiguration attribute should be empty (\"\") if the service is accessed via http instead of https (when testing on local machine with no certs)</p>\n\n<p>Hope this helps someone.</p>\n"
},
{
"answer_id": 18653154,
"author": "Aatif Shabbir",
"author_id": 2677615,
"author_profile": "https://Stackoverflow.com/users/2677615",
"pm_score": 0,
"selected": false,
"text": "<p>If you still get the same error after all your possible work done. Just add a \"AJAX Enabled WCF-Service\".</p>\n"
},
{
"answer_id": 30665983,
"author": "garryp",
"author_id": 3395015,
"author_profile": "https://Stackoverflow.com/users/3395015",
"pm_score": 0,
"selected": false,
"text": "<p>For me the issue was the following; we added MVC to a solution with routing. Our WCF services were not being ignored. I resolved this by adding the following rule (where \"WCF\" is the folder we keep our services in).</p>\n\n<pre><code>routes.IgnoreRoute(\"WCF/{*pathInfo}\");\n</code></pre>\n\n<p>Hope that saves somebody a few hours.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59181",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3635/"
]
| I have a WCF service that gets called from client side JavaScript. The call fails with a Service is null JavaScript error. WebDevelopment helper trace shows that the calls to load the jsdebug support file results in a 404 (file not found) error.
Restarting IIS or clearing out the Temp ASP.Net files or setting batch="false" on the compilation tag in web.config does not resolve the problem
From the browser
<https://Myserver/MyApp/Services/MyService.svc> displays the service metadata
however
<https://Myserver/MyApp/Services/MyService.svc/jsdebug> results in a 404.
The issue seems to be with the https protocol. With http /jsdebug downloads the supporting JS file.
Any ideas?
TIA | Figured it out!
Here is the services configuration section from web.config
Look at the bindingConfiguration attribute on the endpoint. The value "webBinding" points to the binding name="webBinding" tag in the bindings and that is what tells the service to use Transport level security it HTTPS. In my case the attribute value was empty causing the webservice request to the /js or /jsdebug file over HTTPS to fail and throw a 404 error.
```
<services>
<service name="MyService">
<endpoint address="" behaviorConfiguration="MyServiceAspNetAjaxBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="Services.MyService" />
</service>
</services>
<bindings>
<webHttpBinding>
<binding name="webBinding">
<security mode="Transport">
</security>
</binding>
</webHttpBinding>
</bindings>
```
Note that the bindingConfiguration attribute should be empty ("") if the service is accessed via http instead of https (when testing on local machine with no certs)
Hope this helps someone. |
59,182 | <p>What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser? The button is currently defines like this:</p>
<pre><code><asp:button id="btnFind"
runat="server"
Text="Find Info"
onclick="btnFind_Click">
</asp:button>
</code></pre>
<p><strong>Update:</strong></p>
<p>This appears to be specific to IE7, IE6 and FF do not show the URL in the status bar.</p>
| [
{
"answer_id": 59189,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": true,
"text": "<p>I use FF so never noticed this, but the link does in fact appear in the status bar in IE..</p>\n<p>I dont think you can overwrite it :( I initially thought maybe setting the ToolTip (al la "title") property might do it.. Seems it does not..</p>\n<p>Looking at the source, what appears is nowhere to be found, so I would say this is a <em>browser</em> issue, I don't think you can do anything in code.. :(</p>\n<h2>Update</h2>\n<p>Yeah, Looks like IE always posts whatever the form action is.. Can't see a way to override it, as yet..</p>\n<p>Perhaps try explicitly setting it via JS?</p>\n<h2>Update II</h2>\n<p>Done some more Googleing. Don't think there really is a "nice" way of doing it.. Unless you remove the form all together and post data some other way..</p>\n<p><strong>Is it really worth that much? Generally this just tends to be the page name?</strong></p>\n"
},
{
"answer_id": 59234,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": -1,
"selected": false,
"text": "<p>I don't see a link, I see this:</p>\n\n<pre><code>javascript:__doPostBack('btn','');\n</code></pre>\n\n<p><strong>EDIT</strong>: Sorry, was looking at a LinkButton, not an ASP:Button. The ASP:Button shows the forms ACTION element like stated. </p>\n\n<p>But, if you are trying to hide the DoPostBackCall, the only way to do that is to directly manipulate window.status with javascript. <strong>The downside is most browsers don't allow this anymore.</strong></p>\n\n<p>To do that, in your page_load add:</p>\n\n<pre><code>btnFind.Attributes.Add(\"onmouseover\",\"window.status = '';\");\nbtnFind.Attributes.Add(\"onmouseout\",\"window.status = '';\");\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59182",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/206/"
]
| What is the best way to keep an asp:button from displaying it's URL on the status bar of the browser? The button is currently defines like this:
```
<asp:button id="btnFind"
runat="server"
Text="Find Info"
onclick="btnFind_Click">
</asp:button>
```
**Update:**
This appears to be specific to IE7, IE6 and FF do not show the URL in the status bar. | I use FF so never noticed this, but the link does in fact appear in the status bar in IE..
I dont think you can overwrite it :( I initially thought maybe setting the ToolTip (al la "title") property might do it.. Seems it does not..
Looking at the source, what appears is nowhere to be found, so I would say this is a *browser* issue, I don't think you can do anything in code.. :(
Update
------
Yeah, Looks like IE always posts whatever the form action is.. Can't see a way to override it, as yet..
Perhaps try explicitly setting it via JS?
Update II
---------
Done some more Googleing. Don't think there really is a "nice" way of doing it.. Unless you remove the form all together and post data some other way..
**Is it really worth that much? Generally this just tends to be the page name?** |
59,217 | <p>Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?</p>
<p>The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.</p>
<p>I'm looking to avoid writing my own function to accomplish this if possible.</p>
| [
{
"answer_id": 59230,
"author": "GEOCHET",
"author_id": 5640,
"author_profile": "https://Stackoverflow.com/users/5640",
"pm_score": 3,
"selected": false,
"text": "<p>I think you can use <a href=\"http://msdn.microsoft.com/en-us/library/y5s0whfd.aspx\" rel=\"noreferrer\">Array.Copy</a> for this. It takes a source index and destination index so you should be able to append the one array to the other. If you need to go more complex than just appending one to the other, this may not be the right tool for you.</p>\n"
},
{
"answer_id": 59233,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming the destination array has enough space, <a href=\"https://msdn.microsoft.com/en-us/library/system.array.copy%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>Array.Copy()</code></a> will work. You might also try using a <code>List<T></code> and its <a href=\"https://msdn.microsoft.com/en-us/library/z883w3dc%28v=vs.110%29.aspx\" rel=\"nofollow noreferrer\"><code>.AddRange()</code></a> method.</p>\n"
},
{
"answer_id": 59246,
"author": "apandit",
"author_id": 6128,
"author_profile": "https://Stackoverflow.com/users/6128",
"pm_score": 0,
"selected": false,
"text": "<p>I'm assuming you're using your own array types as opposed to the built-in .NET arrays:<br /></p>\n\n<pre><code>public string[] merge(input1, input2)\n{\n string[] output = new string[input1.length + input2.length];\n for(int i = 0; i < output.length; i++)\n {\n if (i >= input1.length)\n output[i] = input2[i-input1.length];\n else\n output[i] = input1[i];\n }\n return output;\n}\n</code></pre>\n\n<p>Another way of doing this would be using the built in ArrayList class.</p>\n\n<pre><code>public ArrayList merge(input1, input2)\n{\n Arraylist output = new ArrayList();\n foreach(string val in input1)\n output.add(val);\n foreach(string val in input2)\n output.add(val);\n return output;\n}\n</code></pre>\n\n<p>Both examples are C#.</p>\n"
},
{
"answer_id": 59250,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "<p>If you can manipulate one of the arrays, you can resize it before performing the copy:</p>\n\n<pre><code>T[] array1 = getOneArray();\nT[] array2 = getAnotherArray();\nint array1OriginalLength = array1.Length;\nArray.Resize<T>(ref array1, array1OriginalLength + array2.Length);\nArray.Copy(array2, 0, array1, array1OriginalLength, array2.Length);\n</code></pre>\n\n<p>Otherwise, you can make a new array</p>\n\n<pre><code>T[] array1 = getOneArray();\nT[] array2 = getAnotherArray();\nT[] newArray = new T[array1.Length + array2.Length];\nArray.Copy(array1, newArray, array1.Length);\nArray.Copy(array2, 0, newArray, array1.Length, array2.Length);\n</code></pre>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.array.aspx\" rel=\"noreferrer\">More on available Array methods on MSDN</a>.</p>\n"
},
{
"answer_id": 59253,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>First, make sure you ask yourself the question \"Should I really be using an Array here\"?</p>\n\n<p>Unless you're building something where speed is of the utmost importance, a typed List, like <code>List<int></code> is probably the way to go. The only time I ever use arrays are for byte arrays when sending stuff over the network. Other than that, I never touch them.</p>\n"
},
{
"answer_id": 59262,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 9,
"selected": false,
"text": "<p>In C# 3.0 you can use LINQ's <a href=\"https://msdn.microsoft.com/en-us/library/vstudio/bb302894%28v=vs.100%29.aspx\" rel=\"noreferrer\">Concat</a> method to accomplish this easily:</p>\n\n<pre><code>int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\nint[] combined = front.Concat(back).ToArray();\n</code></pre>\n\n<p>In C# 2.0 you don't have such a direct way, but Array.Copy is probably the best solution:</p>\n\n<pre><code>int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\n\nint[] combined = new int[front.Length + back.Length];\nArray.Copy(front, combined, front.Length);\nArray.Copy(back, 0, combined, front.Length, back.Length);\n</code></pre>\n\n<p>This could easily be used to implement your own version of <code>Concat</code>.</p>\n"
},
{
"answer_id": 8770946,
"author": "namco",
"author_id": 591826,
"author_profile": "https://Stackoverflow.com/users/591826",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>ArrayLIst al = new ArrayList();\nal.AddRange(array_1);\nal.AddRange(array_2);\nal.AddRange(array_3);\narray_4 = al.ToArray();\n</code></pre>\n"
},
{
"answer_id": 15482599,
"author": "pasx",
"author_id": 683319,
"author_profile": "https://Stackoverflow.com/users/683319",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a simple example using Array.CopyTo.\nI think that it answers your question and gives an example of CopyTo usage - I am always puzzled when I need to use this function because the help is a bit unclear - the index is the position in the destination array where inserting occurs.</p>\n\n<pre><code>int[] xSrc1 = new int[3] { 0, 1, 2 };\nint[] xSrc2 = new int[5] { 3, 4, 5, 6 , 7 };\n\nint[] xAll = new int[xSrc1.Length + xSrc2.Length];\nxSrc1.CopyTo(xAll, 0);\nxSrc2.CopyTo(xAll, xSrc1.Length);\n</code></pre>\n\n<p>I guess you can't get it much simpler.</p>\n"
},
{
"answer_id": 15997813,
"author": "vikasse",
"author_id": 545620,
"author_profile": "https://Stackoverflow.com/users/545620",
"pm_score": 0,
"selected": false,
"text": "<pre><code>int [] SouceArray1 = new int[] {2,1,3};\nint [] SourceArray2 = new int[] {4,5,6};\nint [] targetArray = new int [SouceArray1.Length + SourceArray2.Length];\nSouceArray1.CopyTo(targetArray,0);\nSourceArray2.CopyTo(targetArray,SouceArray1.Length) ; \nforeach (int i in targetArray) Console.WriteLine(i + \" \"); \n</code></pre>\n\n<p>Using the above code two Arrays can be easily merged.</p>\n"
},
{
"answer_id": 20531421,
"author": "Lorenz Lo Sauer",
"author_id": 901946,
"author_profile": "https://Stackoverflow.com/users/901946",
"pm_score": 2,
"selected": false,
"text": "<p>Personally, I prefer my own Language Extensions, which I add or remove at will for rapid prototyping.</p>\n\n<p>Following is an example for strings.</p>\n\n<pre><code>//resides in IEnumerableStringExtensions.cs\npublic static class IEnumerableStringExtensions\n{\n public static IEnumerable<string> Append(this string[] arrayInitial, string[] arrayToAppend)\n {\n string[] ret = new string[arrayInitial.Length + arrayToAppend.Length];\n arrayInitial.CopyTo(ret, 0);\n arrayToAppend.CopyTo(ret, arrayInitial.Length);\n\n return ret;\n }\n}\n</code></pre>\n\n<p>It is much faster than LINQ and Concat. Faster still, is using a custom <code>IEnumerable</code> Type-wrapper which stores references/pointers of passed arrays and allows looping over the entire collection as if it were a normal array. (Useful in HPC, Graphics Processing, Graphics render...)</p>\n\n<p><strong>Your Code:</strong></p>\n\n<pre><code>var someStringArray = new[]{\"a\", \"b\", \"c\"};\nvar someStringArray2 = new[]{\"d\", \"e\", \"f\"};\nsomeStringArray.Append(someStringArray2 ); //contains a,b,c,d,e,f\n</code></pre>\n\n<p>For the entire code and a generics version see: <a href=\"https://gist.github.com/lsauer/7919764\" rel=\"nofollow\">https://gist.github.com/lsauer/7919764</a></p>\n\n<p><strong>Note:</strong> This returns an unextended IEnumerable object. To return an extended object is a bit slower.</p>\n\n<p><em>I compiled such extensions since 2002, with a lot of credits going to helpful people on CodeProject and 'Stackoverflow'. I will release these shortly and put the link up here.</em></p>\n"
},
{
"answer_id": 23822750,
"author": "Simon B.",
"author_id": 3667854,
"author_profile": "https://Stackoverflow.com/users/3667854",
"pm_score": 7,
"selected": false,
"text": "<p>Use <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"noreferrer\">LINQ</a>:</p>\n\n<pre><code>var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = arr1.Union(arr2).ToArray();\n</code></pre>\n\n<p>Keep in mind, this will remove duplicates. If you want to keep duplicates, use Concat. </p>\n"
},
{
"answer_id": 24958986,
"author": "Angelo Ortega",
"author_id": 3877523,
"author_profile": "https://Stackoverflow.com/users/3877523",
"pm_score": 4,
"selected": false,
"text": "<p>Easier would just be using <a href=\"http://en.wikipedia.org/wiki/Language_Integrated_Query\" rel=\"noreferrer\">LINQ</a>:</p>\n\n<pre><code>var array = new string[] { \"test\" }.ToList();\nvar array1 = new string[] { \"test\" }.ToList();\narray.AddRange(array1);\nvar result = array.ToArray();\n</code></pre>\n\n<p>First convert the arrays to lists and merge them... After that just convert the list back to an array :)</p>\n"
},
{
"answer_id": 27306348,
"author": "Lukas",
"author_id": 593388,
"author_profile": "https://Stackoverflow.com/users/593388",
"pm_score": 2,
"selected": false,
"text": "<p>In case someone else is looking for how to merge two image byte arrays:</p>\n\n<pre><code> private void LoadImage()\n {\n string src = string.empty;\n byte[] mergedImageData = new byte[0];\n\n mergedImageData = MergeTwoImageByteArrays(watermarkByteArray, backgroundImageByteArray);\n src = \"data:image/png;base64,\" + Convert.ToBase64String(mergedImageData);\n MyImage.ImageUrl = src;\n }\n\n private byte[] MergeTwoImageByteArrays(byte[] imageBytes, byte[] imageBaseBytes)\n {\n byte[] mergedImageData = new byte[0];\n using (var msBase = new MemoryStream(imageBaseBytes))\n {\n System.Drawing.Image imgBase = System.Drawing.Image.FromStream(msBase);\n Graphics gBase = Graphics.FromImage(imgBase);\n using (var msInfo = new MemoryStream(imageBytes))\n {\n System.Drawing.Image imgInfo = System.Drawing.Image.FromStream(msInfo);\n Graphics gInfo = Graphics.FromImage(imgInfo);\n gBase.DrawImage(imgInfo, new Point(0, 0));\n //imgBase.Save(Server.MapPath(\"_____testImg.png\"), ImageFormat.Png);\n MemoryStream mergedImageStream = new MemoryStream();\n imgBase.Save(mergedImageStream, ImageFormat.Png);\n mergedImageData = mergedImageStream.ToArray();\n mergedImageStream.Close();\n }\n }\n return mergedImageData;\n }\n</code></pre>\n"
},
{
"answer_id": 29591722,
"author": "Rajkumar M",
"author_id": 4779984,
"author_profile": "https://Stackoverflow.com/users/4779984",
"pm_score": -1,
"selected": false,
"text": "<p>This code will work for all cases:</p>\n\n<pre><code>int[] a1 ={3,4,5,6};\nint[] a2 = {4,7,9};\nint i = a1.Length-1;\nint j = a2.Length-1;\nint resultIndex= i+j+1;\nArray.Resize(ref a2, a1.Length +a2.Length);\nwhile(resultIndex >=0)\n{\n if(i != 0 && j !=0)\n {\n if(a1[i] > a2[j])\n {\n a2[resultIndex--] = a[i--];\n }\n else\n {\n a2[resultIndex--] = a[j--];\n }\n }\n else if(i>=0 && j<=0)\n { \n a2[resultIndex--] = a[i--];\n }\n else if(j>=0 && i <=0)\n {\n a2[resultIndex--] = a[j--];\n }\n}\n</code></pre>\n"
},
{
"answer_id": 35873378,
"author": "John Reilly",
"author_id": 761388,
"author_profile": "https://Stackoverflow.com/users/761388",
"pm_score": 3,
"selected": false,
"text": "<p>Everyone has already had their say but I think this more readable than the \"use as Extension method\" approach:</p>\n\n<pre><code>var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = Queryable.Concat(arr1, arr2).ToArray();\n</code></pre>\n\n<p>However it can only be used when bringing together 2 arrays.</p>\n"
},
{
"answer_id": 42333029,
"author": "Solomon Rutzky",
"author_id": 577765,
"author_profile": "https://Stackoverflow.com/users/577765",
"pm_score": 2,
"selected": false,
"text": "<p>Just to have it noted as an option: if the arrays you are working with are of a primitive type – Boolean (bool), Char, SByte, Byte, Int16 (short), UInt16, Int32 (int), UInt32, Int64 (long), UInt64, IntPtr, UIntPtr, Single, or Double – then you could (or should?) try using <a href=\"https://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx\" rel=\"nofollow noreferrer\">Buffer.BlockCopy</a>. According to the MSDN page for the <a href=\"https://msdn.microsoft.com/en-us/library/system.buffer.aspx\" rel=\"nofollow noreferrer\">Buffer</a> class:</p>\n\n<blockquote>\n <p>This class provides better performance for manipulating primitive types than similar methods in the <a href=\"https://msdn.microsoft.com/en-us/library/system.array.aspx\" rel=\"nofollow noreferrer\">System.Array</a> class.</p>\n</blockquote>\n\n<p>Using the C# 2.0 example from @OwenP's <a href=\"https://stackoverflow.com/a/59262/577765\">answer</a> as a starting point, it would work as follows:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>int[] front = { 1, 2, 3, 4 };\nint[] back = { 5, 6, 7, 8 };\n\nint[] combined = new int[front.Length + back.Length];\nBuffer.BlockCopy(front, 0, combined, 0, front.Length);\nBuffer.BlockCopy(back, 0, combined, front.Length, back.Length);\n</code></pre>\n\n<p>There is barely any difference in syntax between <code>Buffer.BlockCopy</code> and the <code>Array.Copy</code> that @OwenP used, but this should be faster (even if only slightly).</p>\n"
},
{
"answer_id": 43250371,
"author": "Smith",
"author_id": 362461,
"author_profile": "https://Stackoverflow.com/users/362461",
"pm_score": 6,
"selected": false,
"text": "<p>If you don't want to remove duplicates, then try this</p>\n\n<p>Use LINQ:</p>\n\n<pre><code>var arr1 = new[] { 1, 2, 3, 4, 5 };\nvar arr2 = new[] { 6, 7, 8, 9, 0 };\nvar arr = arr1.Concat(arr2).ToArray();\n</code></pre>\n"
},
{
"answer_id": 46849562,
"author": "Lord Darth Vader",
"author_id": 2527116,
"author_profile": "https://Stackoverflow.com/users/2527116",
"pm_score": 0,
"selected": false,
"text": "<p>Created and extension method to handle null</p>\n\n<pre><code>public static class IEnumerableExtenions\n{\n public static IEnumerable<T> UnionIfNotNull<T>(this IEnumerable<T> list1, IEnumerable<T> list2)\n {\n if (list1 != null && list2 != null)\n return list1.Union(list2);\n else if (list1 != null)\n return list1;\n else if (list2 != null)\n return list2;\n else return null;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 49230902,
"author": "Simon_Weaver",
"author_id": 16940,
"author_profile": "https://Stackoverflow.com/users/16940",
"pm_score": 2,
"selected": false,
"text": "<p>I needed a solution to combine an unknown number of arrays.</p>\n\n<p>Surprised nobody else provided a solution using <code>SelectMany</code> with <code>params</code>. </p>\n\n<pre><code> private static T[] Combine<T>(params IEnumerable<T>[] items) =>\n items.SelectMany(i => i).Distinct().ToArray();\n</code></pre>\n\n<p>If you don't want distinct items just remove distinct.</p>\n\n<pre><code> public string[] Reds = new [] { \"Red\", \"Crimson\", \"TrafficLightRed\" };\n public string[] Greens = new [] { \"Green\", \"LimeGreen\" };\n public string[] Blues = new [] { \"Blue\", \"SkyBlue\", \"Navy\" };\n\n public string[] Colors = Combine(Reds, Greens, Blues);\n</code></pre>\n\n<p>Note: There is definitely no guarantee of ordering when using distinct.</p>\n"
},
{
"answer_id": 55578088,
"author": "cj.burrow",
"author_id": 6580072,
"author_profile": "https://Stackoverflow.com/users/6580072",
"pm_score": 3,
"selected": false,
"text": "<p>This is what I came up with. Works for a variable number of arrays. </p>\n\n<pre><code>public static T[] ConcatArrays<T>(params T[][] args)\n {\n if (args == null)\n throw new ArgumentNullException();\n\n var offset = 0;\n var newLength = args.Sum(arr => arr.Length); \n var newArray = new T[newLength];\n\n foreach (var arr in args)\n {\n Buffer.BlockCopy(arr, 0, newArray, offset, arr.Length);\n offset += arr.Length;\n }\n\n return newArray;\n }\n</code></pre>\n\n<p>... </p>\n\n<pre><code>var header = new byte[] { 0, 1, 2};\nvar data = new byte[] { 3, 4, 5, 6 };\nvar checksum = new byte[] {7, 0};\nvar newArray = ConcatArrays(header, data, checksum);\n//output byte[9] { 0, 1, 2, 3, 4, 5, 6, 7, 0 }\n</code></pre>\n"
},
{
"answer_id": 59576666,
"author": "schoetbi",
"author_id": 108238,
"author_profile": "https://Stackoverflow.com/users/108238",
"pm_score": 2,
"selected": false,
"text": "<p>If you have the source arrays in an array itself you can use <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.selectmany?view=netframework-4.8\" rel=\"nofollow noreferrer\">SelectMany</a>:</p>\n\n<pre><code>var arrays = new[]{new[]{1, 2, 3}, new[]{4, 5, 6}};\nvar combined = arrays.SelectMany(a => a).ToArray();\nforeach (var v in combined) Console.WriteLine(v); \n</code></pre>\n\n<p>gives</p>\n\n<pre><code>1\n2\n3\n4\n5\n6\n</code></pre>\n\n<p>Probably this is not the fastest method but might fit depending on usecase.</p>\n"
},
{
"answer_id": 66751270,
"author": "Dmitry Shashurov",
"author_id": 4309436,
"author_profile": "https://Stackoverflow.com/users/4309436",
"pm_score": -1,
"selected": false,
"text": "<p>Simple code to join multiple arrays:</p>\n<pre><code>string[] arr1 = ...\nstring[] arr2 = ...\nstring[] arr3 = ... \nList<string> arr = new List<string>(arr1.Length + arr2.Length + arr3.Length);\narr.AddRange(arr1);\narr.AddRange(arr2);\narr.AddRange(arr3);\nstring[] result = arr.ToArray();\n</code></pre>\n"
},
{
"answer_id": 67243561,
"author": "Mondonno",
"author_id": 11824362,
"author_profile": "https://Stackoverflow.com/users/11824362",
"pm_score": -1,
"selected": false,
"text": "<p>This is another way to do this :)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static void ArrayPush<T>(ref T[] table, object value)\n{\n Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)\n table.SetValue(value, table.Length - 1); // Setting the value for the new element\n}\n\npublic static void MergeArrays<T>(ref T[] tableOne, T[] tableTwo) {\n foreach(var element in tableTwo) {\n ArrayPush(ref tableOne, element);\n }\n}\n</code></pre>\n<p>Here is the <a href=\"https://dotnetfiddle.net/5B5Oyj\" rel=\"nofollow noreferrer\">snippet/example</a></p>\n"
},
{
"answer_id": 68940225,
"author": "Harjeet Singh",
"author_id": 4960384,
"author_profile": "https://Stackoverflow.com/users/4960384",
"pm_score": 0,
"selected": false,
"text": "<pre><code>string[] names1 = new string[] { "Ava", "Emma", "Olivia" };\nstring[] names2 = new string[] { "Olivia", "Sophia", "Emma" };\nList<string> arr = new List<string>(names1.Length + names2.Length);\narr.AddRange(names1);\narr.AddRange(names2);\nstring[] result = arr.Distinct().ToArray();\nforeach(string str in result)\n{\n Console.WriteLine(str.ToString());\n}\n\nConsole.ReadLine();\n</code></pre>\n"
},
{
"answer_id": 74140785,
"author": "ArrayFormula",
"author_id": 13501781,
"author_profile": "https://Stackoverflow.com/users/13501781",
"pm_score": 0,
"selected": false,
"text": "<p>I wanted to find an approach without using any libraries or functionality beyond arrays themselves.</p>\n<p>The first two examples are mostly for reading the logic from scratch, but I also wonder if there could be performance variations depending on the sitaution.</p>\n<p>The third example is the most practical choice.</p>\n<pre><code>// Two for-loops\nprivate static int[] MergedArrays_1(int[] a, int[] b)\n{\n int[] result = new int[a.Length + b.Length];\n for (int i = 0; i < a.Length; i++)\n {\n result[i] = a[i];\n }\n for (int i = a.Length; i < result.Length; i++)\n {\n result[i] = b[i - a.Length];\n }\n return result;\n}\n\n// One for-loop\nprivate static int[] MergedArrays_2(int[] a, int[] b)\n{\n int[] results = new int[a.Length + b.Length];\n for (int i = 0; i < results.Length; i++)\n {\n results[i] = (i < a.Length) ? a[i] : b[i - a.Length];\n }\n return results;\n}\n\n// Array Method\nprivate static int[] MergedArrays_3(int[] a, int[] b)\n{\n int[] results = new int[a.Length + b.Length];\n a.CopyTo(results, 0);\n b.CopyTo(results, a.Length);\n return results;\n}\n</code></pre>\n<p>Lastly, I made a fourth example, that can merge multiple arrays, using the params keyword.</p>\n<pre><code>int[] result = MultipleMergedArrays(arrayOne, arrayTwo, arrayThree);\n</code></pre>\n<pre><code>private static int[] MultipleMergedArrays(params int[][] a)\n{\n // Get Length\n int resultsLength = 0;\n for (int row = 0; row < a.GetLength(0); row++)\n {\n resultsLength += a.Length;\n }\n\n // Initialize\n int[] results = new int[resultsLength];\n\n // Add Items\n int index = 0;\n for (int row = 0; row < a.GetLength(0); row++)\n {\n a[row].CopyTo(results, index);\n index += a[row].Length;\n }\n return results;\n}\n</code></pre>\n<p>The way it works when using params, is that the single-dimension arrays are passed into a jagged array.</p>\n<p>GetLength(0) returns the number of arrays contained within the jagged array.</p>\n<p>The code first counts the Length of all the arrays, then it initializes a new array based on that size, and starts adding entire arrays into the new results array by using the CopyTo() method, while adding the Length of each added array to an index counter.</p>\n<p>PS: Some times it is necessary to remove empty items, or certain items, from arrays when merging.</p>\n<pre><code>private static int[] RemoveEmpty(int[] array)\n{\n int count = 0;\n for (int i = 0; i < array.Length; i++)\n {\n if (array[i] == 0) count++;\n }\n\n int[] result = new int[array.Length - count];\n\n count = 0;\n for (int i = 0; i < array.Length; i++)\n {\n if (array[i] == 0) continue;\n result[count] = array[i];\n count++;\n }\n\n return result;\n}\n</code></pre>\n<p>This function can be combined with the ones above.</p>\n<p>It takes an array, counts the number of items that match zero. And creates a new array of the proper size. Then the counter is recycled and used as an index, for where to put place the input array's values into the new and smaller result array.\nWhen an item matches zero, it skips the rest of the code in that round of the loop, and continues with the next round, without incrementing the integer counter.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3058/"
]
| Is there a built in function in .NET 2.0 that will take two arrays and merge them into one array?
The arrays are both of the same type. I'm getting these arrays from a widely used function within my code base and can't modify the function to return the data in a different format.
I'm looking to avoid writing my own function to accomplish this if possible. | If you can manipulate one of the arrays, you can resize it before performing the copy:
```
T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
int array1OriginalLength = array1.Length;
Array.Resize<T>(ref array1, array1OriginalLength + array2.Length);
Array.Copy(array2, 0, array1, array1OriginalLength, array2.Length);
```
Otherwise, you can make a new array
```
T[] array1 = getOneArray();
T[] array2 = getAnotherArray();
T[] newArray = new T[array1.Length + array2.Length];
Array.Copy(array1, newArray, array1.Length);
Array.Copy(array2, 0, newArray, array1.Length, array2.Length);
```
[More on available Array methods on MSDN](http://msdn.microsoft.com/en-us/library/system.array.aspx). |
59,220 | <p>I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.</p>
<p>What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.</p>
<p>As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.</p>
<p>What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:</p>
<pre><code>String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
</code></pre>
<p>That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:</p>
<pre><code>AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
</code></pre>
<p>That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.</p>
<p>So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.</p>
<p>I know that tools like Reflector do this, I just can't find the syntax for getting at it. </p>
| [
{
"answer_id": 59243,
"author": "Kent Boogaart",
"author_id": 5380,
"author_profile": "https://Stackoverflow.com/users/5380",
"pm_score": 5,
"selected": true,
"text": "<p>Couple of options here:</p>\n\n<ol>\n<li>Attach to <code>AppDomain.AssemblyResolve</code> and do another <code>LoadFile</code> based on the requested assembly.</li>\n<li>Spin up another <code>AppDomain</code> with the directory as its base and load the assemblies in that <code>AppDomain</code>.</li>\n</ol>\n\n<p>I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see <code>Assembly.ReflectionOnlyLoad</code>).</p>\n"
},
{
"answer_id": 37060921,
"author": "mathume",
"author_id": 400694,
"author_profile": "https://Stackoverflow.com/users/400694",
"pm_score": 3,
"selected": false,
"text": "<p>I worked out <a href=\"https://stackoverflow.com/users/5380/kent-boogaart\">Kent Boogaart</a>'s second option.\nEssentially I had to:</p>\n\n<p>1.) Implement the <code>ResolveEventHandler</code> in a separate class, inheriting from <code>MarshalByRefObject</code> and adding the <code>Serializable</code> attribute.</p>\n\n<p>2.) Add the current <code>ApplicationBase</code>, essentially where the event handler's dll is, to the <code>AppDomain</code> <code>PrivateBinPath</code>.</p>\n\n<p>You can find the code on <a href=\"https://github.com/mathume/ResolveDependencies\" rel=\"nofollow noreferrer\">github</a>.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59220",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
]
| I'm writing a utility for myself, partly as an exercise in learning C# Reflection and partly because I actually want the resulting tool for my own use.
What I'm after is basically pointing the application at an assembly and choosing a given class from which to select properties that should be included in an exported HTML form as fields. That form will be then used in my ASP.NET MVC app as the beginning of a View.
As I'm using Subsonic objects for the applications where I want to use, this should be reasonable and I figured that, by wanting to include things like differing output HTML depending on data type, Reflection was the way to get this done.
What I'm looking for, however, seems to be elusive. I'm trying to take the DLL/EXE that's chosen through the OpenFileDialog as the starting point and load it:
```
String FilePath = Path.GetDirectoryName(FileName);
System.Reflection.Assembly o = System.Reflection.Assembly.LoadFile(FileName);
```
That works fine, but because Subsonic-generated objects actually are full of object types that are defined in Subsonic.dll, etc., those dependent objects aren't loaded. Enter:
```
AssemblyName[] ReferencedAssemblies = o.GetReferencedAssemblies();
```
That, too, contains exactly what I would expect it to. However, what I'm trying to figure out is how to load those assemblies so that my digging into my objects will work properly. I understand that if those assemblies were in the GAC or in the directory of the running executable, I could just load them by their name, but that isn't likely to be the case for this use case and it's my primary use case.
So, what it boils down to is how do I load a given assembly and all of its arbitrary assemblies starting with a filename and resulting in a completely Reflection-browsable tree of types, properties, methods, etc.
I know that tools like Reflector do this, I just can't find the syntax for getting at it. | Couple of options here:
1. Attach to `AppDomain.AssemblyResolve` and do another `LoadFile` based on the requested assembly.
2. Spin up another `AppDomain` with the directory as its base and load the assemblies in that `AppDomain`.
I'd highly recommend pursuing option 2, since that will likely be cleaner and allow you to unload all those assemblies after. Also, consider loading assemblies in the reflection-only context if you only need to reflect over them (see `Assembly.ReflectionOnlyLoad`). |
59,232 | <p>What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?</p>
<p>For example: I have a <code>JOBS</code> table with the column <code>JOB_NUMBER</code>. How can I find out if I have any duplicate <code>JOB_NUMBER</code>s, and how many times they're duplicated?</p>
| [
{
"answer_id": 59242,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 10,
"selected": true,
"text": "<p>Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time.</p>\n<pre><code>SELECT column_name, COUNT(column_name)\nFROM table_name\nGROUP BY column_name\nHAVING COUNT(column_name) > 1;\n</code></pre>\n"
},
{
"answer_id": 59254,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 5,
"selected": false,
"text": "<p>Simplest I can think of:</p>\n\n<pre><code>select job_number, count(*)\nfrom jobs\ngroup by job_number\nhaving count(*) > 1;\n</code></pre>\n"
},
{
"answer_id": 59261,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 3,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>SELECT <column>, count(*)\nFROM <table>\nGROUP BY <column> HAVING COUNT(*) > 1;\n</code></pre>\n\n<p>To answer the example above, it would look like:</p>\n\n<pre><code>SELECT job_number, count(*)\nFROM jobs\nGROUP BY job_number HAVING COUNT(*) > 1;\n</code></pre>\n"
},
{
"answer_id": 59278,
"author": "agnul",
"author_id": 6069,
"author_profile": "https://Stackoverflow.com/users/6069",
"pm_score": 2,
"selected": false,
"text": "<p>Doing</p>\n\n<pre><code>select count(j1.job_number), j1.job_number, j1.id, j2.id\nfrom jobs j1 join jobs j2 on (j1.job_numer = j2.job_number)\nwhere j1.id != j2.id\ngroup by j1.job_number\n</code></pre>\n\n<p>will give you the duplicated rows' ids.</p>\n"
},
{
"answer_id": 60437,
"author": "Grrey",
"author_id": 6155,
"author_profile": "https://Stackoverflow.com/users/6155",
"pm_score": 6,
"selected": false,
"text": "<p>Another way:</p>\n\n<pre><code>SELECT *\nFROM TABLE A\nWHERE EXISTS (\n SELECT 1 FROM TABLE\n WHERE COLUMN_NAME = A.COLUMN_NAME\n AND ROWID < A.ROWID\n)\n</code></pre>\n\n<p>Works fine (quick enough) when there is index on <code>column_name</code>. And it's better way to delete or update duplicate rows.</p>\n"
},
{
"answer_id": 60584,
"author": "Evan",
"author_id": 6277,
"author_profile": "https://Stackoverflow.com/users/6277",
"pm_score": 4,
"selected": false,
"text": "<p>You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.</p>\n\n<pre><code>SELECT column_name\nFROM table\nGROUP BY column_name\nHAVING COUNT(*) > 1\n</code></pre>\n"
},
{
"answer_id": 12507836,
"author": "Jitendra Vispute",
"author_id": 772712,
"author_profile": "https://Stackoverflow.com/users/772712",
"pm_score": 3,
"selected": false,
"text": "<p>In case where multiple columns identify unique row (e.g relations table ) there you can use following </p>\n\n<p>Use row id \n e.g. emp_dept(empid, deptid, startdate, enddate)\n suppose empid and deptid are unique and identify row in that case</p>\n\n<pre><code>select oed.empid, count(oed.empid) \nfrom emp_dept oed \nwhere exists ( select * \n from emp_dept ied \n where oed.rowid <> ied.rowid and \n ied.empid = oed.empid and \n ied.deptid = oed.deptid ) \n group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);\n</code></pre>\n\n<p>and if such table has primary key then use primary key instead of rowid, e.g id is pk then</p>\n\n<pre><code>select oed.empid, count(oed.empid) \nfrom emp_dept oed \nwhere exists ( select * \n from emp_dept ied \n where oed.id <> ied.id and \n ied.empid = oed.empid and \n ied.deptid = oed.deptid ) \n group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);\n</code></pre>\n"
},
{
"answer_id": 15827573,
"author": "Wahid Haidari",
"author_id": 2247937,
"author_profile": "https://Stackoverflow.com/users/2247937",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT SocialSecurity_Number, Count(*) no_of_rows\nFROM SocialSecurity \nGROUP BY SocialSecurity_Number\nHAVING Count(*) > 1\nOrder by Count(*) desc \n</code></pre>\n"
},
{
"answer_id": 35039925,
"author": "Stacker",
"author_id": 1348805,
"author_profile": "https://Stackoverflow.com/users/1348805",
"pm_score": -1,
"selected": false,
"text": "<p>Also u can try something like this to list all duplicate values in a table say reqitem</p>\n\n<pre><code>SELECT count(poid) \nFROM poitem \nWHERE poid = 50 \nAND rownum < any (SELECT count(*) FROM poitem WHERE poid = 50) \nGROUP BY poid \nMINUS\nSELECT count(poid) \nFROM poitem \nWHERE poid in (50)\nGROUP BY poid \nHAVING count(poid) > 1;\n</code></pre>\n"
},
{
"answer_id": 35312175,
"author": "DoOrDie",
"author_id": 5726548,
"author_profile": "https://Stackoverflow.com/users/5726548",
"pm_score": 0,
"selected": false,
"text": "<p><strong>1. solution</strong></p>\n\n<pre><code>select * from emp\n where rowid not in\n (select max(rowid) from emp group by empno);\n</code></pre>\n"
},
{
"answer_id": 46905493,
"author": "J. Chomel",
"author_id": 6019417,
"author_profile": "https://Stackoverflow.com/users/6019417",
"pm_score": 2,
"selected": false,
"text": "<p>I usually use <a href=\"https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions001.htm#i81407\" rel=\"nofollow noreferrer\">Oracle Analytic</a> function <a href=\"http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions137.htm#i86310\" rel=\"nofollow noreferrer\">ROW_NUMBER()</a>.</p>\n<p>Say you want to check the duplicates you have regarding a unique index or primary key built on columns (<code>c1</code>, <code>c2</code>, <code>c3</code>).\nThen you will go this way, bringing up <strong><code>ROWID</code></strong> s of rows where the number of lines brought by <code>ROW_NUMBER()</code> is <code>>1</code>:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>Select *\nFrom Table_With_Duplicates\nWhere Rowid In (Select Rowid\n From (Select ROW_NUMBER() Over (\n Partition By c1, c2, c3\n Order By c1, c2, c3\n ) nbLines\n From Table_With_Duplicates) t2\n Where nbLines > 1)\n</code></pre>\n"
},
{
"answer_id": 48224922,
"author": "Chaminda Dilshan",
"author_id": 9166453,
"author_profile": "https://Stackoverflow.com/users/9166453",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an SQL request to do that:</p>\n\n<pre><code>select column_name, count(1)\nfrom table\ngroup by column_name\nhaving count (column_name) > 1;\n</code></pre>\n"
},
{
"answer_id": 51474054,
"author": "Parth Kansara",
"author_id": 9952631,
"author_profile": "https://Stackoverflow.com/users/9952631",
"pm_score": 2,
"selected": false,
"text": "<p>I know its an old thread but this may help some one.</p>\n\n<p>If you need to print other columns of the table while checking for duplicate use below:</p>\n\n<pre><code>select * from table where column_name in\n(select ing.column_name from table ing group by ing.column_name having count(*) > 1)\norder by column_name desc;\n</code></pre>\n\n<p>also can add some additional filters in the where clause if needed.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
]
| What's the simplest SQL statement that will return the duplicate values for a given column and the count of their occurrences in an Oracle database table?
For example: I have a `JOBS` table with the column `JOB_NUMBER`. How can I find out if I have any duplicate `JOB_NUMBER`s, and how many times they're duplicated? | Aggregate the column by COUNT, then use a HAVING clause to find values that appear greater than one time.
```
SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
HAVING COUNT(column_name) > 1;
``` |
59,267 | <p>Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported.</p>
<p>The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases.</p>
| [
{
"answer_id": 59271,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "<p>Just write <code><input type=\"button\" ... /></code> into your html. There's nothing special at all with the html controls.</p>\n"
},
{
"answer_id": 59286,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": -1,
"selected": false,
"text": "<p><code><asp:Button></code> is the ASP.NET equivalent to the HTML.Button. It will by default generate an <code><input type=\"button\"></code>. (This is the System.Web.UI.WebControls.Button class)</p>\n"
},
{
"answer_id": 59316,
"author": "Graviton",
"author_id": 3834,
"author_profile": "https://Stackoverflow.com/users/3834",
"pm_score": 5,
"selected": true,
"text": "<p>I figured it out. It goes something like this:</p>\n\n<pre><code><form method=\"post\" action=\"<%= Html.AttributeEncode(Url.Action(\"CastUpVote\")) %>\">\n<input type=\"submit\" value=\"<%=ViewData.Model.UpVotes%> up votes\" />\n</form>\n</code></pre>\n"
},
{
"answer_id": 61433,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>Several of the extension methods got moved to Microsoft.Web.Mvc, which is the MVC Futures DLL. You might want to look there for things that have gone missing.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59267",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
]
| Starting from ASP.NET MVC Preview 3, HTML.Button ( and other related HTML controls) are no longer supported.
The question is, what is the equivalent for them? I've an app that was built using Preview 2, now I have to make it compatible with the latest CTP releases. | I figured it out. It goes something like this:
```
<form method="post" action="<%= Html.AttributeEncode(Url.Action("CastUpVote")) %>">
<input type="submit" value="<%=ViewData.Model.UpVotes%> up votes" />
</form>
``` |
59,280 | <p>I need to update a <code>combobox</code> with a new value so it changes the reflected text in it. The cleanest way to do this is after the <code>combobox</code>has been initialised and with a message.</p>
<p>So I am trying to craft a <code>postmessage</code> to the hwnd that contains the <code>combobox</code>.</p>
<p>So if I want to send a message to it, changing the currently selected item to the nth item, what would the <code>postmessage</code> look like?</p>
<p>I am guessing that it would involve <code>ON_CBN_SELCHANGE</code>, but I can't get it to work right.</p>
| [
{
"answer_id": 59317,
"author": "Simon Steele",
"author_id": 4591,
"author_profile": "https://Stackoverflow.com/users/4591",
"pm_score": 4,
"selected": true,
"text": "<p>You want <a href=\"http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx\" rel=\"nofollow noreferrer\">ComboBox_SetCurSel</a>:</p>\n\n<pre><code>ComboBox_SetCurSel(hWndCombo, n);\n</code></pre>\n\n<p>or if it's an MFC CComboBox control you can probably do:</p>\n\n<pre><code>m_combo.SetCurSel(2);\n</code></pre>\n\n<p>I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN_SELCHANGE is the notification that the control sends <em>back to you</em> when the selection is changed.</p>\n\n<p>Finally, you might want to add the c++ tag to this question.</p>\n"
},
{
"answer_id": 59350,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 1,
"selected": false,
"text": "<p>A concise version:</p>\n\n<pre><code>const int index = 0;\nm_comboBox.PostMessage(CBN_SELCHANGE, index);\n</code></pre>\n"
},
{
"answer_id": 98203,
"author": "jussij",
"author_id": 14738,
"author_profile": "https://Stackoverflow.com/users/14738",
"pm_score": 0,
"selected": false,
"text": "<p>What might be going wrong is the selection is being changed inside the selection change message handler, which result in another selection change message.</p>\n\n<p>One way to get around this <em>unwanted feedback loop</em> is to add a sentinel to the select change message handler as shown below:</p>\n\n<pre><code>void onSelectChangeHandler(HWND hwnd)\n{\n static bool fInsideSelectChange = 0;\n\n //-- ignore the change message if this function generated it\n if (fInsideSelectChange == 0)\n {\n //-- turn on the sentinel\n fInsideSelectChange = 1;\n\n //-- make the selection changes as required\n .....\n\n //-- we are done so turn off the sentinel\n fInsideSelectChange = 0;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 45231288,
"author": "serup",
"author_id": 3990012,
"author_profile": "https://Stackoverflow.com/users/3990012",
"pm_score": -1,
"selected": false,
"text": "<p>if you fx want to change the title - which is the line shown when combobox is closed, then you can do following:</p>\n\n<p>m_ComboBox.DeleteString(0); // first delete previous if any, 0 = visual string\nm_ComboBox.AddString(_T(\"Hello there\"));</p>\n\n<p>put this in fx. in OnCloseupCombo - when event close a dropdownbox fires </p>\n\n<pre><code>ON_CBN_CLOSEUP(IDC_COMBO1, OnCloseupCombo)\n</code></pre>\n\n<p>This change is a new string not a selection of already assigned combobox elements</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59280",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/342/"
]
| I need to update a `combobox` with a new value so it changes the reflected text in it. The cleanest way to do this is after the `combobox`has been initialised and with a message.
So I am trying to craft a `postmessage` to the hwnd that contains the `combobox`.
So if I want to send a message to it, changing the currently selected item to the nth item, what would the `postmessage` look like?
I am guessing that it would involve `ON_CBN_SELCHANGE`, but I can't get it to work right. | You want [ComboBox\_SetCurSel](http://msdn.microsoft.com/en-us/library/bb856484(VS.85).aspx):
```
ComboBox_SetCurSel(hWndCombo, n);
```
or if it's an MFC CComboBox control you can probably do:
```
m_combo.SetCurSel(2);
```
I would imagine if you're doing it manually you would also want SendMessage rather than PostMessage. CBN\_SELCHANGE is the notification that the control sends *back to you* when the selection is changed.
Finally, you might want to add the c++ tag to this question. |
59,294 | <p>I have the following query:</p>
<pre><code>select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
</code></pre>
<p>What would be the difference if I replaced all calls to <code>count(column_name)</code> to <code>count(*)</code>?</p>
<p>This question was inspired by <a href="https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle">How do I find duplicate values in a table in Oracle?</a>.</p>
<hr>
<p>To clarify the accepted answer (and maybe my question), replacing <code>count(column_name)</code> with <code>count(*)</code> would return an extra row in the result that contains a <code>null</code> and the count of <code>null</code> values in the column.</p>
| [
{
"answer_id": 59302,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 9,
"selected": true,
"text": "<p><code>count(*)</code> counts NULLs and <code>count(column)</code> does not</p>\n\n<p>[edit] added this code so that people can run it</p>\n\n<pre><code>create table #bla(id int,id2 int)\ninsert #bla values(null,null)\ninsert #bla values(1,null)\ninsert #bla values(null,1)\ninsert #bla values(1,null)\ninsert #bla values(null,1)\ninsert #bla values(1,null)\ninsert #bla values(null,null)\n\nselect count(*),count(id),count(id2)\nfrom #bla\n</code></pre>\n\n<p>results\n7 3 2</p>\n"
},
{
"answer_id": 59352,
"author": "Peter C",
"author_id": 1952,
"author_profile": "https://Stackoverflow.com/users/1952",
"pm_score": 4,
"selected": false,
"text": "<p>The explanation in the <a href=\"https://learn.microsoft.com/en-us/sql/t-sql/functions/count-transact-sql?view=sql-server-ver15\" rel=\"nofollow noreferrer\">docs</a>, helps to explain this:</p>\n<blockquote>\n<p>COUNT(*) returns the number of items in a group, including NULL values and duplicates.</p>\n<p>COUNT(expression) evaluates expression for each row in a group and returns the number of nonnull values.</p>\n</blockquote>\n<p>So count(*) includes nulls, the other method doesn't.</p>\n"
},
{
"answer_id": 59369,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 5,
"selected": false,
"text": "<p>Another minor difference, between using * and a specific column, is that in the column case you can add the keyword DISTINCT, and restrict the count to distinct values:</p>\n\n<pre><code>select column_a, count(distinct column_b)\nfrom table\ngroup by column_a\nhaving count(distinct column_b) > 1;\n</code></pre>\n"
},
{
"answer_id": 61089,
"author": "Alan",
"author_id": 5878,
"author_profile": "https://Stackoverflow.com/users/5878",
"pm_score": 4,
"selected": false,
"text": "<p>A further and perhaps subtle difference is that in some database implementations the count(*) is computed by looking at the indexes on the table in question rather than the actual data rows. Since no specific column is specified, there is no need to bother with the actual rows and their values (as there would be if you counted a specific column). Allowing the database to use the index data can be significantly faster than making it count \"real\" rows.</p>\n"
},
{
"answer_id": 3039334,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": false,
"text": "<p>We can use the <a href=\"https://data.stackexchange.com/\" rel=\"nofollow noreferrer\">Stack Exchange Data Explorer</a> to illustrate the difference with a simple query. The Users table in Stack Overflow's database has columns that are often left blank, like the user's Website URL.</p>\n\n<pre><code>-- count(column_name) vs. count(*)\n-- Illustrates the difference between counting a column\n-- that can hold null values, a 'not null' column, and count(*)\n\nselect count(WebsiteUrl), count(Id), count(*) from Users\n</code></pre>\n\n<p>If you run the query above in the <a href=\"https://data.stackexchange.com/stackoverflow/query/new\" rel=\"nofollow noreferrer\">Data Explorer</a>, you'll see that the count is the same for <code>count(Id)</code> and <code>count(*)</code>because the <code>Id</code> column doesn't allow <code>null</code> values. The <code>WebsiteUrl</code> count is much lower, though, because that column allows <code>null</code>.</p>\n"
},
{
"answer_id": 4925414,
"author": "Ali Adravi",
"author_id": 586227,
"author_profile": "https://Stackoverflow.com/users/586227",
"pm_score": -1,
"selected": false,
"text": "<p>It is best to use</p>\n\n<pre><code>Count(1) in place of column name or * \n</code></pre>\n\n<p>to count the number of rows in a table, it is faster than any format because it never go to check the column name into table exists or not</p>\n"
},
{
"answer_id": 9318012,
"author": "G21",
"author_id": 903005,
"author_profile": "https://Stackoverflow.com/users/903005",
"pm_score": 2,
"selected": false,
"text": "<ul>\n<li>The COUNT(*) sentence indicates SQL Server to return all the rows from a table, including NULLs. </li>\n<li>COUNT(column_name) just retrieves the rows having a non-null value on the rows.</li>\n</ul>\n\n<p>Please see following code for test executions SQL Server 2008:</p>\n\n<pre><code>-- Variable table\nDECLARE @Table TABLE\n(\n CustomerId int NULL \n , Name nvarchar(50) NULL\n)\n\n-- Insert some records for tests\nINSERT INTO @Table VALUES( NULL, 'Pedro')\nINSERT INTO @Table VALUES( 1, 'Juan')\nINSERT INTO @Table VALUES( 2, 'Pablo')\nINSERT INTO @Table VALUES( 3, 'Marcelo')\nINSERT INTO @Table VALUES( NULL, 'Leonardo')\nINSERT INTO @Table VALUES( 4, 'Ignacio')\n\n-- Get all the collumns by indicating *\nSELECT COUNT(*) AS 'AllRowsCount'\nFROM @Table\n\n-- Get only content columns ( exluce NULLs )\nSELECT COUNT(CustomerId) AS 'OnlyNotNullCounts'\nFROM @Table\n</code></pre>\n"
},
{
"answer_id": 12530297,
"author": "Hiren gardhariya",
"author_id": 1564949,
"author_profile": "https://Stackoverflow.com/users/1564949",
"pm_score": -1,
"selected": false,
"text": "<p>There is no difference if one column is fix in your table, if you want to use more than one column than you have to specify that how much columns you required to count......</p>\n\n<p>Thanks,</p>\n"
},
{
"answer_id": 16378822,
"author": "Ahmedul Kabir",
"author_id": 1685054,
"author_profile": "https://Stackoverflow.com/users/1685054",
"pm_score": 2,
"selected": false,
"text": "<p>Basically the <code>COUNT(*)</code> function return all the rows from a table whereas <code>COUNT(COLUMN_NAME)</code> does not; that is it excludes null values which everyone here have also answered here.\nBut the most interesting part is to make queries and database optimized it is better to use <code>COUNT(*)</code> unless doing multiple counts or a complex query rather than <code>COUNT(COLUMN_NAME)</code>. Otherwise, it will really lower your DB performance while dealing with a huge number of data. </p>\n"
},
{
"answer_id": 36987526,
"author": "Unna",
"author_id": 6083307,
"author_profile": "https://Stackoverflow.com/users/6083307",
"pm_score": -1,
"selected": false,
"text": "<p>As mentioned in the previous answers, <code>Count(*)</code> counts even the <code>NULL</code> columns, whereas <code>count(Columnname)</code> counts only if the column has values. </p>\n\n<p>It's always best practice to avoid <code>*</code> (<code>Select *</code>, <code>count *</code>, …) </p>\n"
},
{
"answer_id": 55327529,
"author": "Arun Solomon",
"author_id": 10654073,
"author_profile": "https://Stackoverflow.com/users/10654073",
"pm_score": 2,
"selected": false,
"text": "<p><code>COUNT(*)</code> – Returns the total number of records in a table (Including NULL valued records).</p>\n\n<p><code>COUNT(Column Name)</code> – Returns the total number of Non-NULL records. It means that, it ignores counting NULL valued records in that particular column.</p>\n"
},
{
"answer_id": 68799071,
"author": "Payel Senapati",
"author_id": 12118888,
"author_profile": "https://Stackoverflow.com/users/12118888",
"pm_score": 0,
"selected": false,
"text": "<p>Further elaborating upon the answer given by @SQLMeance and @Brannon making use of <code>GROUP BY</code> clause which has been mentioned by OP but not present in answer by @SQLMenace</p>\n<pre><code>CREATE TABLE table1 ( \nid INT \n);\n</code></pre>\n<pre><code>INSERT INTO table1 VALUES \n(1), \n(2), \n(NULL), \n(2), \n(NULL), \n(3), \n(1), \n(4), \n(NULL), \n(2);\n</code></pre>\n<pre><code>SELECT * FROM table1;\n</code></pre>\n<pre><code>+------+\n| id |\n+------+\n| 1 |\n| 2 |\n| NULL |\n| 2 |\n| NULL |\n| 3 |\n| 1 |\n| 4 |\n| NULL |\n| 2 |\n+------+\n10 rows in set (0.00 sec)\n</code></pre>\n<pre><code>SELECT id, COUNT(*) FROM table1 GROUP BY id;\n</code></pre>\n<pre><code>+------+----------+\n| id | COUNT(*) |\n+------+----------+\n| 1 | 2 |\n| 2 | 3 |\n| NULL | 3 |\n| 3 | 1 |\n| 4 | 1 |\n+------+----------+\n5 rows in set (0.00 sec)\n</code></pre>\n<p>Here, <code>COUNT(*)</code> counts the number of occurrences of each type of <code>id</code> including <code>NULL</code></p>\n<pre><code>SELECT id, COUNT(id) FROM table1 GROUP BY id;\n</code></pre>\n<pre><code>+------+-----------+\n| id | COUNT(id) |\n+------+-----------+\n| 1 | 2 |\n| 2 | 3 |\n| NULL | 0 |\n| 3 | 1 |\n| 4 | 1 |\n+------+-----------+\n5 rows in set (0.00 sec)\n</code></pre>\n<p>Here, <code>COUNT(id)</code> counts the number of occurrences of each type of <code>id</code> but does not count the number of occurrences of <code>NULL</code></p>\n<pre><code>SELECT id, COUNT(DISTINCT id) FROM table1 GROUP BY id;\n</code></pre>\n<pre><code>+------+--------------------+\n| id | COUNT(DISTINCT id) |\n+------+--------------------+\n| NULL | 0 |\n| 1 | 1 |\n| 2 | 1 |\n| 3 | 1 |\n| 4 | 1 |\n+------+--------------------+\n5 rows in set (0.00 sec)\n</code></pre>\n<p>Here, <code>COUNT(DISTINCT id)</code> counts the number of occurrences of each type of <code>id</code> only once (does not count duplicates) and also does not count the number of occurrences of <code>NULL</code></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59294",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
| I have the following query:
```
select column_name, count(column_name)
from table
group by column_name
having count(column_name) > 1;
```
What would be the difference if I replaced all calls to `count(column_name)` to `count(*)`?
This question was inspired by [How do I find duplicate values in a table in Oracle?](https://stackoverflow.com/questions/59232/how-do-i-find-duplicate-values-in-a-table-in-oracle).
---
To clarify the accepted answer (and maybe my question), replacing `count(column_name)` with `count(*)` would return an extra row in the result that contains a `null` and the count of `null` values in the column. | `count(*)` counts NULLs and `count(column)` does not
[edit] added this code so that people can run it
```
create table #bla(id int,id2 int)
insert #bla values(null,null)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,1)
insert #bla values(1,null)
insert #bla values(null,null)
select count(*),count(id),count(id2)
from #bla
```
results
7 3 2 |
59,309 | <p>What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.</p>
<p><img src="https://content.screencast.com/users/jessegavin/folders/Jing/media/ba5c2688-0aad-4e89-878a-8911946f8612/2008-09-12_1027.png" alt="alt text"></p>
| [
{
"answer_id": 59324,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 4,
"selected": false,
"text": "<p>This is something I have needed to do many times and a consistent solution still requires you add a little non-semantic markup and some browser specific hacks. When we get browser support for css 3 you'll get your vertical centering without sinning.</p>\n\n<p>For a better explanation of the technique you can look <a href=\"http://www.jakpsatweb.cz/css/css-vertical-center-solution.html\" rel=\"nofollow noreferrer\">the article I adapted it from</a>, but basically it involves adding an extra element and applying different styles in IE and browsers that support <code>position:table\\table-cell</code> on non-table elements.</p>\n\n<pre><code><div class=\"valign-outer\">\n <div class=\"valign-middle\">\n <div class=\"valign-inner\">\n Excuse me. What did you sleep in your clothes again last night. Really. You're gonna be in the car with her. Hey, not too early I sleep in on Saturday. Oh, McFly, your shoe's untied. Don't be so gullible, McFly. You got the place fixed up nice, McFly. I have you're car towed all the way to your house and all you've got for me is light beer. What are you looking at, butthead. Say hi to your mom for me.\n </div>\n </div>\n</div>\n\n<style>\n /* Non-structural styling */\n .valign-outer { height: 400px; border: 1px solid red; }\n .valign-inner { border: 1px solid blue; }\n</style>\n\n<!--[if lte IE 7]>\n<style>\n /* For IE7 and earlier */\n .valign-outer { position: relative; overflow: hidden; }\n .valign-middle { position: absolute; top: 50%; }\n .valign-inner { position: relative; top: -50% }\n</style>\n<![endif]-->\n<!--[if gt IE 7]> -->\n<style>\n /* For other browsers */\n .valign-outer { position: static; display: table; overflow: hidden; }\n .valign-middle { position: static; display: table-cell; vertical-align: middle; width: 100%; }\n</style>\n</code></pre>\n\n<p>There are many ways (hacks) to apply styles in specific sets of browsers. I used conditional comments but look at the article linked above to see two other techniques.</p>\n\n<p><em>Note: There are simple ways to get vertical centering if you know some heights in advance, if you are trying to center a single line of text, or in several other cases. If you have more details then throw them in because there may be a method that doesn't require browser hacks or non-semantic markup.</em></p>\n\n<p><strong>Update:</strong> We are beginning to get better browser support for CSS3, bringing both flex-box and transforms as alternative methods for getting vertical centering (among other effects). See <a href=\"https://stackoverflow.com/questions/5412912/align-vertically-using-css-3\">this other question</a> for more information about modern methods, but keep in mind that browser support is still sketchy for CSS3.</p>\n"
},
{
"answer_id": 13075912,
"author": "Fadi",
"author_id": 856921,
"author_profile": "https://Stackoverflow.com/users/856921",
"pm_score": 7,
"selected": false,
"text": "<p>This seems to be the best solution I’ve found to this problem, as long as your browser supports the <code>::before</code> pseudo element: <a href=\"http://css-tricks.com/centering-in-the-unknown/\" rel=\"noreferrer\">CSS-Tricks: Centering in the Unknown</a>.</p>\n\n<p>It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the <code>display: table</code> method because <code>table</code> elements don’t obey the <code>max-height</code> property.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.block {\r\n height: 300px;\r\n text-align: center;\r\n background: #c0c0c0;\r\n border: #a0a0a0 solid 1px;\r\n margin: 20px;\r\n}\r\n\r\n.block::before {\r\n content: '';\r\n display: inline-block;\r\n height: 100%; \r\n vertical-align: middle;\r\n margin-right: -0.25em; /* Adjusts for spacing */\r\n\r\n /* For visualization \r\n background: #808080; width: 5px;\r\n */\r\n}\r\n\r\n.centered {\r\n display: inline-block;\r\n vertical-align: middle;\r\n width: 300px;\r\n padding: 10px 15px;\r\n border: #a0a0a0 solid 1px;\r\n background: #f5f5f5;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"block\">\r\n <div class=\"centered\">\r\n <h1>Some text</h1>\r\n <p>But he stole up to us again, and suddenly clapping his hand on my\r\n shoulder, said&mdash;\"Did ye see anything looking like men going\r\n towards that ship a while ago?\"</p>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 20434170,
"author": "dougli",
"author_id": 3076093,
"author_profile": "https://Stackoverflow.com/users/3076093",
"pm_score": 3,
"selected": false,
"text": "<p>Using the child selector, I've taken <a href=\"https://stackoverflow.com/questions/59309/how-to-vertically-center-content-with-variable-height-within-a-div/13075912#13075912\">Fadi's incredible answer</a> above and boiled it down to just one CSS rule that I can apply. Now all I have to do is add the <code>contentCentered</code> class name to elements I want to center:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.contentCentered {\r\n text-align: center;\r\n}\r\n\r\n.contentCentered::before {\r\n content: '';\r\n display: inline-block;\r\n height: 100%; \r\n vertical-align: middle;\r\n margin-right: -.25em; /* Adjusts for spacing */\r\n}\r\n\r\n.contentCentered > * {\r\n display: inline-block;\r\n vertical-align: middle;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"contentCentered\">\r\n <div>\r\n <h1>Some text</h1>\r\n <p>But he stole up to us again, and suddenly clapping his hand on my\r\n shoulder, said&mdash;\"Did ye see anything looking like men going\r\n towards that ship a while ago?\"</p>\r\n </div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Forked CodePen: <a href=\"http://codepen.io/dougli/pen/Eeysg\" rel=\"nofollow noreferrer\">http://codepen.io/dougli/pen/Eeysg</a></p>\n"
},
{
"answer_id": 26125596,
"author": "user3432605",
"author_id": 3432605,
"author_profile": "https://Stackoverflow.com/users/3432605",
"pm_score": 0,
"selected": false,
"text": "<p>This is my awesome solution for a <code>div</code> with a dynamic (percentaged) height.</p>\n\n<p><strong>CSS</strong></p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.vertical_placer{\n background:red;\n position:absolute; \n height:43%; \n width:100%;\n display: table;\n}\n\n.inner_placer{ \n display: table-cell;\n vertical-align: middle;\n text-align:center;\n}\n\n.inner_placer svg{\n position:relative;\n color:#fff;\n background:blue;\n width:30%;\n min-height:20px;\n max-height:60px;\n height:20%;\n}\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code><div class=\"footer\">\n <div class=\"vertical_placer\">\n <div class=\"inner_placer\">\n <svg> some Text here</svg>\n </div>\n </div>\n</div> \n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/hunter74/oosb3s8w/1/\" rel=\"nofollow\">Try this by yourself.</a></p>\n"
},
{
"answer_id": 27663253,
"author": "BlackCetha",
"author_id": 4396938,
"author_profile": "https://Stackoverflow.com/users/4396938",
"pm_score": 8,
"selected": true,
"text": "<p>Just add</p>\n\n<pre><code>position: relative;\ntop: 50%;\ntransform: translateY(-50%);\n</code></pre>\n\n<p>to the inner div.</p>\n\n<p>What it does is moving the inner div's top border to the half height of the outer div (<code>top: 50%;</code>) and then the inner div up by half its height (<code>transform: translateY(-50%)</code>). This will work with <code>position: absolute</code> or <code>relative</code>.</p>\n\n<p>Keep in mind that <code>transform</code> and <code>translate</code> have vendor prefixes which are not included for simplicity.</p>\n\n<p>Codepen: <a href=\"http://codepen.io/anon/pen/ZYprdb\" rel=\"noreferrer\">http://codepen.io/anon/pen/ZYprdb</a></p>\n"
},
{
"answer_id": 37294825,
"author": "Loïc G.",
"author_id": 953096,
"author_profile": "https://Stackoverflow.com/users/953096",
"pm_score": 2,
"selected": false,
"text": "<p>You can use margin auto. With flex, the div seems to be centered vertically too.</p>\n\n\n\n<pre class=\"lang-css prettyprint-override\"><code>body,\nhtml {\n height: 100%;\n margin: 0;\n}\n.site {\n height: 100%;\n display: flex;\n}\n.site .box {\n background: #0ff;\n max-width: 20vw;\n margin: auto;\n}\n</code></pre>\n\n<pre class=\"lang-html prettyprint-override\"><code><div class=\"site\">\n <div class=\"box\">\n <h1>blabla</h1>\n <p>blabla</p>\n <p>blablabla</p>\n <p>lbibdfvkdlvfdks</p>\n </div>\n</div>\n</code></pre>\n\n\n"
},
{
"answer_id": 40712796,
"author": "Leo Dimuccio",
"author_id": 7187602,
"author_profile": "https://Stackoverflow.com/users/7187602",
"pm_score": 2,
"selected": false,
"text": "<p>Best result for me so far: </p>\n\n<p>div to be centered:</p>\n\n<pre><code>position: absolute;\ntop: 50%;\ntransform: translateY(-50%);\nmargin: 0 auto;\nright: 0;\nleft: 0;\n</code></pre>\n"
},
{
"answer_id": 58139571,
"author": "Leandro Castro",
"author_id": 3594412,
"author_profile": "https://Stackoverflow.com/users/3594412",
"pm_score": 1,
"selected": false,
"text": "<p>For me the best way to do this is:</p>\n\n<pre><code>.container{\n position: relative;\n}\n\n.element{\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n}\n</code></pre>\n\n<p>The advantage is not having to make the height explicit</p>\n"
},
{
"answer_id": 61923425,
"author": "hassan yousefi",
"author_id": 12637216,
"author_profile": "https://Stackoverflow.com/users/12637216",
"pm_score": 4,
"selected": false,
"text": "<p>you can use flex display such as below code:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.example{\r\n background-color:red;\r\n height:90px;\r\n width:90px;\r\n display:flex;\r\n align-items:center; /*for vertically center*/\r\n justify-content:center; /*for horizontally center*/\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"example\">\r\n <h6>Some text</h6>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5651/"
]
| What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.
 | Just add
```
position: relative;
top: 50%;
transform: translateY(-50%);
```
to the inner div.
What it does is moving the inner div's top border to the half height of the outer div (`top: 50%;`) and then the inner div up by half its height (`transform: translateY(-50%)`). This will work with `position: absolute` or `relative`.
Keep in mind that `transform` and `translate` have vendor prefixes which are not included for simplicity.
Codepen: <http://codepen.io/anon/pen/ZYprdb> |
59,313 | <p>I remember watching a webcast from Mark Russinovich showing the sequence of keyboard keys for a user initiated kernel dump. Can somebody refresh my memory on the exact order of the keys.</p>
<p>Please note this is for XP.</p>
| [
{
"answer_id": 59358,
"author": "Darren Kopp",
"author_id": 77,
"author_profile": "https://Stackoverflow.com/users/77",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of any keyboard short cuts, but are you looking for like in task manager, when you right click on a process and select \"Create Dump\"?</p>\n"
},
{
"answer_id": 59372,
"author": "David Mohundro",
"author_id": 4570,
"author_profile": "https://Stackoverflow.com/users/4570",
"pm_score": 1,
"selected": false,
"text": "<p>As far as I know, the \"Create Dump\" command was only added to Task Manager in Vista. The only process I know of to do this is using the adplus VBScript that comes with <a href=\"http://www.microsoft.com/whdc/devtools/debugging/default.mspx\" rel=\"nofollow noreferrer\">Debugging Tools</a>. Short of hooking into dbghelp and programmatically doing it yourself.</p>\n"
},
{
"answer_id": 59383,
"author": "apandit",
"author_id": 6128,
"author_profile": "https://Stackoverflow.com/users/6128",
"pm_score": 4,
"selected": true,
"text": "<p><a href=\"http://psacake.com/web/jr.asp\" rel=\"nofollow noreferrer\">http://psacake.com/web/jr.asp</a> contains full instructions, and here's an excerpt:</p>\n\n<pre>\nWhile it may seem odd to think about purposefully causing a Blue Screen Of Death (BSOD), Microsoft includes such a provision in Windows XP. This might come in handy for testing and troubleshooting your Startup And Recovery settings, Event logging, and for demonstration purposes.\n\nHere's how to create a BSOD:\n\nLaunch the Registry Editor (Regedit.exe).\nGo to HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\i8042prt\\Parameters.\nGo to Edit, select New | DWORD Value and name the new value CrashOnCtrlScroll.\nDouble-click the CrashOnCtrlScroll DWORD Value, type 1 in the Value Data textbox, and click OK.\nClose the Registry Editor and restart Windows XP.\nWhen you want to cause a BSOD, press and hold down the [Ctrl] key on the right side of your keyboard, and then tap the [ScrollLock] key twice. Now you should see the BSOD.\n\nIf your system reboots instead of displaying the BSOD, you'll have to disable the Automatically\nRestart setting in the System Properties dialog box. To do so, follow these steps:\n\nPress [Windows]-Break.\nSelect the Advanced tab.\nClick the Settings button in the Startup And Recovery panel.\nClear the Automatically Restart check box in the System Failure panel.\nClick OK twice.\n\nHere's how you remove the BSOD configuration:\n\nLaunch the Registry Editor (Regedit.exe).\nGo to HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\i8042prt\\Parameters.\nSelect the CrashOnCtrlScroll value, pull down the Edit menu, and select the Delete command.\nClose the Registry Editor and restart Windows XP.\nNote: Editing the registry is risky, so make sure you have a verified backup before making any changes. \n</pre>\n\n<p>And I may be wrong in assuming you want BSOD, so this is a Microsoft Page showing how to capture kernel dumps:\n<a href=\"https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450\" rel=\"nofollow noreferrer\">https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450</a></p>\n"
},
{
"answer_id": 59393,
"author": "Jack Bolding",
"author_id": 5882,
"author_profile": "https://Stackoverflow.com/users/5882",
"pm_score": 1,
"selected": false,
"text": "<p>You can setup the <a href=\"http://support.microsoft.com/kb/241215\" rel=\"nofollow noreferrer\">user dump tool</a> from Microsoft with hot keys to dump a process. However, this is a user process dump, not a kernel dump... </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59313",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4337/"
]
| I remember watching a webcast from Mark Russinovich showing the sequence of keyboard keys for a user initiated kernel dump. Can somebody refresh my memory on the exact order of the keys.
Please note this is for XP. | <http://psacake.com/web/jr.asp> contains full instructions, and here's an excerpt:
```
While it may seem odd to think about purposefully causing a Blue Screen Of Death (BSOD), Microsoft includes such a provision in Windows XP. This might come in handy for testing and troubleshooting your Startup And Recovery settings, Event logging, and for demonstration purposes.
Here's how to create a BSOD:
Launch the Registry Editor (Regedit.exe).
Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters.
Go to Edit, select New | DWORD Value and name the new value CrashOnCtrlScroll.
Double-click the CrashOnCtrlScroll DWORD Value, type 1 in the Value Data textbox, and click OK.
Close the Registry Editor and restart Windows XP.
When you want to cause a BSOD, press and hold down the [Ctrl] key on the right side of your keyboard, and then tap the [ScrollLock] key twice. Now you should see the BSOD.
If your system reboots instead of displaying the BSOD, you'll have to disable the Automatically
Restart setting in the System Properties dialog box. To do so, follow these steps:
Press [Windows]-Break.
Select the Advanced tab.
Click the Settings button in the Startup And Recovery panel.
Clear the Automatically Restart check box in the System Failure panel.
Click OK twice.
Here's how you remove the BSOD configuration:
Launch the Registry Editor (Regedit.exe).
Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\i8042prt\Parameters.
Select the CrashOnCtrlScroll value, pull down the Edit menu, and select the Delete command.
Close the Registry Editor and restart Windows XP.
Note: Editing the registry is risky, so make sure you have a verified backup before making any changes.
```
And I may be wrong in assuming you want BSOD, so this is a Microsoft Page showing how to capture kernel dumps:
<https://web.archive.org/web/20151014034039/https://support.microsoft.com/fr-ma/kb/316450> |
59,322 | <p>I have the following code:</p>
<pre><code>SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
</code></pre>
<p>Is there any difference to the results or performance if I replace the COUNT(*) with COUNT('x')?</p>
<p>(This question is related to a <a href="https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count">previous one</a>)</p>
| [
{
"answer_id": 59385,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "<p>The major performance difference is that COUNT(*) can be satisfied by examining the primary key on the table.</p>\n\n<p>i.e. in the simple case below, the query will return immediately, without needing to examine any rows.</p>\n\n<pre><code>select count(*) from table\n</code></pre>\n\n<p>I'm not sure if the query optimizer in SQL Server will do so, but in the example above, if the column you are grouping on has an index the server should be able to satisfy the query without hitting the actual table at all.</p>\n\n<p>To clarify: this answer refers specifically to SQL Server. I don't know how other DBMS products handle this.</p>\n"
},
{
"answer_id": 59391,
"author": "NateSchneider",
"author_id": 5129,
"author_profile": "https://Stackoverflow.com/users/5129",
"pm_score": 2,
"selected": false,
"text": "<p>This question is slightly different that the other referenced. In the referenced question, it was asked what the difference was when using count(*) and count(SomeColumnName), and <a href=\"https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count#59302\">SQLMenace's answer</a> was spot on.</p>\n\n<p>To address this question, essentially there is no difference in the result. Both count(*) and count('x') and say count(1) will return the same number. The difference is that when using \" * \" just like in a SELECT all columns are returned, then counted. When a constant is used (e.g. 'x' or 1) then a row with one column is returned and then counted. The performance difference would be seen when \" * \" returns many columns.</p>\n\n<p><strong>Update</strong>: The above statement about performance is probably not quite right as discussed in other answers, but does apply to subselect queries when using EXISTS and NOT EXISTS</p>\n"
},
{
"answer_id": 59412,
"author": "Matt Rogish",
"author_id": 2590,
"author_profile": "https://Stackoverflow.com/users/2590",
"pm_score": 5,
"selected": true,
"text": "<p>To say that <code>SELECT COUNT(*) vs COUNT(1)</code> results in your DBMS returning \"columns\" is pure bunk. That <em>may</em> have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is <strong>NO</strong> performance difference between <code>SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation')</code></p>\n\n<p>Moreover, <code>SELECT(1) vs SELECT(*)</code> will NOT have any difference in INDEX usage -- most DBMS will actually optimize <code>SELECT( n ) into SELECT(*)</code> anyway. See the ASK TOM: Oracle has been optimizing <code>SELECT(n) into SELECT(*)</code> for the better part of a decade, if not longer:\n<a href=\"http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789\" rel=\"noreferrer\">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789</a></p>\n\n<blockquote>\n <p>problem is in count(col) to count(<em>)\n conversion\n <strong></em> **03/23/00</strong> 05:46 pm *** one workaround is to set event 10122 to\n turn off count(col) ->count(<em>)\n optimization. Another work around is\n to change the count(col) to count(</em>),\n it means the same, when the col has a\n NOT NULL constraint. The bug number is\n 1215372.</p>\n</blockquote>\n\n<p>One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise). </p>\n\n<p>Bottom line: if what you want is the count of rows in a table, use COUNT(*)</p>\n"
},
{
"answer_id": 59858,
"author": "Darryl Hein",
"author_id": 5441,
"author_profile": "https://Stackoverflow.com/users/5441",
"pm_score": 1,
"selected": false,
"text": "<p>MySQL: According to the MySQL website, <code>COUNT(*)</code> is faster for single table queries when using MyISAM:</p>\n\n<p><a href=\"http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_count</a></p>\n\n<p>I'm guessing with a having clause with a count in it may change things.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
]
| I have the following code:
```
SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
```
Is there any difference to the results or performance if I replace the COUNT(\*) with COUNT('x')?
(This question is related to a [previous one](https://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count)) | To say that `SELECT COUNT(*) vs COUNT(1)` results in your DBMS returning "columns" is pure bunk. That *may* have been the case long, long ago but any self-respecting query optimizer will choose some fast method to count the rows in the table - there is **NO** performance difference between `SELECT COUNT(*), COUNT(1), COUNT('this is a silly conversation')`
Moreover, `SELECT(1) vs SELECT(*)` will NOT have any difference in INDEX usage -- most DBMS will actually optimize `SELECT( n ) into SELECT(*)` anyway. See the ASK TOM: Oracle has been optimizing `SELECT(n) into SELECT(*)` for the better part of a decade, if not longer:
<http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1156151916789>
>
> problem is in count(col) to count(*)
> conversion* \*\*03/23/00 05:46 pm \*\*\* one workaround is to set event 10122 to
> turn off count(col) ->count(*)
> optimization. Another work around is
> to change the count(col) to count(*),
> it means the same, when the col has a
> NOT NULL constraint. The bug number is
> 1215372.
>
>
>
One thing to note - if you are using COUNT(col) (don't!) and col is marked NULL, then it will actually have to count the number of occurrences in the table (either via index scan, histogram, etc. if they exist, or a full table scan otherwise).
Bottom line: if what you want is the count of rows in a table, use COUNT(\*) |
59,331 | <p>Suppose I have <code>fileA.h</code> which declares a class <code>classA</code> with template function <code>SomeFunc<T>()</code>. This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of <code>SomeFunc()</code> (like for <code>SomeFunc<int>()</code>) in <code>fileA.C</code> (ie. not in the header file).</p>
<p>If I now call <code>SomeFunc<int>()</code> from some other code (maybe also from another library), would it call the generic version, or the specialization?</p>
<p>I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2.</p>
| [
{
"answer_id": 59359,
"author": "Brandon",
"author_id": 5959,
"author_profile": "https://Stackoverflow.com/users/5959",
"pm_score": 0,
"selected": false,
"text": "<p>Unless the specialized template function is also listed in the header file, the other application will have no knowledge of the specialized version. The solution is the add <code>SomeFunc<int>()</code> to the header as well.</p>\n"
},
{
"answer_id": 59361,
"author": "Serge",
"author_id": 1007,
"author_profile": "https://Stackoverflow.com/users/1007",
"pm_score": 3,
"selected": false,
"text": "<p>Have you added a prototype with parameters to your header file?</p>\n\n<p>I mean is there somewhere in fileA.h</p>\n\n<pre><code>template<> SomeFunc<int>();\n</code></pre>\n\n<p>If not that's probably the reason.</p>\n"
},
{
"answer_id": 59368,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 0,
"selected": false,
"text": "<p>Brandon: that's what I thought - the specialized function should never be called. Which is true for the second application I mentioned. The first app, however, clearly calls the specialized form even though the specialization is not declared in the header file!</p>\n\n<p>I mainly seek enlightenment here :-) because the first app is a unit test, and it's unfortunate to have a bug that doesn't appear in the test but in the real app...</p>\n\n<p>(PS: I have fixed this specific bug, indeed by declaring the specialization in the header; but what other similar bugs might still be hidden?)</p>\n"
},
{
"answer_id": 59394,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>Per the specs, your specialized function template should never be called outside <code>fileA.C</code>, unless you <code>export</code> the template definition, which no compiler (except Comeau) currently supports (or has it planned for the forseeable future).</p>\n\n<p>On the other hand, once the function template is instantiated, there is a function visible to the compiler that is no longer a template. GCC may re-use this definition across different compiler units because the standard states that each template shall only be instantiated once for a given set of type arguments [temp.spec]. Still, since the template is not exported, this should be limited to the compilation unit.</p>\n\n<p>I believe that GCC may expose a bug here in sharing its list of instantiated templates across compilation units. Normally, this is a reasonable optimization but it should take function specializations into account which it doesn't seem to do correctly.</p>\n"
},
{
"answer_id": 59409,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 1,
"selected": false,
"text": "<p>In Microsoft C++, I did an experiment with inline functions. I wanted to know what would happen if I defined incompatible versions of a function in different sources. I got different results depending on whether I was using a Debug build or a Release build. In Debug, the compiler refuses to inline anything, and the linker was linking the same version of the function no matter what was in scope in the source. In Release, the compiler inlined whichever version had been defined at the time, and you got differing versions of the function.</p>\n\n<p>In neither case were there any warnings. I kind of suspected this, which is why I did the experiment.</p>\n\n<p>I assume that template functions would behave the same, as would other compilers.</p>\n"
},
{
"answer_id": 59416,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 5,
"selected": false,
"text": "<p>It is <strong>an error</strong> to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is \"ill formed, no diagnostic required\").</p>\n\n<p>Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new \"extern template\" facility:</p>\n\n<pre><code>extern template<> SomeFunc<int>();\n</code></pre>\n\n<p>This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the <code>extern</code>.</p>\n"
},
{
"answer_id": 59458,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>@[anthony-williams],</p>\n\n<p>are you sure you're not confusing <code>extern</code> template declarations with <code>extern template</code> instantiations? From what I see, <code>extern template</code> may <em>only</em> be used for explicit instantiation, not for specialization (which implies implicit instantiation). [temp.expl.spec] doesn't mention the <code>extern</code> keyword:</p>\n\n<blockquote>\n <p><em>explicit-specialization</em>:<br>\n <code>template</code> < > <em>declaration</em></p>\n</blockquote>\n"
},
{
"answer_id": 787102,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I had the same problem with gcc4, here is how i solved it. It was more simple a solution than what i was lead to believe by previous comments. The previous posts ideas were correct but their syntax didn't work for me.</p>\n\n<pre><code>\n ----------header-----------------\n template < class A >\n void foobar(A& object)\n {\n std::cout << object;\n }\n\n template <> \n void foobar(int);\n\n ---------source------------------\n #include \"header.hpp\"\n\n template <>\n void foobar(int x)\n {\n std::cout << \"an int\";\n }\n\n</code></pre>\n"
},
{
"answer_id": 18742483,
"author": "CarLuva",
"author_id": 967077,
"author_profile": "https://Stackoverflow.com/users/967077",
"pm_score": 1,
"selected": false,
"text": "<p>As Anthony Williams says, the <code>extern template</code> construct is the correct way to do this, but since his sample code is incomplete and has multiple syntax errors, here's a complete solution.</p>\n\n<p>fileA.h:</p>\n\n<pre><code>namespace myNamespace {\n class classA {\n public:\n template <class T> void SomeFunc() { ... }\n };\n\n // The following line declares the specialization SomeFunc<int>().\n template <> void classA::SomeFunc<int>();\n\n // The following line externalizes the instantiation of the previously\n // declared specialization SomeFunc<int>(). If the preceding line is omitted,\n // the following line PREVENTS the specialization of SomeFunc<int>();\n // SomeFunc<int>() will not be usable unless it is manually instantiated\n // separately). When the preceding line is included, all the compilers I\n // tested this on, including gcc, behave exactly the same (throwing a link\n // error if the specialization of SomeFunc<int>() is not instantiated\n // separately), regardless of whether or not the following line is included;\n // however, my understanding is that nothing in the standard requires that\n // behavior if the following line is NOT included.\n extern template void classA::SomeFunc<int>();\n}\n</code></pre>\n\n<p>fileA.C:</p>\n\n<pre><code>#include \"fileA.h\"\n\ntemplate <> void myNamespace::classA::SomeFunc<int>() { ... }\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59331",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2148773/"
]
| Suppose I have `fileA.h` which declares a class `classA` with template function `SomeFunc<T>()`. This function is implemented directly in the header file (as is usual for template functions). Now I add a specialized implementation of `SomeFunc()` (like for `SomeFunc<int>()`) in `fileA.C` (ie. not in the header file).
If I now call `SomeFunc<int>()` from some other code (maybe also from another library), would it call the generic version, or the specialization?
I have this problem right now, where the class and function live in a library which is used by two applications. And one application correctly uses the specialization, while another app uses the generic form (which causes runtime problems later on). Why the difference? Could this be related to linker options etc? This is on Linux, with g++ 4.1.2. | It is **an error** to have a specialization for a template which is not visible at the point of call. Unfortunately, compilers are not required to diagnose this error, and can then do what they like with your code (in standardese it is "ill formed, no diagnostic required").
Technically, you need to define the specialization in the header file, but just about every compiler will handle this as you might expect: this is fixed in C++11 with the new "extern template" facility:
```
extern template<> SomeFunc<int>();
```
This explicitly declares that the particular specialization is defined elsewhere. Many compilers support this already, some with and some without the `extern`. |
59,380 | <p>I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my <code>index.php</code> (ex. <code>somecity.domain.com</code>). </p>
<p>Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. <code>blog.domain.com</code>).</p>
<p>My <code>.htaccess</code> currently reads:</p>
<pre><code>RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code></pre>
<p>Can I manipulate this <code>.htaccess</code> to achieve what I need? Can it be done through Apache?</p>
| [
{
"answer_id": 59382,
"author": "changelog",
"author_id": 5646,
"author_profile": "https://Stackoverflow.com/users/5646",
"pm_score": 0,
"selected": false,
"text": "<p>You'll have to configure apache for those static sub-domains. The \"catch-all\" site will be the default site configured, so that one will catch the other ones.</p>\n"
},
{
"answer_id": 59403,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure I understand completely what you need to accomplish, but it might helpful to setup virtual domains within your Apache configuration file. You can map them to folders on the drive with different applications installed. Each virtual domain is treated much like a root directory. I have my development environment setup locally on my Windows machine a lot like this:</p>\n\n<pre><code>NameVirtualHost *:80\n\n# Begin virtual host directives.\n\n<VirtualHost *:80>\n\n# myblog.com virtual host.\n\nServerAdmin [email protected]\nDocumentRoot \"c:/apache_www/myblog.com/www\"\nServerName myblog.com\nServerAlias *.myblog.com\nErrorLog \"c:/apache_www/myblog.com/logs/log\"\nScriptAlias /cgi-bin/ \"c:/apache_www/myblog.com/cgi-bin/\"\n\n<Directory \"c:/apache_www/myblog.com/www\">\n Options Indexes FollowSymLinks\n AllowOverride All\n Order allow,deny\n Allow from all\n</Directory>\n\n</VirtualHost>\n</code></pre>\n\n<p>If this does not help get you on the right track, then try researching the VirtualHost directive to come up with a solution. I find trying to do all this in an .htaccess to be cumbersome and difficult to manage.</p>\n"
},
{
"answer_id": 59405,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 1,
"selected": false,
"text": "<p>Your .htaccess does nothing useful, as Apache is probably configured with DirectoryIndex index.php. Well, it does move domain.com/a to domain.com/index.php, but I doubt that is what you want.</p>\n\n<p>Your wildcard virtualhost works because you probably have ServerAlias *.domain.com in your configuration, or a single virtualhost and DNS pointing to the address of your server. (When you have a single virtualhost, it shows up for any request, and the first listed virtualhost is the default one)</p>\n\n<p>You have to create new VirtualHosts for the static domains, leaving the default one as, well, the default one :)</p>\n\n<p>Check <a href=\"http://httpd.apache.org/docs/2.2/vhosts/examples.html\" rel=\"nofollow noreferrer\">these</a> <a href=\"http://wiki.apache.org/httpd/ExampleVhosts\" rel=\"nofollow noreferrer\">tutorials</a> that explain it all.</p>\n"
},
{
"answer_id": 59773,
"author": "SeanDowney",
"author_id": 5261,
"author_profile": "https://Stackoverflow.com/users/5261",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if you have cPanel installed on your host, but I was able to do this by adding a new subdomain <code>*</code> and then sending all that traffic to a particular subdomain, for example: <code>*.domain.com -> master.domain.com</code>. Then you can read out which URL you are at in master.domain.com and go from there.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6140/"
]
| I have a wildcard subdomain enabled and dynamically parse the URL by passing it as-is to my `index.php` (ex. `somecity.domain.com`).
Now, I wish to create a few subdomains that are static where I can install different application and not co-mingle with my current one (ex. `blog.domain.com`).
My `.htaccess` currently reads:
```
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
```
Can I manipulate this `.htaccess` to achieve what I need? Can it be done through Apache? | Your .htaccess does nothing useful, as Apache is probably configured with DirectoryIndex index.php. Well, it does move domain.com/a to domain.com/index.php, but I doubt that is what you want.
Your wildcard virtualhost works because you probably have ServerAlias \*.domain.com in your configuration, or a single virtualhost and DNS pointing to the address of your server. (When you have a single virtualhost, it shows up for any request, and the first listed virtualhost is the default one)
You have to create new VirtualHosts for the static domains, leaving the default one as, well, the default one :)
Check [these](http://httpd.apache.org/docs/2.2/vhosts/examples.html) [tutorials](http://wiki.apache.org/httpd/ExampleVhosts) that explain it all. |
59,390 | <p>In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?</p>
<p>Am I going to get myself into trouble if I change this:</p>
<pre><code><cfcomponent>
<cfset variables.foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #variables.foo# and #bar#.">
</cffunction>
</cfcomponent>
</code></pre>
<p>to this?</p>
<pre><code><cfcomponent>
<cfset foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #foo# and #bar#.">
</cffunction>
</cfcomponent>
</code></pre>
| [
{
"answer_id": 59554,
"author": "Soldarnal",
"author_id": 3420,
"author_profile": "https://Stackoverflow.com/users/3420",
"pm_score": 4,
"selected": true,
"text": "<p>It won't matter to specify \"variables\" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.</p>\n\n<pre><code><cfcomponent>\n <cfset foo = \"a private instance variable\">\n\n <cffunction name=\"doSomething\">\n <cfargument name=\"foo\" required=\"yes\"/>\n <cfset var bar = \"a function local variable\">\n <cfreturn \"I have #foo# and #bar#.\">\n </cffunction>\n\n <cffunction name=\"doAnotherThing\">\n <cfargument name=\"foo\" required=\"yes\"/>\n <cfset var bar = \"a function local variable\">\n <cfreturn \"I have #variables.foo# and #bar#.\">\n </cffunction>\n\n</cfcomponent>\n</code></pre>\n\n<p>doSomething(\"args\") returns \"I have <strong>args</strong> and a <strong>function local variable</strong>\"</p>\n\n<p>doAnotherThing(\"args\") returns \"I have <strong>a private instance of a variable</strong> and a <strong>function local variable</strong>.\"</p>\n"
},
{
"answer_id": 59566,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 2,
"selected": false,
"text": "<p>The short answer to your question is that no, you will probably not run into trouble attempting to do that. Outside the context of a UDF (even still inside a CFC), an un-scoped set statement implies the variables scope.</p>\n\n<p>In addition, in a CFC, the Variables scope is available to all of its functions; it is sort of the global scope within that CFC -- similar to the \"this\" scope, except variables scope is akin to \"private\" variables, whereas the this scope is akin to public variables.</p>\n\n<p>To test this, create test.cfc:</p>\n\n<pre><code><cfcomponent>\n <cfset foo = \"bar\" />\n <cffunction name=\"dumpit\" output=\"true\">\n <cfdump var=\"#variables#\" label=\"cfc variables scope\">\n <cfdump var=\"#this#\" label=\"cfc this scope\">\n </cffunction>\n</cfcomponent>\n</code></pre>\n\n<p>and a page to test it, test.cfm:</p>\n\n<pre><code><cfset createObject(\"component\", \"test\").dumpit() />\n</code></pre>\n\n<p>And the results will be:</p>\n\n<p><img src=\"https://i.stack.imgur.com/LSoL6.png\"/></p>\n\n<hr>\n\n<p>Now, to address another problem I see in your example code...</p>\n\n<p>In CF, all User Defined Functions have a special un-named scope commonly referred to as the \"var\" scope. If you do the following inside a UDF:</p>\n\n<pre><code><cfset foo = \"bar\" />\n</code></pre>\n\n<p>Then you are telling CF to put that variable into the var scope.</p>\n\n<p>To compound things a bit, you can run into problems (variable values changing when you weren't expecting them to) when you are <strong><em>not</em></strong> using the var scope in your inline UDFs.</p>\n\n<p>So the rule of thumb is to always, Always, ALWAYS, <strong><em>ALWAYS</em></strong> var-scope your function-internal variables (including query names). There is a tool called <a href=\"http://varscoper.riaforge.org/\" rel=\"nofollow noreferrer\">varScoper</a> that will assist you in finding variables that need to be var-scoped. Last I checked it wasn't perfect, but it's definitely a start.</p>\n\n<p>However, it is a <em>bad</em> idea to reference (display/use) variables without a scope (obviously excepting var-scoped variables, as you can't specify the scope to read from) in CFCs or even on your standard CFM pages. As of CF7, there were 9 scopes that were checked in a specific order when you read a variable without specifying the scope, first match wins. With CF8, there could be more scopes in that list, I haven't checked. When you do this, you run the risk of getting a value from one scope when you are expecting it from another; which is a nightmare to debug... I assure you. ;)</p>\n\n<p>So in short: <em>implying</em> a variable's scope (on set) is not a terrible idea (though I usually specify it anyway); but <em>inferring</em> variable's scope (on read) is asking for trouble.</p>\n"
},
{
"answer_id": 59891,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 0,
"selected": false,
"text": "<p>After reading your answers here's what I'm thinking:</p>\n\n<p><strong>Yes, it's safe. In general, it's not necessary or useful to explicitly specify the variables scope. It just adds clutter to an already verbose language.</strong></p>\n\n<p>Granted, there is one minor exception, as <a href=\"https://stackoverflow.com/users/3420/soldarnal\">Soldarnal</a> pointed out, where qualifying a variables-scoped variable is required. That is if you have a function local variable with the same name. (But you probably shouldn't do that anyway.)</p>\n"
},
{
"answer_id": 62989,
"author": "Bill Rawlinson",
"author_id": 7329,
"author_profile": "https://Stackoverflow.com/users/7329",
"pm_score": 1,
"selected": false,
"text": "<p>The simple answer to your question is:\n\"NO, it isn't necessary\"</p>\n\n<p>However, I think best practices would suggest that you do, in fact, use the variables indentifier when accessing those variables. In my opinion anyone who comes upon your code in the future, and is looking in the middle of a function, will instantly know the scoping of the variable without having to scan the top of the function the local functions.</p>\n\n<p>In fact, I add a little extra verbosity to my CFC UDFs by creating one local struct:</p>\n\n<p><cfset var local = structNew() /></p>\n\n<p>Then I put all my local vars in that struct and reference them that way so my code will look something like this:</p>\n\n<p><cfset local.foo = variables.bar + 10 /></p>\n"
},
{
"answer_id": 65112,
"author": "Dan Wilson",
"author_id": 8823,
"author_profile": "https://Stackoverflow.com/users/8823",
"pm_score": 3,
"selected": false,
"text": "<p>Especially in CFCs, proper scoping is important. The extra 'verbosity' is worth the clarity. \nHaving variables slip out of their indended scope will cause severe problems and very hard to diagnose.</p>\n\n<p>Verbosity isn't always a bad thing. We name our functions and methods in descriptive manners like getAuthenticatedUser(), rather than gau(). Database columns and tables are best left descriptive like EmployeePayroll rather than empprl. Thus, being terse might be 'easier' when your short term memory is full of the project details, but being descriptive shows your intent and is helpful during the maintenance phase of an application, long after your short term memory has been filled with other stuff.</p>\n"
},
{
"answer_id": 99253,
"author": "ethyreal",
"author_id": 18159,
"author_profile": "https://Stackoverflow.com/users/18159",
"pm_score": 0,
"selected": false,
"text": "<p>Best practices aside, i believe it could also depend on how your going to access your cfc's i have not had any problems leaving them out when creating objects and accessing them from coldfusion. However i think it might be needed when accessing and/or mapping them remotely via actionscript in flex/flash. </p>\n"
},
{
"answer_id": 128842,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>I'll say Yes. Is it explicitly necessary? Nope. Can you get away with not doing it? Sure. Are you asking for trouble? Absolutely. If you have the following inside a cffunction:</p>\n\n<pre><code><cfset foo = \"bar\" />\n</code></pre>\n\n<p>That will not place that variable in the function local var scope, it will place it in the CFC's global VARIABLES scope, meaning that it is available to every method of that CFC. There are times when you may want to do this, but most of the time you'd be asking for a race condition.</p>\n\n<p>When any variable is being read by the server, if that variable is not explicity declared as part of a scope (REQUEST., SESSION., etc.) then ColdFusion will run ScopeCheck() to determine which scope the variable is in. Not only is this placing unnecessary overhead on your application server, it also introduces the ability for hijacking, whereby your variable is in one scope, but ScopeCheck() has found a variable of the same name higher in the precedence order.</p>\n\n<p>Always, always, ALWAYS, scope all variables. No matter how trivial. Even things like query names and looping indexes. Save yourself, and those that come behind you, from the pain.</p>\n"
},
{
"answer_id": 131137,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a very good <a href=\"http://www.coldfusionjedi.com/downloads/cfcscopes.pdf\" rel=\"nofollow noreferrer\">CFC scope reference</a> from Raymond Camden.\nPersonally, I prefer to make a 'self' hash to avoid all confusion (notice I don't use the 'variables' scope in the functions):</p>\n\n<pre><code><cfcomponent>\n <cfset variables.self = structNew()>\n <cfscript>\n structInsert(variables.self, <key>, <value>);\n ...\n </cfscript>\n\n <cffunction name=\"foo\">\n self.<key> = <value>\n <cfreturn self.<key> />\n </cffunction>\n\n ...\n</code></pre>\n"
},
{
"answer_id": 148409,
"author": "Matt Woodward",
"author_id": 3612,
"author_profile": "https://Stackoverflow.com/users/3612",
"pm_score": 2,
"selected": false,
"text": "<p>Not explicitly scoping in the variables scope may work, but it's not a good idea, and honestly the only reason <em>not</em> to is out of laziness IMO. If you explicitly scope everything 1) you avoid potential issues, and 2) it makes the code easier to read because there's no question which scope things are in.</p>\n\n<p>To me it doesn't make the code more verbose (and certainly not unnecessarily verbose)--it's actually easier to read, avoids confusion, and avoids weird side effects that may crop up if you don't explicitly scope.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59390",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/437/"
]
| In a ColdFusion Component (CFC), is it necessary to use fully qualified names for variables-scoped variables?
Am I going to get myself into trouble if I change this:
```
<cfcomponent>
<cfset variables.foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #variables.foo# and #bar#.">
</cffunction>
</cfcomponent>
```
to this?
```
<cfcomponent>
<cfset foo = "a private instance variable">
<cffunction name = "doSomething">
<cfset var bar = "a function local variable">
<cfreturn "I have #foo# and #bar#.">
</cffunction>
</cfcomponent>
``` | It won't matter to specify "variables" when you create the variable, because foo will be placed in the variables scope by default; but it will matter when you access the variable.
```
<cfcomponent>
<cfset foo = "a private instance variable">
<cffunction name="doSomething">
<cfargument name="foo" required="yes"/>
<cfset var bar = "a function local variable">
<cfreturn "I have #foo# and #bar#.">
</cffunction>
<cffunction name="doAnotherThing">
<cfargument name="foo" required="yes"/>
<cfset var bar = "a function local variable">
<cfreturn "I have #variables.foo# and #bar#.">
</cffunction>
</cfcomponent>
```
doSomething("args") returns "I have **args** and a **function local variable**"
doAnotherThing("args") returns "I have **a private instance of a variable** and a **function local variable**." |
59,396 | <p>I have a Data Access Object TransactionDao. When you call TransactionDao.Save(transaction) I would like for it to setting a transaction.IsSaved=true flag (this is a simplification the actual thing I'm trying to do is not quite so banal). So when mocking my TransactionDao with RhinoMocks how can I indicate that it should transform its input?</p>
<p>Ideally I would like to write something like this:</p>
<pre><code>Expect.Call(delegate {dao.Save(transaction);}).Override(x => x.IsSaved=true);
</code></pre>
<p>Does anyone know how to do this?</p>
<hr>
<p>Though I got a hint how to do it from the answer specified below the actual type signature is off, you have to do something like this:
Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p>
<pre><code>public delegate void FakeSave(Transaction t);
...
Expect.Call(delegate {dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.IsSaved = true; }));
</code></pre>
| [
{
"answer_id": 59420,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": -1,
"selected": false,
"text": "<p>you should mock the transaction and make it return true fo IsSaved, if you can mock the transaction of course.</p>\n\n<pre><code>ITransaction transaction = _Mocker.dynamicMock<ITransaction>;\nExpect.Call(transaction.IsSaved).IgnoreArguments.Return(true);\n_mocker.ReplayAll();\ndao.Save(transaction);\n</code></pre>\n"
},
{
"answer_id": 59429,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 1,
"selected": false,
"text": "<p>You can accomplish this using the Do callback:</p>\n\n<pre><code>Expect.Call(delegate {dao.Save(transaction);})\n .Do(x => x.IsSaved = true);\n</code></pre>\n"
},
{
"answer_id": 867435,
"author": "frantisek",
"author_id": 53332,
"author_profile": "https://Stackoverflow.com/users/53332",
"pm_score": 3,
"selected": true,
"text": "<p>Gorge, </p>\n\n<p>The simplest solution, which I found, applied to your question is the following:</p>\n\n<pre><code>Expect.Call(() => dao.Save(transaction))\n .Do(new Action<Transaction>(x => x.IsSaved = true));\n</code></pre>\n\n<p>So you don't need to create a special delegate or anything else. Just use Action which is in standard .NET 3.5 libraries.</p>\n\n<p>Hope this help.\nFrantisek</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59396",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I have a Data Access Object TransactionDao. When you call TransactionDao.Save(transaction) I would like for it to setting a transaction.IsSaved=true flag (this is a simplification the actual thing I'm trying to do is not quite so banal). So when mocking my TransactionDao with RhinoMocks how can I indicate that it should transform its input?
Ideally I would like to write something like this:
```
Expect.Call(delegate {dao.Save(transaction);}).Override(x => x.IsSaved=true);
```
Does anyone know how to do this?
---
Though I got a hint how to do it from the answer specified below the actual type signature is off, you have to do something like this:
Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:
```
public delegate void FakeSave(Transaction t);
...
Expect.Call(delegate {dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.IsSaved = true; }));
``` | Gorge,
The simplest solution, which I found, applied to your question is the following:
```
Expect.Call(() => dao.Save(transaction))
.Do(new Action<Transaction>(x => x.IsSaved = true));
```
So you don't need to create a special delegate or anything else. Just use Action which is in standard .NET 3.5 libraries.
Hope this help.
Frantisek |
59,422 | <p>Is accessing a <strong>bool</strong> field atomic in C#? In particular, do I need to put a lock around:</p>
<pre><code>class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
</code></pre>
| [
{
"answer_id": 59430,
"author": "Larsenal",
"author_id": 337,
"author_profile": "https://Stackoverflow.com/users/337",
"pm_score": 8,
"selected": true,
"text": "<p><strong>Yes.</strong></p>\n\n<blockquote>\n <p>Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types. </p>\n</blockquote>\n\n<p>as found in <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references\" rel=\"noreferrer\">C# Language Spec</a>.</p>\n\n<p>Edit: It's probably also worthwhile understanding the <a href=\"https://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.140).aspx\" rel=\"noreferrer\"><strong>volatile</strong></a> keyword.</p>\n"
},
{
"answer_id": 59505,
"author": "McKenzieG1",
"author_id": 3776,
"author_profile": "https://Stackoverflow.com/users/3776",
"pm_score": 5,
"selected": false,
"text": "<p>bool accesses are indeed atomic, but that isn't the whole story. </p>\n\n<p>You don't have to worry about reading a value that is 'incompletely written' - it isn't clear what that could possibly mean for a bool in any case - but you do have to worry about processor caches, at least if details of timing are an issue. If thread #1 running on core A has your <code>_bar</code> in cache, and <code>_bar</code> gets updated by thread #2 running on another core, thread #1 will not see the change immediately unless you add locking, declare <code>_bar</code> as <code>volatile</code>, or explicitly insert calls to <code>Thread.MemoryBarrier()</code> to invalidate the cached value.</p>\n"
},
{
"answer_id": 106301,
"author": "Dror Helper",
"author_id": 11361,
"author_profile": "https://Stackoverflow.com/users/11361",
"pm_score": 6,
"selected": false,
"text": "<p>As stated above, <code>bool</code> is atomic, but you still need to remember that it also depends on what you want to do with it.</p>\n<pre><code>if(b == false)\n{\n //do something\n}\n</code></pre>\n<p>is not an atomic operation, meaning that the value of <code>b</code> could change before the current thread executes the code after the <code>if</code> statement.</p>\n"
},
{
"answer_id": 16664812,
"author": "stux",
"author_id": 1581640,
"author_profile": "https://Stackoverflow.com/users/1581640",
"pm_score": 2,
"selected": false,
"text": "<p>the approach I have used, and I think is correct, is</p>\n\n<pre><code>volatile bool b = false;\n\n.. rarely signal an update with a large state change...\n\nlock b_lock\n{\n b = true;\n //other;\n}\n\n... another thread ...\n\nif(b)\n{\n lock b_lock\n {\n if(b)\n {\n //other stuff\n b = false;\n }\n }\n}\n</code></pre>\n\n<p>the goal was basically to avoid having to repetively lock an object on every iteration just to check if we needed to lock it in order to provide a large amount of state change information which occurs rarely. I <em>think</em> this approach works. And if absolute consistancy is required, I <em>think</em> volatile would be appropriate on the b bool.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59422",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/838/"
]
| Is accessing a **bool** field atomic in C#? In particular, do I need to put a lock around:
```
class Foo
{
private bool _bar;
//... in some function on any thread (or many threads)
_bar = true;
//... same for a read
if (_bar) { ... }
}
``` | **Yes.**
>
> Reads and writes of the following data types are atomic: bool, char, byte, sbyte, short, ushort, uint, int, float, and reference types.
>
>
>
as found in [C# Language Spec](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#atomicity-of-variable-references).
Edit: It's probably also worthwhile understanding the [**volatile**](https://msdn.microsoft.com/en-us/library/x13ttww7(v=vs.140).aspx) keyword. |
59,423 | <p>I've got the following in my .css file creating a little image next to each link on my site:</p>
<pre class="lang-css prettyprint-override"><code>div.post .text a[href^="http:"]
{
background: url(../../pics/remote.gif) right top no-repeat;
padding-right: 10px;
white-space: nowrap;
}
</code></pre>
<p>How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves?</p>
| [
{
"answer_id": 59448,
"author": "Thunder3",
"author_id": 2832,
"author_profile": "https://Stackoverflow.com/users/2832",
"pm_score": 1,
"selected": false,
"text": "<p>It might be worth it to add a class to those <code><a></code> tags and then add another declaration to remove the background:</p>\n\n<pre><code>div.post .text a.noimage{\n background:none;\n}\n</code></pre>\n"
},
{
"answer_id": 59454,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>If you have the content of the links as a span, you could do this, otherwise I think you would need to give one scenario a class to differentiate it.</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>a > span {\n background: url(../../pics/remote.gif) right top no-repeat;\n padding-right: 10px;\n white-space: nowrap;\n}\na > img {\n /* any specific styling for images wrapped in a link (e.g. polaroid like) */\n border: 1px solid #cccccc;\n padding: 4px 4px 25px 4px;\n}\n</code></pre>\n"
},
{
"answer_id": 59469,
"author": "gz.",
"author_id": 3665,
"author_profile": "https://Stackoverflow.com/users/3665",
"pm_score": 0,
"selected": false,
"text": "<p>You need a class name on either the <code>a</code> elements you want to include or exclude. If you don't want to do this in your server side code or documents, you could add the classes with javascript as the page is loaded. With the selection logic wrapped up elsewhere, your rule could just be:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>a.external_link\n{\n background: url(../../pics/remote.gif) right top no-repeat;\n padding-right: 10px;\n white-space: nowrap;\n}\n</code></pre>\n\n<p>It would be possible with XPath to create a pattern like yours that would also exclude <code>a</code> elements that had <code>img</code> children, however this facility has been repeatedly (<a href=\"http://lists.w3.org/Archives/Public/www-style/2002May/0011.html\" rel=\"nofollow noreferrer\">2002</a>, <a href=\"http://lists.w3.org/Archives/Public/www-style/2006Oct/0009.html\" rel=\"nofollow noreferrer\">2006</a>, <a href=\"http://lists.w3.org/Archives/Public/www-style/2007Apr/0105.html\" rel=\"nofollow noreferrer\">2007</a>) proposed and rejected for CSS, largely on the grounds it goes against the incremental layout principles.</p>\n\n<p>So, while it is possible to do neat conditional content additions as you have with a contextual selector and a prefix match on the <code>href</code> attribute, CSS is considerably weaker than a general purpose programming language. To do more complex things you need to move the logic up a level and write out simpler instructions for the style engine to handle.</p>\n"
},
{
"answer_id": 59511,
"author": "rpetrich",
"author_id": 4007,
"author_profile": "https://Stackoverflow.com/users/4007",
"pm_score": 3,
"selected": true,
"text": "<p>If you set the background color and have a negative right margin on the image, the image will cover the external link image.</p>\n\n<p>Example:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>a[href^=\"http:\"] {\r\n background: url(http://en.wikipedia.org/skins-1.5/monobook/external.png) right center no-repeat;\r\n padding-right: 14px;\r\n white-space: nowrap;\r\n}\r\na[href^=\"http:\"] img {\r\n margin-right: -14px;\r\n border: medium none;\r\n background-color: red;\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><a href=\"http://www.google.ca\">Google</a>\r\n<br/>\r\n<a href=\"http://www.google.ca\">\r\n <img src=\"http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/50px-Commons-logo.svg.png\" />\r\n</a></code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>edit: If you've got a patterned background this isn't going to look great for images that have transparency. Also, your <code>href^=</code> selector won't work on IE7 but you probably knew that already</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59423",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1683/"
]
| I've got the following in my .css file creating a little image next to each link on my site:
```css
div.post .text a[href^="http:"]
{
background: url(../../pics/remote.gif) right top no-repeat;
padding-right: 10px;
white-space: nowrap;
}
```
How do I modify this snippet (or add something new) to exclude the link icon next to images that are links themselves? | If you set the background color and have a negative right margin on the image, the image will cover the external link image.
Example:
```css
a[href^="http:"] {
background: url(http://en.wikipedia.org/skins-1.5/monobook/external.png) right center no-repeat;
padding-right: 14px;
white-space: nowrap;
}
a[href^="http:"] img {
margin-right: -14px;
border: medium none;
background-color: red;
}
```
```html
<a href="http://www.google.ca">Google</a>
<br/>
<a href="http://www.google.ca">
<img src="http://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Commons-logo.svg/50px-Commons-logo.svg.png" />
</a>
```
edit: If you've got a patterned background this isn't going to look great for images that have transparency. Also, your `href^=` selector won't work on IE7 but you probably knew that already |
59,425 | <p>I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record.</p>
<pre><code>INSERT INTO messages
(typeId, messageTime, stationId, message)
VALUES
(?, NOW(), ?, ?)
</code></pre>
| [
{
"answer_id": 59437,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 3,
"selected": true,
"text": "<pre><code>SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime\n</code></pre>\n"
},
{
"answer_id": 59443,
"author": "Martynnw",
"author_id": 5466,
"author_profile": "https://Stackoverflow.com/users/5466",
"pm_score": 2,
"selected": false,
"text": "<p>The SQL Server query is:</p>\n\n<pre><code>Select *\nFrom Messages\nWhere MessageTime > DateAdd(dd, -1, GetDate())\n</code></pre>\n\n<p>As far as I can tell the (untested!) MySQL equivalent is</p>\n\n<pre><code>Select *\nFrom Messages\nWhere MessageTime > ADDDATE(NOW(), INTERVAL -1 DAY)\n</code></pre>\n"
},
{
"answer_id": 59459,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>There is no cross database solution, as most of them have their own date handling (and mainly interval representation) syntax and semantics. </p>\n\n<p>In <code>PostgreSQL</code> it would be</p>\n\n<pre><code>SELECT * FROM messages WHERE messagetime >= messagetime - interval '1 day'\n</code></pre>\n"
},
{
"answer_id": 59470,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "<p>For Sybase SQL Anywhere:</p>\n\n<pre><code>Select * From Messages Where MessageTime > dateadd( day, -1, now() )\n</code></pre>\n"
},
{
"answer_id": 59508,
"author": "hamishmcn",
"author_id": 3590,
"author_profile": "https://Stackoverflow.com/users/3590",
"pm_score": 1,
"selected": false,
"text": "<p>For Oracle </p>\n\n<pre><code>SELECT * FROM messages WHERE messageTime > SYSDATE - 1\n</code></pre>\n\n<p>(The psuedo variable SYSDATE includes the time, so sysdate -1 will give you the last 24 hrs)</p>\n"
},
{
"answer_id": 59532,
"author": "John Meagher",
"author_id": 3535,
"author_profile": "https://Stackoverflow.com/users/3535",
"pm_score": 0,
"selected": false,
"text": "<p>If you are accessing this from an API based client (I'm guessing that is the case because of the '?'s in the query) you can do this from your program rather than through SQL.</p>\n\n<p>Note: The rest is for JDBC syntax, other APIs/languages will be different syntax, but should be conceptually the same. </p>\n\n<p>On the insert side do</p>\n\n<pre><code>PreparedStatement stmt = connection.prepareStatement( \n \"INSERT INTO messages \" +\n \"(typeId, messageTime, stationId, message) VALUES \" +\n \"(?, ?, ?, ?)\" );\nstmt.setInt(1, typeId);\nstmt.setDate(2, new java.sql.Date(System.currentTimeMillis()));\nstmt.setInt(3, stationId);\nstmt.setString(4, message);\n</code></pre>\n\n<p>On the query side do:</p>\n\n<pre><code>PrepatedStatement stmt = connection.prepareStatement(\n \"SELECT typeId, messageTime, stationId, message \" +\n \"from messages where messageTime < ?\");\nlong yesterday = System.currentTimeMillis() - 86400000; // 86400 sec/day\nstmt.setDate(1,new java.sql.Date(yesterday));\n</code></pre>\n\n<p>That should work in a portable manner. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59425",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1288/"
]
| I'm using MySQL in particular, but I'm hoping for a cross-vendor solution. I'm using the NOW() function to add a timestamp as a column for each record.
```
INSERT INTO messages
(typeId, messageTime, stationId, message)
VALUES
(?, NOW(), ?, ?)
``` | ```
SELECT * FROM messages WHERE DATE_SUB(CURDATE(),INTERVAL 1 DAY) <= messageTime
``` |
59,444 | <p>Is there a system stored procedure to get the version #?</p>
| [
{
"answer_id": 59449,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 5,
"selected": false,
"text": "<p>SELECT @@VERSION</p>\n"
},
{
"answer_id": 59457,
"author": "Joe Kuemerle",
"author_id": 4273,
"author_profile": "https://Stackoverflow.com/users/4273",
"pm_score": 9,
"selected": true,
"text": "<p>Try </p>\n\n<pre><code>SELECT @@VERSION \n</code></pre>\n\n<p>or for SQL Server 2000 and above the following is easier to parse :) </p>\n\n<pre><code>SELECT SERVERPROPERTY('productversion')\n , SERVERPROPERTY('productlevel')\n , SERVERPROPERTY('edition')\n</code></pre>\n\n<p>From: <a href=\"http://support.microsoft.com/kb/321185\" rel=\"noreferrer\">http://support.microsoft.com/kb/321185</a></p>\n"
},
{
"answer_id": 60399,
"author": "Matt",
"author_id": 4154,
"author_profile": "https://Stackoverflow.com/users/4154",
"pm_score": 2,
"selected": false,
"text": "<p>The KB article linked in <a href=\"https://stackoverflow.com/questions/59444/how-do-you-check-what-version-of-sql-server-for-a-database-using-tsql#59457\">Joe's post</a> is great for determining which service packs have been installed for any version. Along those same lines, <a href=\"http://support.microsoft.com/kb/937137\" rel=\"nofollow noreferrer\">this KB article</a> maps version numbers to specific hotfixes and cumulative updates, but it only applies to SQL05 SP2 and up.</p>\n"
},
{
"answer_id": 510741,
"author": "Bruce Chapman",
"author_id": 174730,
"author_profile": "https://Stackoverflow.com/users/174730",
"pm_score": 2,
"selected": false,
"text": "<p>Here's a bit of script I use for testing if a server is 2005 or later</p>\n\n<pre><code>declare @isSqlServer2005 bit\nselect @isSqlServer2005 = case when CONVERT(int, SUBSTRING(CONVERT(varchar(15), SERVERPROPERTY('productversion')), 0, CHARINDEX('.', CONVERT(varchar(15), SERVERPROPERTY('productversion'))))) < 9 then 0 else 1 end\nselect @isSqlServer2005\n</code></pre>\n\n<p>Note : updated from original answer (see comment)</p>\n"
},
{
"answer_id": 3178966,
"author": "freak",
"author_id": 383595,
"author_profile": "https://Stackoverflow.com/users/383595",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>if (SELECT LEFT(CAST(SERVERPROPERTY('productversion') as varchar), 2)) = '10'\nBEGIN\n</code></pre>\n"
},
{
"answer_id": 6454881,
"author": "Geoff",
"author_id": 55487,
"author_profile": "https://Stackoverflow.com/users/55487",
"pm_score": 4,
"selected": false,
"text": "<p>For SQL Server 2000 and above, I prefer the following parsing of Joe's answer:</p>\n\n<pre><code>declare @sqlVers numeric(4,2)\nselect @sqlVers = left(cast(serverproperty('productversion') as varchar), 4)\n</code></pre>\n\n<p>Gives results as follows:</p>\n\n<pre>\n<b>Result Server Version</b>\n8.00 SQL 2000\n9.00 SQL 2005\n10.00 SQL 2008\n10.50 SQL 2008R2\n11.00 SQL 2012\n12.00 SQL 2014\n</pre>\n\n<p>Basic list of version numbers <a href=\"http://sqlserverbuilds.blogspot.com/\" rel=\"noreferrer\">here</a>, or exhaustive list from Microsoft <a href=\"https://support.microsoft.com/en-us/kb/321185?wa=wsignin1.0\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 14390702,
"author": "Mark Kram",
"author_id": 100283,
"author_profile": "https://Stackoverflow.com/users/100283",
"pm_score": 5,
"selected": false,
"text": "<p>I know this is an older post but I updated the code found in the <a href=\"http://blog.devstone.com/aaron/default,date,2006-12-15.aspx\" rel=\"nofollow noreferrer\">link</a> (which is dead as of 2013-12-03) mentioned in the <a href=\"https://stackoverflow.com/a/59450/15168\">answer</a> posted by <a href=\"https://stackoverflow.com/users/2590/matt-rogish\">Matt Rogish</a>:</p>\n\n<pre><code>DECLARE @ver nvarchar(128)\nSET @ver = CAST(serverproperty('ProductVersion') AS nvarchar)\nSET @ver = SUBSTRING(@ver, 1, CHARINDEX('.', @ver) - 1)\n\nIF ( @ver = '7' )\n SELECT 'SQL Server 7'\nELSE IF ( @ver = '8' )\n SELECT 'SQL Server 2000'\nELSE IF ( @ver = '9' )\n SELECT 'SQL Server 2005'\nELSE IF ( @ver = '10' )\n SELECT 'SQL Server 2008/2008 R2'\nELSE IF ( @ver = '11' )\n SELECT 'SQL Server 2012'\nELSE IF ( @ver = '12' )\n SELECT 'SQL Server 2014'\nELSE IF ( @ver = '13' )\n SELECT 'SQL Server 2016'\nELSE IF ( @ver = '14' )\n SELECT 'SQL Server 2017'\nELSE\n SELECT 'Unsupported SQL Server Version'\n</code></pre>\n"
},
{
"answer_id": 16571275,
"author": "crosswalk",
"author_id": 236423,
"author_profile": "https://Stackoverflow.com/users/236423",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT \n@@SERVERNAME AS ServerName,\nCASE WHEN LEFT(CAST(serverproperty('productversion') as char), 1) = 9 THEN '2005'\n WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 10 THEN '2008'\n WHEN LEFT(CAST(serverproperty('productversion') as char), 2) = 11 THEN '2012'\nEND AS MajorVersion,\nSERVERPROPERTY ('productlevel') AS MinorVersion, \nSERVERPROPERTY('productversion') AS FullVersion, \nSERVERPROPERTY ('edition') AS Edition\n</code></pre>\n"
},
{
"answer_id": 23385767,
"author": "Nux",
"author_id": 333296,
"author_profile": "https://Stackoverflow.com/users/333296",
"pm_score": 1,
"selected": false,
"text": "<p>Getting only the major SQL Server version in a single select:</p>\n\n<pre><code>SELECT SUBSTRING(ver, 1, CHARINDEX('.', ver) - 1)\nFROM (SELECT CAST(serverproperty('ProductVersion') AS nvarchar) ver) as t\n</code></pre>\n\n<p>Returns <code>8</code> for SQL 2000, <code>9</code> for SQL 2005 and so on (tested up to 2012).</p>\n"
},
{
"answer_id": 25188612,
"author": "Zia",
"author_id": 3919450,
"author_profile": "https://Stackoverflow.com/users/3919450",
"pm_score": 2,
"selected": false,
"text": "<p>There is another extended Stored Procedure which can be used to see the Version info:</p>\n\n<pre><code>exec [master].sys.[xp_msver]\n</code></pre>\n"
},
{
"answer_id": 26818437,
"author": "Alex",
"author_id": 2397221,
"author_profile": "https://Stackoverflow.com/users/2397221",
"pm_score": 2,
"selected": false,
"text": "<pre><code>CREATE FUNCTION dbo.UFN_GET_SQL_SEVER_VERSION \n(\n)\nRETURNS sysname\nAS\nBEGIN\n DECLARE @ServerVersion sysname, @ProductVersion sysname, @ProductLevel sysname, @Edition sysname;\n\n SELECT @ProductVersion = CONVERT(sysname, SERVERPROPERTY('ProductVersion')), \n @ProductLevel = CONVERT(sysname, SERVERPROPERTY('ProductLevel')),\n @Edition = CONVERT(sysname, SERVERPROPERTY ('Edition'));\n --see: http://support2.microsoft.com/kb/321185\n SELECT @ServerVersion = \n CASE \n WHEN @ProductVersion LIKE '8.00.%' THEN 'Microsoft SQL Server 2000'\n WHEN @ProductVersion LIKE '9.00.%' THEN 'Microsoft SQL Server 2005'\n WHEN @ProductVersion LIKE '10.00.%' THEN 'Microsoft SQL Server 2008'\n WHEN @ProductVersion LIKE '10.50.%' THEN 'Microsoft SQL Server 2008 R2'\n WHEN @ProductVersion LIKE '11.0%' THEN 'Microsoft SQL Server 2012'\n WHEN @ProductVersion LIKE '12.0%' THEN 'Microsoft SQL Server 2014'\n END\n\n RETURN @ServerVersion + N' ('+@ProductLevel + N'), ' + @Edition + ' - ' + @ProductVersion;\n\nEND\nGO\n</code></pre>\n"
},
{
"answer_id": 35787064,
"author": "pruthvi",
"author_id": 6016258,
"author_profile": "https://Stackoverflow.com/users/6016258",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT\n 'the sqlserver is ' + substring(@@VERSION, 21, 5) AS [sql version]\n</code></pre>\n"
},
{
"answer_id": 40177596,
"author": "Allen Ackerman",
"author_id": 7053303,
"author_profile": "https://Stackoverflow.com/users/7053303",
"pm_score": 1,
"selected": false,
"text": "<p>If all you want is the major version for T-SQL reasons, the following gives you the year of the SQL Server version for 2000 or later.</p>\n\n<p><code>SELECT left(ltrim(replace(@@Version,'Microsoft SQL Server','')),4)</code></p>\n\n<p>This code gracefully handles the extra spaces and tabs for various versions of SQL Server.</p>\n"
},
{
"answer_id": 42291858,
"author": "Arif",
"author_id": 7579331,
"author_profile": "https://Stackoverflow.com/users/7579331",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT @@VERSION[server], SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')\n</code></pre>\n"
},
{
"answer_id": 43767263,
"author": "VAV",
"author_id": 1921460,
"author_profile": "https://Stackoverflow.com/users/1921460",
"pm_score": 1,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>SELECT @@MICROSOFTVERSION / 0x01000000 AS MajorVersionNumber\n</code></pre>\n\n<p>For more information see: <a href=\"https://social.technet.microsoft.com/wiki/contents/articles/783.sql-server-versions.aspx\" rel=\"nofollow noreferrer\">Querying for version/edition info</a></p>\n"
},
{
"answer_id": 49512753,
"author": "Vikrant Bagal",
"author_id": 5426308,
"author_profile": "https://Stackoverflow.com/users/5426308",
"pm_score": 1,
"selected": false,
"text": "<pre><code>select substring(@@version,0,charindex(convert(varchar,SERVERPROPERTY('productversion')) ,@@version)+len(convert(varchar,SERVERPROPERTY('productversion')))) \n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
| Is there a system stored procedure to get the version #? | Try
```
SELECT @@VERSION
```
or for SQL Server 2000 and above the following is easier to parse :)
```
SELECT SERVERPROPERTY('productversion')
, SERVERPROPERTY('productlevel')
, SERVERPROPERTY('edition')
```
From: <http://support.microsoft.com/kb/321185> |
59,451 | <p>How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.</p>
<p>Edit: Here's the code I'm now using this for, based on the answer from Santiago below.</p>
<pre><code>public DataTemplate Create(Type type)
{
return (DataTemplate)XamlReader.Load(
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/client/2007"">
<" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
</DataTemplate>"
);
}
</code></pre>
<p>This works really nicely and allows me to change the binding on the fly. </p>
| [
{
"answer_id": 62871,
"author": "jarda",
"author_id": 6601,
"author_profile": "https://Stackoverflow.com/users/6601",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://msdn.microsoft.com/en-us/library/system.windows.datatemplate%28v=vs.95%29.aspx\" rel=\"nofollow noreferrer\">citation from MSDN</a>: </p>\n\n<blockquote>\n <p>The XAML usage that defines the content for creating a data template is not exposed as a settable property. It is special behavior built into the XAML processing of a DataTemplate object element.</p>\n</blockquote>\n"
},
{
"answer_id": 72158,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": true,
"text": "<p>Although you cannot programatically create it, you can load it from a XAML string in code like this:</p>\n\n<pre><code> public static DataTemplate Create(Type type)\n {\n return (DataTemplate) XamlReader.Load(\n @\"<DataTemplate\n xmlns=\"\"http://schemas.microsoft.com/client/2007\"\">\n <\" + type.Name + @\"/>\n </DataTemplate>\"\n );\n }\n</code></pre>\n\n<p>The snippet above creates a data template containing a single control, which may be a user control with the contents you need.</p>\n"
},
{
"answer_id": 356064,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>I had a few problems with this code, getting element not foung exceptions. Just for reference, it was that I needed my namesspace included in the DataTemplate...</p>\n\n<pre><code>private DataTemplate Create(Type type)\n {\n string xaml = @\"<DataTemplate \n xmlns=\"\"http://schemas.microsoft.com/client/2007\"\"\n xmlns:controls=\"\"clr-namespace:\" + type.Namespace + @\";assembly=\" + type.Namespace + @\"\"\">\n <controls:\" + type.Name + @\"/></DataTemplate>\";\n return (DataTemplate)XamlReader.Load(xaml);\n }\n</code></pre>\n"
},
{
"answer_id": 7101581,
"author": "Davut Gürbüz",
"author_id": 413032,
"author_profile": "https://Stackoverflow.com/users/413032",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, Silverligt 4 older than WPF's current versions. \nWhen you add a template as a resource i.e. as I did\nI added a userControl Template in Application.xaml MergedResources between ResourceDictionary.\nIn XAML if tag implemented IDictionary you could user x:Key attribute. Like that </p>\n\n<pre><code> <ResourceDictionary>\n <DataTemplate x:Key=\"TextBoxEditTemplate\">\n <Some user control x:Name=\"myOwnControl\" />\n </DataTemplate>\n </ResourceDictionary>\n</code></pre>\n\n<p>Ok! You may reach your template by coding that, <strong>Application.Current.resources[\"TextBoxEditTemplate\"]</strong>\non the other hand some methods for finding members of this template will not work. Beside this DataTemplate doesn't implement IDictionary so you cannot assign x:Key attribute for items in this dataTemplate. as myOwnControl in example.</p>\n\n<p>Without xaml current silverlight has some restrictions about creation fully dynamic code-behind DataTemplates.Even it works on WPF.</p>\n\n<p>Anyway the best solution by this point is creation of XAML script for datatemplate ,You may assing some values element in DataTemplate script. We created our own usercontrols has some properties with DependencyObjectProperty...</p>\n\n<p>At last if your object has no inherits ,i.e. not a MyControl:UserControl you may inherit <strong><em>MyObject:DependencyObject</em></strong> by this way you can reach your object by calling like Application.Current.Resources.FirstChilderen...</p>\n\n<p>FindName works only in WPF</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5932/"
]
| How do I create a silverlight data template in code? I've seen plenty of examples for WPF, but nothing for Silverlight.
Edit: Here's the code I'm now using this for, based on the answer from Santiago below.
```
public DataTemplate Create(Type type)
{
return (DataTemplate)XamlReader.Load(
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/client/2007"">
<" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/>
</DataTemplate>"
);
}
```
This works really nicely and allows me to change the binding on the fly. | Although you cannot programatically create it, you can load it from a XAML string in code like this:
```
public static DataTemplate Create(Type type)
{
return (DataTemplate) XamlReader.Load(
@"<DataTemplate
xmlns=""http://schemas.microsoft.com/client/2007"">
<" + type.Name + @"/>
</DataTemplate>"
);
}
```
The snippet above creates a data template containing a single control, which may be a user control with the contents you need. |
59,456 | <p>I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.</p>
<p>Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, _File</p>
<p>However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?</p>
<pre><code><Menu>
<MenuItem>
<MenuItem.Header>
<UserControl>
<Image Source="..." />
<Label Text="_Open" />
</UserControl>
</MenuItem.Header>
</MenuItem>
...
</code></pre>
| [
{
"answer_id": 59706,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is you placed the image inside of the content of the MenuHeader which means that you'll lose the accelerator key. If you're just trying to have an image in the menu header, do the following.</p>\n\n<pre><code><MenuItem Header=\"_Open\">\n <MenuItem.Icon>\n <Image Source=\"images/Open.png\"/>\n </MenuItem.Icon>\n</MenuItem>\n</code></pre>\n\n<p>If you want to customize the look and feel even further, modify the <a href=\"http://msdn.microsoft.com/en-us/library/ms747082(VS.85).aspx\" rel=\"nofollow noreferrer\">controltemplate</a> and style for the menu. From experience, styling the menus and menuitems are much more difficult then styling the other WPF controls.</p>\n"
},
{
"answer_id": 60361,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 0,
"selected": false,
"text": "<p>@a7an: Ah, I didn't notice the Icon property before. That's a good start.</p>\n\n<p>However, specifically I wanted to add an extra 'button' to some MenuItems so I could have a 'Pin' feature (see the recently loaded Documents list in Office 2007 for the feature idea).</p>\n\n<p>Since there needs to be code as well, will I probably need to subclass the control and add the code for the button? (Not affraid of messing with the MenuItem template, have already had to do it once and I'd do it again if I had to! ;) )</p>\n"
},
{
"answer_id": 60365,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 4,
"selected": true,
"text": "<p>I think the Icon property fits your needs.<br>\nHowever to answer the original question, it is possible to retain the Accelerator functionality when you compose the content of your menuitem. <strong>If you have nested content in a MenuItem you need to define the AccessText property explicitly</strong> like in the first one below. When you use the inline form, this is automagically taken care of.</p>\n\n<pre><code> <Menu> \n <MenuItem>\n <MenuItem.Header>\n <StackPanel Orientation=\"Horizontal\">\n <Image Source=\"Images/Open.ico\" /> \n <AccessText>_Open..</AccessText>\n </StackPanel>\n </MenuItem.Header>\n </MenuItem>\n <MenuItem Header=\"_Close\" />\n </Menu>\n</code></pre>\n"
},
{
"answer_id": 1108605,
"author": "awe",
"author_id": 109392,
"author_profile": "https://Stackoverflow.com/users/109392",
"pm_score": 2,
"selected": false,
"text": "<p>First thought, you would think that the Icon property can only contain an image. But it can actually contain anything! I discovered this by accident when I programmatically tried to set the Image property directly to a string with the path to an image. The result was that it did not show the image, but the actual text of the path! Then I discovered that I had to create an Image element first and set that to the Icon property. This lead me to think that the Image property was just any content container that is located in the icon area at the left in the menu, and I was right. I tried to put a button there, and it worked!</p>\n\n<p>This is showing a button with the text \"i\" in the Icon area of the menu item. When you click on the button, the Button_Click event is triggered (the LanguageMenu_Click is NOT triggered when you click the button).</p>\n\n<pre><code><MenuItem Name=\"LanguageMenu\" Header=\"_Language\" Click=\"LanguageMenu_Click\">\n <MenuItem.Icon>\n <Button Click=\"Button_Click\">i</Button>\n </MenuItem.Icon>\n</MenuItem>\n</code></pre>\n\n<p>This leads to an alternative to not have to make an image for the icon, but use text with a symbol font instead to display a simple \"icon\". The following example uses the Wingdings font which contains a floppydisk symbol. This symbol in the font is mapped to the charachter <code><</code>, which has special meaning in XAML, so we have to use the encoded version <code>&lt;</code> instead. This works like a dream! The following shows a floppydisk symbol as an icon on the menu item: </p>\n\n<pre><code><MenuItem Name=\"mnuFileSave\" Header=\"Save\" Command=\"ApplicationCommands.Save\">\n <MenuItem.Icon>\n <Label VerticalAlignment=\"Center\" HorizontalAlignment=\"Center\" \n FontFamily=\"Wingdings\">&lt;</Label>\n </MenuItem.Icon> \n</MenuItem>\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/483/"
]
| I'd like to make some custom MenuHeaders in WPF so I can have (for example), an icon and text in a menu item.
Normally using MenuItems, if you populate the Header field with straight text, you can add an accelerator by using an underscore. eg, \_File
However, if I wanted to put in a UserControl, I believe this function would break, how would I do something similar to the following?
```
<Menu>
<MenuItem>
<MenuItem.Header>
<UserControl>
<Image Source="..." />
<Label Text="_Open" />
</UserControl>
</MenuItem.Header>
</MenuItem>
...
``` | I think the Icon property fits your needs.
However to answer the original question, it is possible to retain the Accelerator functionality when you compose the content of your menuitem. **If you have nested content in a MenuItem you need to define the AccessText property explicitly** like in the first one below. When you use the inline form, this is automagically taken care of.
```
<Menu>
<MenuItem>
<MenuItem.Header>
<StackPanel Orientation="Horizontal">
<Image Source="Images/Open.ico" />
<AccessText>_Open..</AccessText>
</StackPanel>
</MenuItem.Header>
</MenuItem>
<MenuItem Header="_Close" />
</Menu>
``` |
59,465 | <p>By default the webjump hotlist has the following which I use quite often:</p>
<pre><code>M-x webjump RET Google
M-x webjump RET Wikipedia
</code></pre>
<p>How can I add 'Stackoverflow' to my list?</p>
| [
{
"answer_id": 59476,
"author": "Marcel Levy",
"author_id": 676,
"author_profile": "https://Stackoverflow.com/users/676",
"pm_score": 2,
"selected": true,
"text": "<p>Here's some example code in <a href=\"http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el\" rel=\"nofollow noreferrer\">a webjump.el file on a site run by Apple:</a></p>\n\n<pre><code>;; (require 'webjump)\n;; (global-set-key \"\\C-cj\" 'webjump)\n;; (setq webjump-sites\n;; (append '(\n;; (\"My Home Page\" . \"www.someisp.net/users/joebobjr/\")\n;; (\"Pop's Site\" . \"www.joebob-and-son.com/\")\n;; )\n;; webjump-sample-sites))\n</code></pre>\n"
},
{
"answer_id": 81909,
"author": "Chopmo",
"author_id": 13747,
"author_profile": "https://Stackoverflow.com/users/13747",
"pm_score": 2,
"selected": false,
"text": "<p>A general tip for looking up answers to questions like this one: </p>\n\n<ol>\n<li>Look up the help for a relevant function. eg. <strong>C-h f webjump</strong></li>\n<li>In the top line of the help buffer, hit RET on the filename in which the function is defined. This will take you to the function definition. </li>\n<li><strong>M-<</strong> to jump to the beginning of the buffer. </li>\n<li>Read through the documentation for the file. Typically (and in this case) this will include information on how to configure the feature. </li>\n</ol>\n"
},
{
"answer_id": 151984,
"author": "jfm3",
"author_id": 11138,
"author_profile": "https://Stackoverflow.com/users/11138",
"pm_score": 2,
"selected": false,
"text": "<p>You will need to find where you are setting your <code>webjump-sites</code> variable. This is probably your <code>.emacs</code> file. Then you'll need to add a pair to that alist as follows.</p>\n\n<pre><code>(\"stackoverflow\". \"www.stackoverflow.com\")\n</code></pre>\n\n<p>A full example of what to put in your .emacs would be as follows.</p>\n\n<pre><code>(setq webjump-sites\n (append '((\"stackoverflow\" . \"www.stackoverflow.com\"))\n webjump-sample-sites)\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59465",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4872/"
]
| By default the webjump hotlist has the following which I use quite often:
```
M-x webjump RET Google
M-x webjump RET Wikipedia
```
How can I add 'Stackoverflow' to my list? | Here's some example code in [a webjump.el file on a site run by Apple:](http://www.opensource.apple.com/darwinsource/10.0/emacs-39/emacs/lisp/webjump.el)
```
;; (require 'webjump)
;; (global-set-key "\C-cj" 'webjump)
;; (setq webjump-sites
;; (append '(
;; ("My Home Page" . "www.someisp.net/users/joebobjr/")
;; ("Pop's Site" . "www.joebob-and-son.com/")
;; )
;; webjump-sample-sites))
``` |
59,472 | <p>Is there a way (or shortcut) to tell VS 2008 that it cuts a line like this:</p>
<p><strong>Before:</strong></p>
<pre><code>Some Text here
This gets cut
Some Code there
</code></pre>
<p><strong>After:</strong></p>
<pre><code>Some Text here
Some Code there
</code></pre>
<p><strong>What I want:</strong></p>
<pre><code>Some Text here
Some Code there
</code></pre>
<p>PS: I don't want to select the whole line or something like this... only the text I want to cut.</p>
| [
{
"answer_id": 59513,
"author": "Tomas Sedovic",
"author_id": 2239,
"author_profile": "https://Stackoverflow.com/users/2239",
"pm_score": 3,
"selected": true,
"text": "<p>Unless I misunderstood you:<br>\nJust place cursor on the line you want to cut (no selection) and press <kbd>Ctrl</kbd> + <kbd>x</kbd>. That cuts the line (leaving no blanks) and puts the text in the Clipboard. (tested in <em>MS VC# 2008 Express</em> with no additional settings I'm aware of)</p>\n\n<p>Is that what you want?</p>\n"
},
{
"answer_id": 59516,
"author": "Nathan Jones",
"author_id": 5848,
"author_profile": "https://Stackoverflow.com/users/5848",
"pm_score": 0,
"selected": false,
"text": "<p>Don't select anything, just hit <kbd>ctrl</kbd>+<kbd>x</kbd> when the cursor is on the line.</p>\n"
},
{
"answer_id": 59717,
"author": "Eric Schoonover",
"author_id": 3957,
"author_profile": "https://Stackoverflow.com/users/3957",
"pm_score": 1,
"selected": false,
"text": "<p><kbd>Shift</kbd>+<kbd>Delete</kbd> also works.\nSelect a line and hit Shift-Delete it will remove the line and place that line in your clipboard.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6143/"
]
| Is there a way (or shortcut) to tell VS 2008 that it cuts a line like this:
**Before:**
```
Some Text here
This gets cut
Some Code there
```
**After:**
```
Some Text here
Some Code there
```
**What I want:**
```
Some Text here
Some Code there
```
PS: I don't want to select the whole line or something like this... only the text I want to cut. | Unless I misunderstood you:
Just place cursor on the line you want to cut (no selection) and press `Ctrl` + `x`. That cuts the line (leaving no blanks) and puts the text in the Clipboard. (tested in *MS VC# 2008 Express* with no additional settings I'm aware of)
Is that what you want? |
59,483 | <pre><code>1167 ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1);
(gdb) n
1168 if (!ptr) {
(gdb) print ptr
$1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) print &cwd
$2 = (char (*)[3500]) 0xbff2d96c
(gdb) print strlen(cwd)
$3 = 36
(gdb) print "%s",cwd
$4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' <repeats 912 times>, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"...
(gdb) print "%s", ptr
$5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) Quit
</code></pre>
<p>Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd...</p>
<p>[edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid]</p>
| [
{
"answer_id": 59509,
"author": "oliver",
"author_id": 2148773,
"author_profile": "https://Stackoverflow.com/users/2148773",
"pm_score": 1,
"selected": false,
"text": "<p>That <code>ptr</code> is displayed as nicely-formatted string and <code>cwd</code> as \"byte buffer\" is probably specific to gdb. In any case it shouldn't affect your application; according to <code>man 3 getcwd</code>, <code>ptr</code> should point to <code>cwd</code> (or it should be NULL if an error occurred).\nCan you use <code>ptr</code> without crashing the program?</p>\n"
},
{
"answer_id": 59514,
"author": "Craig H",
"author_id": 2328,
"author_profile": "https://Stackoverflow.com/users/2328",
"pm_score": 0,
"selected": false,
"text": "<p>What type is cwd? The above code snippet doesn't tell us that. It could be that ptr being a void* is treated differently by gdb.</p>\n"
},
{
"answer_id": 59517,
"author": "mweerden",
"author_id": 4285,
"author_profile": "https://Stackoverflow.com/users/4285",
"pm_score": 3,
"selected": true,
"text": "<p>The reason that <code>cwd</code> is printed differently in <code>gdb</code> is because <code>gdb</code> knows that <code>ptr</code> is a <code>char *</code> (I guess) and that <code>cwd</code> is an array of length <code>3500</code> (as shown in your output). So when printing <code>ptr</code> it prints the pointer value (and as a service also the string it points to) and when printing <code>cwd</code> it prints the <em>whole</em> array.</p>\n\n<p>I don't see any reason why using <code>cwd</code> instead of <code>ptr</code> would lead to problems, but I would need to see some code to be sure.</p>\n"
},
{
"answer_id": 59553,
"author": "Eric Hansander",
"author_id": 5039,
"author_profile": "https://Stackoverflow.com/users/5039",
"pm_score": 3,
"selected": false,
"text": "<p>I agree with mweerden. Trying something I believe is similar to your code, I get:</p>\n\n<pre><code>(gdb) print cwd\n$1 = \"/media\", '\\0' <repeats 782 times>, \"\\016���\" ...\n(gdb) print (char*) cwd\n$2 = 0xbfc8eb84 \"/media\"\n</code></pre>\n\n<p>from gdb, so it seems that since <code>cwd</code> was defined as <code>char cwd[3500]</code>, gdb prints the entire array, while if you tell gdb to interpret it as a <code>char*</code>, it will work as you expect. If your application crashes, I would assume it is because of something else.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59483",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5330/"
]
| ```
1167 ptr = (void*)getcwd(cwd, MAX_PATH_LENGTH-1);
(gdb) n
1168 if (!ptr) {
(gdb) print ptr
$1 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) print &cwd
$2 = (char (*)[3500]) 0xbff2d96c
(gdb) print strlen(cwd)
$3 = 36
(gdb) print "%s",cwd
$4 = "/media/MMC-SD/partition1/aaaaaaaaaaa", '\0' <repeats 912 times>, "��O�001\000\000\000\000��027\000\000\000�3����EL鷠3�000��027\000\000\000\000\000\000\000\027\000\000\000\000��/�027\000\000\000�3����N����\230���鷠3�000��027\000\000\000\000\000\000\000��000\000\000\000\001\000\000\000��M鷠3����\000\000\000\000.\231�027��w\005\b\001\000"...
(gdb) print "%s", ptr
$5 = 0xbff2d96c "/media/MMC-SD/partition1/aaaaaaaaaaa"
(gdb) Quit
```
Why is ptr printing the string correctly but cwd not; this also affects the program and it crashes if I try to use the cwd...
[edit: turns out that crash was caused by a stupid buffer overflow on this var... grr...not gdb, but the print question was still valid] | The reason that `cwd` is printed differently in `gdb` is because `gdb` knows that `ptr` is a `char *` (I guess) and that `cwd` is an array of length `3500` (as shown in your output). So when printing `ptr` it prints the pointer value (and as a service also the string it points to) and when printing `cwd` it prints the *whole* array.
I don't see any reason why using `cwd` instead of `ptr` would lead to problems, but I would need to see some code to be sure. |
59,515 | <p>I am new to all the anonymous features and need some help. I have gotten the following to work:</p>
<pre><code>public void FakeSaveWithMessage(Transaction t)
{
t.Message = "I drink goats blood";
}
public delegate void FakeSave(Transaction t);
public void SampleTestFunction()
{
Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage));
}
</code></pre>
<p>But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried:</p>
<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; });
</code></pre>
<p>and</p>
<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; });
</code></pre>
<p>but these give me</p>
<blockquote>
<p>Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type** compile errors.</p>
</blockquote>
<p>What am I doing wrong?</p>
<hr>
<p>Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:</p>
<pre><code>public delegate void FakeSave(Transaction t);
Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; }));
</code></pre>
| [
{
"answer_id": 59531,
"author": "Chris Marasti-Georg",
"author_id": 96,
"author_profile": "https://Stackoverflow.com/users/96",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like:</p>\n\n<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do(new EventHandler(delegate(Transaction t2) { t2.CheckInInfo.CheckInMessage = \"I drink goats blood\"; }));\n</code></pre>\n\n<p>Note the added EventHandler around the delegate.</p>\n\n<p>EDIT: might not work since the function signatures of EventHandler and the delegate are not the same... The solution you added to the bottom of your question may be the only way.</p>\n\n<p>Alternately, you could create a generic delegate type:</p>\n\n<pre><code>public delegate void UnitTestingDelegate<T>(T thing);\n</code></pre>\n\n<p>So that the delegate is not Transaction specific.</p>\n"
},
{
"answer_id": 59551,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 6,
"selected": true,
"text": "<p>That's a well known error message. Check the link below for a more detailed discussion.</p>\n\n<p><a href=\"http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/\" rel=\"noreferrer\">http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/</a> </p>\n\n<p>Basically you just need to put a cast in front of your anonymous delegate (your lambda expression).</p>\n\n<p>In case the link ever goes down, here is a copy of the post: </p>\n\n<blockquote>\n <p><strong>They are Anonymous Methods, not\n Anonymous Delegates.</strong><br>\n Posted on December 22, 2007 by staceyw1 </p>\n \n <p>It is not just a talking point because\n we want to be difficult. It helps us\n reason about what exactly is going on.\n To be clear, there is *no such thing\n as an anonymous delegate. They don’t\n exist (not yet). They are \"Anonymous\n Methods\" – period. It matters in how\n we think of them and how we talk about\n them. Lets take a look at the\n anonymous method statement \"delegate()\n {…}\". This is actually two different\n operations and when we think of it\n this way, we will never be confused\n again. The first thing the compiler\n does is create the anonymous method\n under the covers using the inferred\n delegate signature as the method\n signature. It is not correct to say\n the method is \"unnamed\" because it\n does have a name and the compiler\n assigns it. It is just hidden from\n normal view. The next thing it does\n is create a delegate object of the\n required type to wrap the method. This\n is called delegate inference and can\n be the source of this confusion. For\n this to work, the compiler must be\n able to figure out (i.e. infer) what\n delegate type it will create. It has\n to be a known concrete type. Let\n write some code to see why.</p>\n</blockquote>\n\n<pre><code>private void MyMethod()\n{\n}\n</code></pre>\n\n<blockquote>\n <p><strong>Does not compile:</strong> </p>\n</blockquote>\n\n<pre><code>1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type\n2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’\n3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’\n</code></pre>\n\n<blockquote>\n <p>Line 1 does not compile because the\n compiler can not infer any delegate\n type. It can plainly see the signature\n we desire, but there is no concrete\n delegate type the compiler can see. \n It could create an anonymous type of\n type delegate for us, but it does not\n work like that. Line 2 does not\n compile for a similar reason. Even\n though the compiler knows the method\n signature, we are not giving it a\n delegate type and it is not just going\n to pick one that would happen to work\n (not what side effects that could\n have). Line 3 does not work because\n we purposely mismatched the method\n signature with a delegate having a\n different signature (as WaitCallback\n takes and object).</p>\n \n <p><strong>Compiles:</strong> </p>\n</blockquote>\n\n<pre><code>4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature.\n5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4.\n6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned.\n</code></pre>\n\n<blockquote>\n <p>In contrast, these work. Line 1 works\n because we tell the compiler what\n delegate type to use and they match,\n so it works. Line 5 works for the\n same reason. Note we used the special\n form of \"delegate\" without the parens.\n The compiler infers the method\n signature from the cast and creates\n the anonymous method with the same\n signature as the inferred delegate\n type. Line 6 works because the\n MyMethod() and Action use same\n signature.</p>\n \n <p>I hope this helps.</p>\n \n <p>Also see:\n <a href=\"http://msdn.microsoft.com/msdnmag/issues/04/05/C20/\" rel=\"noreferrer\">http://msdn.microsoft.com/msdnmag/issues/04/05/C20/</a></p>\n</blockquote>\n"
},
{
"answer_id": 59568,
"author": "hwiechers",
"author_id": 5883,
"author_profile": "https://Stackoverflow.com/users/5883",
"pm_score": 2,
"selected": false,
"text": "<p>What Mark said.</p>\n\n<p>The problem is that Do takes a Delegate parameter. The compiler can't convert the anonymous methods to Delegate, only a \"delegate type\" i.e. a concrete type derived from Delegate.</p>\n\n<p>If that Do function had took Action<>, Action<,> ... etc. overloads, you wouldn't need the cast.</p>\n"
},
{
"answer_id": 59611,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 1,
"selected": false,
"text": "<p>The problem is not with your delegate definition, it's that the parameter of the Do() method is of type System.Delegate, and the compiler generated delegate type (FakeSave) does not implicitly convert to System.Delegate.</p>\n\n<p>Try adding a cast in front of your anonymous delegate:</p>\n\n<pre><code>Expect.Call(delegate { _dao.Save(t); }).Do((Delegate)delegate { t.Message = \"I drink goats blood\"; });\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59515",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
]
| I am new to all the anonymous features and need some help. I have gotten the following to work:
```
public void FakeSaveWithMessage(Transaction t)
{
t.Message = "I drink goats blood";
}
public delegate void FakeSave(Transaction t);
public void SampleTestFunction()
{
Expect.Call(delegate { _dao.Save(t); }).Do(new FakeSave(FakeSaveWithMessage));
}
```
But this is totally ugly and I would like to have the inside of the Do to be an anonymous method or even a lambda if it is possible. I tried:
```
Expect.Call(delegate { _dao.Save(t); }).Do(delegate(Transaction t2) { t2.Message = "I drink goats blood"; });
```
and
```
Expect.Call(delegate { _dao.Save(t); }).Do(delegate { t.Message = "I drink goats blood"; });
```
but these give me
>
> Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type\*\* compile errors.
>
>
>
What am I doing wrong?
---
Because of what Mark Ingram posted, seems like the best answer, though nobody's explicitly said it, is to do this:
```
public delegate void FakeSave(Transaction t);
Expect.Call(delegate { _dao.Save(t); }).Do( new FakeSave(delegate(Transaction t2) { t.Message = expected_msg; }));
``` | That's a well known error message. Check the link below for a more detailed discussion.
<http://staceyw1.wordpress.com/2007/12/22/they-are-anonymous-methods-not-anonymous-delegates/>
Basically you just need to put a cast in front of your anonymous delegate (your lambda expression).
In case the link ever goes down, here is a copy of the post:
>
> **They are Anonymous Methods, not
> Anonymous Delegates.**
>
> Posted on December 22, 2007 by staceyw1
>
>
> It is not just a talking point because
> we want to be difficult. It helps us
> reason about what exactly is going on.
> To be clear, there is \*no such thing
> as an anonymous delegate. They don’t
> exist (not yet). They are "Anonymous
> Methods" – period. It matters in how
> we think of them and how we talk about
> them. Lets take a look at the
> anonymous method statement "delegate()
> {…}". This is actually two different
> operations and when we think of it
> this way, we will never be confused
> again. The first thing the compiler
> does is create the anonymous method
> under the covers using the inferred
> delegate signature as the method
> signature. It is not correct to say
> the method is "unnamed" because it
> does have a name and the compiler
> assigns it. It is just hidden from
> normal view. The next thing it does
> is create a delegate object of the
> required type to wrap the method. This
> is called delegate inference and can
> be the source of this confusion. For
> this to work, the compiler must be
> able to figure out (i.e. infer) what
> delegate type it will create. It has
> to be a known concrete type. Let
> write some code to see why.
>
>
>
```
private void MyMethod()
{
}
```
>
> **Does not compile:**
>
>
>
```
1) Delegate d = delegate() { }; // Cannot convert anonymous method to type ‘System.Delegate’ because it is not a delegate type
2) Delegate d2 = MyMethod; // Cannot convert method group ‘MyMethod’ to non-delegate type ‘System.Delegate’
3) Delegate d3 = (WaitCallback)MyMethod; // No overload for ‘MyMethod’ matches delegate ‘System.Threading.WaitCallback’
```
>
> Line 1 does not compile because the
> compiler can not infer any delegate
> type. It can plainly see the signature
> we desire, but there is no concrete
> delegate type the compiler can see.
> It could create an anonymous type of
> type delegate for us, but it does not
> work like that. Line 2 does not
> compile for a similar reason. Even
> though the compiler knows the method
> signature, we are not giving it a
> delegate type and it is not just going
> to pick one that would happen to work
> (not what side effects that could
> have). Line 3 does not work because
> we purposely mismatched the method
> signature with a delegate having a
> different signature (as WaitCallback
> takes and object).
>
>
> **Compiles:**
>
>
>
```
4) Delegate d4 = (MethodInvoker)MyMethod; // Works because we cast to a delegate type of the same signature.
5) Delegate d5 = (Action)delegate { }; // Works for same reason as d4.
6) Action d6 = MyMethod; // Delegate inference at work here. New Action delegate is created and assigned.
```
>
> In contrast, these work. Line 1 works
> because we tell the compiler what
> delegate type to use and they match,
> so it works. Line 5 works for the
> same reason. Note we used the special
> form of "delegate" without the parens.
> The compiler infers the method
> signature from the cast and creates
> the anonymous method with the same
> signature as the inferred delegate
> type. Line 6 works because the
> MyMethod() and Action use same
> signature.
>
>
> I hope this helps.
>
>
> Also see:
> <http://msdn.microsoft.com/msdnmag/issues/04/05/C20/>
>
>
> |
59,544 | <p>I have the following tables, the <code>groups</code> table which contains hierarchically ordered groups and <code>group_member</code> which stores which groups a user belongs to. </p>
<pre><code>groups
---------
id
parent_id
name
group_member
---------
id
group_id
user_id
ID PARENT_ID NAME
---------------------------
1 NULL Cerebra
2 1 CATS
3 2 CATS 2.0
4 1 Cerepedia
5 4 Cerepedia 2.0
6 1 CMS
ID GROUP_ID USER_ID
---------------------------
1 1 3
2 1 4
3 1 5
4 2 7
5 2 6
6 4 6
7 5 12
8 4 9
9 1 10
</code></pre>
<p>I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data: </p>
<pre><code>USER VISIBLE_GROUPS
9 4, 5
3 1,2,4,5,6
12 5
</code></pre>
<p>I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL. </p>
| [
{
"answer_id": 59594,
"author": "Prestaul",
"author_id": 5628,
"author_profile": "https://Stackoverflow.com/users/5628",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that this can be accomplished without using recursion. You can accomplish it with with a single stored procedure using mySQL, but recursion is not allowed in stored procedures by default. <a href=\"http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html\" rel=\"nofollow noreferrer\">This article</a> has information about how to enable recursion. I'm not certain about how much impact this would have on performance verses the multiple query approach. mySQL may do some optimization of stored procedures, but otherwise I would expect the performance to be similar.</p>\n"
},
{
"answer_id": 59632,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>Didn't know if you had a Users table, so I get the list via the User_ID's stored in the Group_Member table...</p>\n\n<pre><code>SELECT GroupUsers.User_ID,\n (\n SELECT \n STUFF((SELECT ',' + \n Cast(Group_ID As Varchar(10))\n FROM Group_Member Member (nolock) \n WHERE Member.User_ID=GroupUsers.User_ID\n FOR XML PATH('')),1,1,'') \n ) As Groups\nFROM (SELECT User_ID FROM Group_Member GROUP BY User_ID) GroupUsers\n</code></pre>\n\n<p>That returns:</p>\n\n<pre><code>User_ID Groups\n3 1\n4 1\n5 1\n6 2,4\n7 2\n9 4\n10 1\n12 5\n</code></pre>\n\n<p>Which seems right according to the data in your table. But doesn't match up with your expected value list (e.g. User 9 is only in one group in your table data but you show it in the results as belonging to two)</p>\n\n<p>EDIT: Dang. Just noticed that you're using MySQL. My solution was for SQL Server. Sorry.</p>\n\n<p>-- Kevin Fairchild</p>\n"
},
{
"answer_id": 59765,
"author": "Hank Gay",
"author_id": 4203,
"author_profile": "https://Stackoverflow.com/users/4203",
"pm_score": -1,
"selected": false,
"text": "<p><del>There's no way to do this in the SQL standard, but you can usually find vendor-specific extensions, e.g., <code>CONNECT BY</code> in Oracle.</del></p>\n\n<p>UPDATE: As the comments point out, this was added in SQL 99.</p>\n"
},
{
"answer_id": 59767,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 3,
"selected": false,
"text": "<p>Two things come to mind:</p>\n\n<p><strong>1 -</strong> You can repeatedly outer-join the table to itself to recursively walk up your tree, as in:</p>\n\n<pre><code>SELECT *\nFROM\n MY_GROUPS MG1\n ,MY_GROUPS MG2\n ,MY_GROUPS MG3\n ,MY_GROUPS MG4\n ,MY_GROUPS MG5\n ,MY_GROUP_MEMBERS MGM\nWHERE MG1.PARENT_ID = MG2.UNIQID (+)\n AND MG1.UNIQID = MGM.GROUP_ID (+)\n AND MG2.PARENT_ID = MG3.UNIQID (+)\n AND MG3.PARENT_ID = MG4.UNIQID (+)\n AND MG4.PARENT_ID = MG5.UNIQID (+)\n AND MGM.USER_ID = 9\n</code></pre>\n\n<p>That's gonna give you results like this:</p>\n\n<pre><code>UNIQID PARENT_ID NAME UNIQID_1 PARENT_ID_1 NAME_1 UNIQID_2 PARENT_ID_2 NAME_2 UNIQID_3 PARENT_ID_3 NAME_3 UNIQID_4 PARENT_ID_4 NAME_4 UNIQID_5 GROUP_ID USER_ID\n4 2 Cerepedia 2 1 CATS 1 null Cerebra null null null null null null 8 4 9\n</code></pre>\n\n<p>The limit here is that you must add a new join for each \"level\" you want to walk up the tree. If your tree has less than, say, 20 levels, then you could probably get away with it by creating a view that showed 20 levels from every user.</p>\n\n<p><strong>2 -</strong> The only other approach that I know of is to create a recursive database function, and call that from code. You'll still have some lookup overhead that way (i.e., your # of queries will still be equal to the # of levels you are walking on the tree), but overall it should be faster since it's all taking place within the database.</p>\n\n<p>I'm not sure about MySql, but in Oracle, such a function would be similar to this one (you'll have to change the table and field names; I'm just copying something I did in the past):</p>\n\n<pre><code>CREATE OR REPLACE FUNCTION GoUpLevel(WO_ID INTEGER, UPLEVEL INTEGER) RETURN INTEGER\nIS\nBEGIN\n DECLARE\n iResult INTEGER;\n iParent INTEGER;\nBEGIN\n IF UPLEVEL <= 0 THEN\n iResult := WO_ID;\n ELSE\n SELECT PARENT_ID\n INTO iParent\n FROM WOTREE\n WHERE ID = WO_ID; \n iResult := GoUpLevel(iParent,UPLEVEL-1); --recursive\n END;\n RETURN iResult;\n EXCEPTION WHEN NO_DATA_FOUND THEN\n RETURN NULL;\n END;\nEND GoUpLevel;\n/\n</code></pre>\n"
},
{
"answer_id": 60588,
"author": "Paul Kroll",
"author_id": 6280,
"author_profile": "https://Stackoverflow.com/users/6280",
"pm_score": 2,
"selected": false,
"text": "<p>Joe Cleko's books \"SQL for Smarties\" and \"Trees and Hierarchies in SQL for Smarties\" describe methods that avoid recursion entirely, by using nested sets. That complicates the updating, but makes other queries (that would normally need recursion) comparatively straightforward. There are <a href=\"http://www.dbmsmag.com/9604d06.html\" rel=\"nofollow noreferrer\">some examples in this article</a> written by Joe back in 1996. </p>\n"
},
{
"answer_id": 60974,
"author": "Grzegorz Gierlik",
"author_id": 1483,
"author_profile": "https://Stackoverflow.com/users/1483",
"pm_score": 0,
"selected": false,
"text": "<p>There was already similar <a href=\"https://stackoverflow.com/questions/20426/how-to-maintain-a-recursive-invariant-in-a-mysql-database\">question</a> raised.</p>\n\n<p>Here is my answer (a bit edited):</p>\n\n<p>I am not sure I understand correctly your question, but this could work <a href=\"http://www.depesz.com/index.php/2008/04/11/my-take-on-trees-in-sql/\" rel=\"nofollow noreferrer\">My take on trees in SQL</a>.</p>\n\n<p>Linked post described method of storing tree in database -- PostgreSQL in that case -- but the method is clear enough, so it can be adopted easily for any database.</p>\n\n<p>With this method you can easy update all the nodes depend on modified node K with about N simple SELECTs queries where N is distance of K from root node.</p>\n\n<p>Good Luck!</p>\n"
},
{
"answer_id": 1046311,
"author": "MSpreij",
"author_id": 126584,
"author_profile": "https://Stackoverflow.com/users/126584",
"pm_score": 0,
"selected": false,
"text": "<p>I don't remember which SO question I found the link under, but <a href=\"http://www.sitepoint.com/article/hierarchical-data-database/1/\" rel=\"nofollow noreferrer\">this article on sitepoint.com</a> (second page) shows another way of storing hierarchical trees in a table that makes it easy to find all child nodes, or the path to the top, things like that. Good explanation with example code.</p>\n\n<hr>\n\n<p>PS. Newish to StackOverflow, is the above ok as an answer, or should it really have been a comment on the question since it's just a pointer to a different solution (not exactly answering the question itself)?</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59544",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
| I have the following tables, the `groups` table which contains hierarchically ordered groups and `group_member` which stores which groups a user belongs to.
```
groups
---------
id
parent_id
name
group_member
---------
id
group_id
user_id
ID PARENT_ID NAME
---------------------------
1 NULL Cerebra
2 1 CATS
3 2 CATS 2.0
4 1 Cerepedia
5 4 Cerepedia 2.0
6 1 CMS
ID GROUP_ID USER_ID
---------------------------
1 1 3
2 1 4
3 1 5
4 2 7
5 2 6
6 4 6
7 5 12
8 4 9
9 1 10
```
I want to retrieve the visible groups for a given user. That it is to say groups a user belongs to and children of these groups. For example, with the above data:
```
USER VISIBLE_GROUPS
9 4, 5
3 1,2,4,5,6
12 5
```
I am getting these values using recursion and several database queries. But I would like to know if it is possible to do this with a single SQL query to improve my app performance. I am using MySQL. | Two things come to mind:
**1 -** You can repeatedly outer-join the table to itself to recursively walk up your tree, as in:
```
SELECT *
FROM
MY_GROUPS MG1
,MY_GROUPS MG2
,MY_GROUPS MG3
,MY_GROUPS MG4
,MY_GROUPS MG5
,MY_GROUP_MEMBERS MGM
WHERE MG1.PARENT_ID = MG2.UNIQID (+)
AND MG1.UNIQID = MGM.GROUP_ID (+)
AND MG2.PARENT_ID = MG3.UNIQID (+)
AND MG3.PARENT_ID = MG4.UNIQID (+)
AND MG4.PARENT_ID = MG5.UNIQID (+)
AND MGM.USER_ID = 9
```
That's gonna give you results like this:
```
UNIQID PARENT_ID NAME UNIQID_1 PARENT_ID_1 NAME_1 UNIQID_2 PARENT_ID_2 NAME_2 UNIQID_3 PARENT_ID_3 NAME_3 UNIQID_4 PARENT_ID_4 NAME_4 UNIQID_5 GROUP_ID USER_ID
4 2 Cerepedia 2 1 CATS 1 null Cerebra null null null null null null 8 4 9
```
The limit here is that you must add a new join for each "level" you want to walk up the tree. If your tree has less than, say, 20 levels, then you could probably get away with it by creating a view that showed 20 levels from every user.
**2 -** The only other approach that I know of is to create a recursive database function, and call that from code. You'll still have some lookup overhead that way (i.e., your # of queries will still be equal to the # of levels you are walking on the tree), but overall it should be faster since it's all taking place within the database.
I'm not sure about MySql, but in Oracle, such a function would be similar to this one (you'll have to change the table and field names; I'm just copying something I did in the past):
```
CREATE OR REPLACE FUNCTION GoUpLevel(WO_ID INTEGER, UPLEVEL INTEGER) RETURN INTEGER
IS
BEGIN
DECLARE
iResult INTEGER;
iParent INTEGER;
BEGIN
IF UPLEVEL <= 0 THEN
iResult := WO_ID;
ELSE
SELECT PARENT_ID
INTO iParent
FROM WOTREE
WHERE ID = WO_ID;
iResult := GoUpLevel(iParent,UPLEVEL-1); --recursive
END;
RETURN iResult;
EXCEPTION WHEN NO_DATA_FOUND THEN
RETURN NULL;
END;
END GoUpLevel;
/
``` |
59,557 | <p>is there an easy way to transform HTML into markdown with JAVA?</p>
<p>I am currently using the Java <strong><a href="http://code.google.com/p/markdownj/" rel="noreferrer">MarkdownJ</a></strong> library to transform markdown to html.</p>
<pre><code>import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
MarkdownProcessor markdown_processor = new MarkdownProcessor();
return markdown_processor.markdown(markdown);
}
public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}
</code></pre>
| [
{
"answer_id": 178278,
"author": "myabc",
"author_id": 3789,
"author_profile": "https://Stackoverflow.com/users/3789",
"pm_score": 2,
"selected": false,
"text": "<p>I am working on the same issue, and experimenting with a couple different techniques.</p>\n\n<p>The answer above could work. You could use the <a href=\"http://jtidy.sourceforge.net/\" rel=\"nofollow noreferrer\">jTidy library</a> to do the initial cleanup work and convert from HTML to XHTML. You use the <a href=\"http://www.lowerelement.com/Geekery/XML/XHTML-to-Markdown.html\" rel=\"nofollow noreferrer\">XSLT stylesheet</a> linked above.</p>\n\n<p>Unfortunately there is no library that has a one-stop function to do this in Java. You could try using the Python script <a href=\"http://www.aaronsw.com/2002/html2text/\" rel=\"nofollow noreferrer\">html2text</a> with Jython, but I haven't yet tried this!</p>\n"
},
{
"answer_id": 741062,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>if you are using WMD editor and want to get the markdown code on the server side, just use these options before loading the <code>wmd.js</code> script:</p>\n\n<pre><code>wmd_options = {\n // format sent to the server. can also be \"HTML\"\n output: \"Markdown\",\n\n // line wrapping length for lists, blockquotes, etc.\n lineLength: 40,\n\n // toolbar buttons. Undo and redo get appended automatically.\n buttons: \"bold italic | link blockquote code image | ol ul heading hr\",\n\n // option to automatically add WMD to the first textarea found.\n autostart: true\n };\n</code></pre>\n"
},
{
"answer_id": 62105480,
"author": "Gabriel Furstenheim",
"author_id": 1536133,
"author_profile": "https://Stackoverflow.com/users/1536133",
"pm_score": 4,
"selected": false,
"text": "<p>There is a great library for JS called <a href=\"https://github.com/domchristie/turndown\" rel=\"nofollow noreferrer\">Turndown</a>, you can try it online <a href=\"https://mixmark-io.github.io/turndown/\" rel=\"nofollow noreferrer\">here</a>. It works for htmls that the accepted answer errors out.</p>\n<p>I needed it for Java (as the question), so I ported it. The library for Java is called <a href=\"https://github.com/furstenheim/copy-down\" rel=\"nofollow noreferrer\">CopyDown</a>, it has the same test suite as Turndown and I've tried it with real examples that the accepted answer was throwing errors.</p>\n<p>To install with gradle:</p>\n<pre><code>dependencies {\n compile 'io.github.furstenheim:copy_down:1.0'\n}\n</code></pre>\n<p>Then to use it:</p>\n<pre class=\"lang-java prettyprint-override\"><code>CopyDown converter = new CopyDown();\nString myHtml = "<h1>Some title</h1><div>Some html<p>Another paragraph</p></div>";\nString markdown = converter.convert(myHtml);\nSystem.out.println(markdown);\n> Some title\\n==========\\n\\nSome html\\n\\nAnother paragraph\\n\n</code></pre>\n<p>PS. It has MIT license</p>\n"
},
{
"answer_id": 70212129,
"author": "Mahozad",
"author_id": 8583692,
"author_profile": "https://Stackoverflow.com/users/8583692",
"pm_score": 0,
"selected": false,
"text": "<p>There is a Haskell library called <a href=\"https://github.com/jgm/pandoc\" rel=\"nofollow noreferrer\">pandoc</a> that can convert between most markup formats.<br />\nAlthough it is not a Java library, it can be <a href=\"https://stackoverflow.com/a/8496537/8583692\">used through its CLI in Java</a>.</p>\n<p>You can get and <a href=\"https://github.com/jgm/pandoc/releases/latest\" rel=\"nofollow noreferrer\">install the latest version from here</a>. Read the <a href=\"https://pandoc.org/getting-started.html\" rel=\"nofollow noreferrer\">getting started guides here</a>.</p>\n<pre class=\"lang-java prettyprint-override\"><code>var command = "pandoc --to=markdown_strict --output=result.md input.html";\nvar pandoc = new ProcessBuilder()\n .command(command.split(" "))\n .directory(new File(".")) // Working directory\n .start();\npandoc.waitFor();\n// The output result.md will be created in the working directory\n</code></pre>\n<p>This tool can also be <a href=\"https://github.com/pandoc/pandoc-action-example\" rel=\"nofollow noreferrer\">used in GitHub Actions workflows</a>.</p>\n"
},
{
"answer_id": 72139380,
"author": "Fabian Sponholz",
"author_id": 19051614,
"author_profile": "https://Stackoverflow.com/users/19051614",
"pm_score": 2,
"selected": false,
"text": "<p>There is a Java Library called <a href=\"https://github.com/vsch/flexmark-java\" rel=\"nofollow noreferrer\">flexmark</a> which has such a feature.\nMaven Dependency:</p>\n<pre><code><dependency>\n <groupId>com.vladsch.flexmark</groupId>\n <artifactId>flexmark-html2md-converter</artifactId>\n <version>0.64.0</version>\n</dependency>\n</code></pre>\n<p>Using the class <code>com.vladsch.flexmark.html2md.converter.FlexmarkHtmlConverter</code> you can convert an HTML String to a Markdown String in one line like this:</p>\n<pre><code>String md = FlexmarkHtmlConverter.builder().build().convert(html);\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59557",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
]
| is there an easy way to transform HTML into markdown with JAVA?
I am currently using the Java **[MarkdownJ](http://code.google.com/p/markdownj/)** library to transform markdown to html.
```
import com.petebevin.markdown.MarkdownProcessor;
...
public static String getHTML(String markdown) {
MarkdownProcessor markdown_processor = new MarkdownProcessor();
return markdown_processor.markdown(markdown);
}
public static String getMarkdown(String html) {
/* TODO Ask stackoverflow */
}
``` | There is a great library for JS called [Turndown](https://github.com/domchristie/turndown), you can try it online [here](https://mixmark-io.github.io/turndown/). It works for htmls that the accepted answer errors out.
I needed it for Java (as the question), so I ported it. The library for Java is called [CopyDown](https://github.com/furstenheim/copy-down), it has the same test suite as Turndown and I've tried it with real examples that the accepted answer was throwing errors.
To install with gradle:
```
dependencies {
compile 'io.github.furstenheim:copy_down:1.0'
}
```
Then to use it:
```java
CopyDown converter = new CopyDown();
String myHtml = "<h1>Some title</h1><div>Some html<p>Another paragraph</p></div>";
String markdown = converter.convert(myHtml);
System.out.println(markdown);
> Some title\n==========\n\nSome html\n\nAnother paragraph\n
```
PS. It has MIT license |
59,599 | <p>I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with:</p>
<pre><code>if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...
</code></pre>
<p>...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead:</p>
<pre><code>dim myField
if isNull(Rs("myField")) then
myField = 0
else
myField = Rs("myField")
end if
if myField <> 0 then
...
</code></pre>
<p>Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript?</p>
| [
{
"answer_id": 59606,
"author": "busse",
"author_id": 5702,
"author_profile": "https://Stackoverflow.com/users/5702",
"pm_score": 3,
"selected": false,
"text": "<p>Nested IFs (only slightly less verbose):</p>\n\n<pre><code>if not isNull(Rs(\"myField\")) Then\n if Rs(\"myField\") <> 0 then\n</code></pre>\n"
},
{
"answer_id": 59615,
"author": "Danimal",
"author_id": 2757,
"author_profile": "https://Stackoverflow.com/users/2757",
"pm_score": 0,
"selected": false,
"text": "<p>Would that there were, my friend -- TernaryOp is your only hope. </p>\n"
},
{
"answer_id": 59618,
"author": "oglester",
"author_id": 2017,
"author_profile": "https://Stackoverflow.com/users/2017",
"pm_score": 4,
"selected": true,
"text": "<p>Maybe not the best way, but it certainly works... Also, if you are in vb6 or .net, you can have different methods that cast to proper type too.</p>\n\n<pre><code>if cint( getVal( rs(\"blah\"), \"\" ) )<> 0 then\n 'do something\nend if\n\n\nfunction getVal( v, replacementVal )\n if v is nothing then\n getVal = replacementVal\n else\n getVal = v\n end if\nend function\n</code></pre>\n"
},
{
"answer_id": 59631,
"author": "Marshall",
"author_id": 1302,
"author_profile": "https://Stackoverflow.com/users/1302",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah it's not the best solution but what we use is something like this</p>\n\n<pre><code>function ReplaceNull(s)\n if IsNull(s) or s = \"\" then\n ReplaceNull = \"&nbsp;\"\n else\n ReplaceNull = s\n end if\nend function\n</code></pre>\n"
},
{
"answer_id": 59693,
"author": "dewde",
"author_id": 2640,
"author_profile": "https://Stackoverflow.com/users/2640",
"pm_score": 3,
"selected": false,
"text": "<p>I always used Select Case statements to short circuit logic in VB. Something like..</p>\n\n<pre><code>Select Case True\n\nCase isNull(Rs(\"myField\"))\n\n myField = 0\n\nCase (Rs(\"myField\") <> 0)\n\n myField = Rs(\"myField\")\n\nCase Else\n\n myField = -1 \n\nEnd Select\n</code></pre>\n\n<p>My syntax may be off, been a while. If the first case pops, everything else is ignored.</p>\n"
},
{
"answer_id": 139545,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 0,
"selected": false,
"text": "<p>Two options come to mind:</p>\n\n<p>1) use <code>len()</code> or <code>lenb()</code> to discover if there is any data in the variable:</p>\n\n<pre><code>if not lenb(rs(\"myField\"))=0 then...\n</code></pre>\n\n<p>2) use a function that returns a boolean:</p>\n\n<pre><code>if not isNothing(rs(\"myField\")) then...\n</code></pre>\n\n<p>where <code>isNothing()</code> is a function like so:</p>\n\n<pre><code>function isNothing(vInput)\n isNothing = false : vInput = trim(vInput)\n if vartype(vInput)=0 or isEmpty(vInput) or isNull(vInput) or lenb(vInput)=0 then isNothing = true : end if \nend function\n</code></pre>\n"
},
{
"answer_id": 139572,
"author": "Cirieno",
"author_id": 17615,
"author_profile": "https://Stackoverflow.com/users/17615",
"pm_score": 2,
"selected": false,
"text": "<p>Or perhaps I got the wrong end of the question. Did you mean something like <code>iIf()</code> in VB? This works for me:</p>\n\n<pre><code>myField = returnIf(isNothing(rs(\"myField\")), 0, rs(\"myField\"))\n</code></pre>\n\n<p>where <code>returnIf()</code> is a function like so:</p>\n\n<pre><code>function returnIf(uExpression, uTrue, uFalse)\n if (uExpression = true) then returnIf = uTrue else returnIf = uFalse : end if\nend function\n</code></pre>\n"
},
{
"answer_id": 22572341,
"author": "Bond",
"author_id": 2237785,
"author_profile": "https://Stackoverflow.com/users/2237785",
"pm_score": 2,
"selected": false,
"text": "<p>If you write it as two inline <code>IF</code> statements, you can achieve short-circuiting:</p>\n\n<pre><code>if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then ...\n</code></pre>\n\n<p>But your <code>then</code> action must appear on the same line as well. If you need multiple statements after <code>then</code>, you can separate them with <code>:</code> or move your code to a subroutine that you can call. For example:</p>\n\n<pre><code>if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then x = 1 : y = 2\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>if not isNull(Rs(\"myField\")) then if Rs(\"myField\") <> 0 then DoSomething(Rs(\"myField\"))\n</code></pre>\n"
},
{
"answer_id": 38354090,
"author": "JemWritesCode",
"author_id": 3593119,
"author_profile": "https://Stackoverflow.com/users/3593119",
"pm_score": 0,
"selected": false,
"text": "<p>You may be able to just use <code>Else</code> to catch nulls, \"\"s, etc.</p>\n\n<pre><code>If UCase(Rs(\"myField\")) = \"THING\" then\n 'Do Things\nelseif UCase(Rs(\"myField\")) = \"STUFF\" then\n 'Do Other Stuff\nelse\n 'Invalid data, such as a NULL, \"\", etc.\n 'Throw an error, do nothing, or default action\nEnd If\n</code></pre>\n\n<p>I've tested this in my code and it's currently working. Might not be right for everyone's situation though. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1818/"
]
| I have a large classic ASP app that I have to maintain, and I repeatedly find myself thwarted by the lack of short-circuit evaluation capability. E.g., VBScript won't let you get away with:
```
if not isNull(Rs("myField")) and Rs("myField") <> 0 then
...
```
...because if Rs("myField") is null, you get an error in the second condition, comparing null to 0. So I'll typically end up doing this instead:
```
dim myField
if isNull(Rs("myField")) then
myField = 0
else
myField = Rs("myField")
end if
if myField <> 0 then
...
```
Obviously, the verboseness is pretty appalling. Looking around this large code base, the best workaround I've found is to use a function the original programmer wrote, called TernaryOp, which basically grafts in ternary operator-like functionality, but I'm still stuck using a temporary variable that would not be necessary in a more full-featured language. Is there a better way? Some super-secret way that short-circuiting really does exist in VBScript? | Maybe not the best way, but it certainly works... Also, if you are in vb6 or .net, you can have different methods that cast to proper type too.
```
if cint( getVal( rs("blah"), "" ) )<> 0 then
'do something
end if
function getVal( v, replacementVal )
if v is nothing then
getVal = replacementVal
else
getVal = v
end if
end function
``` |
59,628 | <p>I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.</p>
<p>Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?</p>
<p>This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this? </p>
| [
{
"answer_id": 59652,
"author": "Gareth Jenkins",
"author_id": 1521,
"author_profile": "https://Stackoverflow.com/users/1521",
"pm_score": 0,
"selected": false,
"text": "<p>Could you put the DataGrids inside panels that have their visibility set to false, then call a client-side javascript function from the body's onload event that calls a server side function that sets the visibility of the panels to true?</p>\n\n<p>If you combined this with an asp:updateProgress control and wrapped the whole thing in an UpdatePanel, you should get something close to what you're looking for - especially if you rigged the js function called in onload to only show one panel and call a return function that showed the next etc.</p>\n"
},
{
"answer_id": 59723,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<p>@Gareth Jenkins</p>\n\n<p>The page will execute all of the queries before returning even the first update panel, so he won't save any time there.</p>\n\n<p>The trick to do this is to move each of your complex gridviews into a user control, in the user control, get rid of the Object DataSource crap, and do your binding in the code behind.</p>\n\n<p>Write your bind code so that it only binds in this situation: </p>\n\n<pre><code>if (this.isPostBack && ScriptManager.IsInAsyncPostback)\n</code></pre>\n\n<p>Then, in the page, programaticly refresh the update panel using javascript once the page has loaded, and you'll get each individual gridview rendering once its ready.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59628",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/781/"
]
| I have a page results page (you get there after submitting your search query elsewhere) whit a whole bunch of gridviews for different type of data objects.
Obviously, some of the queries take longer than the others. How can I make each gridview render as soon as it has the data it needs?
This has been tricky for me because it must work on a postback as well as a pageload. Also, the object data sources just fire automatically on page load/postback; I'm not calling any methods programatically to get the data. Will I have to change this? | @Gareth Jenkins
The page will execute all of the queries before returning even the first update panel, so he won't save any time there.
The trick to do this is to move each of your complex gridviews into a user control, in the user control, get rid of the Object DataSource crap, and do your binding in the code behind.
Write your bind code so that it only binds in this situation:
```
if (this.isPostBack && ScriptManager.IsInAsyncPostback)
```
Then, in the page, programaticly refresh the update panel using javascript once the page has loaded, and you'll get each individual gridview rendering once its ready. |
59,635 | <p>Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.</p>
<p>Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.</p>
<p>First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.</p>
<p>So I added the define for <code>_BIND_TO_CURRENT_VCLIBS_VERSION=1</code> to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.</p>
<p>I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors. </p>
<p>Running the app still gets the following error:</p>
<blockquote>
<blockquote>
<p>The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.</p>
</blockquote>
</blockquote>
<p>None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).</p>
<p>Any one had any similar problem with SP1?</p>
<p>Options:<ul>
<li>Find the problem and fix it so it works as it should (preferred)
<li>Install the redist
<li>dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)</ul></p>
<p><b>Edit:</b> I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:</p>
<blockquote>
<p>c:\Program Files\...\...\X.exe</p>
<p>This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.</p>
</blockquote>
<p>Has no-one else had to deal with this issue?</p>
<p><b>Edit:</b> Just for grins, I downloaded and ran the vcredist_x86.exe for VS2008SP1 on my test machine. <b><i>It</i></b> works. With the SP1 DLLs. And my RTM linked app. But <b>NOT</b> in a private side-by-side distribution that worked pre-SP1.</p>
| [
{
"answer_id": 70808,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 6,
"selected": true,
"text": "<p>I have battled this problem myself last week and consider myself somewhat of an expert now ;)</p>\n\n<p>I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put</p>\n\n<pre><code>#define _BIND_TO_CURRENT_MFC_VERSION 1\n#define _BIND_TO_CURRENT_CRT_VERSION 1\n</code></pre>\n\n<p>into <em>every</em> project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.</p>\n\n<p>There are more flags that define what versions to bind to; it's documented on <a href=\"http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx</a> . As an alternative to the lines above, you can also put</p>\n\n<pre><code>#define _BIND_TO_CURRENT_VCLIBS_VERSION 1\n</code></pre>\n\n<p>which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).</p>\n\n<p>Then, check what the embedded manifest says. Download XM Resource Editor: <a href=\"http://www.wilsonc.demon.co.uk/d10resourceeditor.htm\" rel=\"nofollow noreferrer\">http://www.wilsonc.demon.co.uk/d10resourceeditor.htm</a>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.</p>\n\n<p>What I found is that in many cases, <em>both</em> versions were included in the manifest. This means that some libraries use the sp1 version and others don't.</p>\n\n<p>A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\crt\\include\\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the <code>_BIND_TO_CURRENT_CRT_VERSION</code> preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.</p>\n\n<p>Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.</p>\n"
},
{
"answer_id": 72619,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 2,
"selected": false,
"text": "<p>I just remembered another trick that I used to find out which static libraries were ill-behaving: 'grep' through the static libraries for the string '21022'. HOWEVER, don't use the 'normal' grep tools like wingrep because they won't show you these strings (they think it's a binary file and look for the raw, non-unicode string). Use the 'strings' utility from the resource kit (now in the Russinovich site I think). That one will grep through binaries ok. So you let this 'strings' go through your whole source tree and you'll see the binary files (dlls and static libraries) that contain references to the wrong manifest (or to the manifest with the wrong version in it).</p>\n"
},
{
"answer_id": 1567715,
"author": "remcycles",
"author_id": 182734,
"author_profile": "https://Stackoverflow.com/users/182734",
"pm_score": 2,
"selected": false,
"text": "<p>For your third option, you can probably find the DLLs and manifests for the 9.0.21022 version in the C:\\WINDOWS\\WinSxS directory on your dev machine. If you can, then you can setup your own redist directory and install those files with your app.</p>\n\n<p>Alternatively, you can use the 9.0.30729.1 ones supplied with Visual Studio and forge the manifest you install with your app to report that it supplies the 9.0.21022 DLLs, and not 9.0.30729.1. The runtime linker doesn't seem to mind. See this <a href=\"http://blog.kalmbach-software.de/2009/05/27/deployment-of-vc2008-apps-without-installing-anything/\" rel=\"nofollow noreferrer\">blog</a>, which has been immensely helpful for solving these problems, for more information.</p>\n\n<p>Both workarounds fixed the problems I had with deploying the DLLs as private assemblies with VS2008 Express.</p>\n\n<p>Roel's answer is the way to go for your first option (\"fix it right\"), but if you depend on a library that depends on 9.0.21022 (and your manifest therefore lists both versions), then the third option may be the only way to go if you don't want to run vcredist_x86.exe.</p>\n"
},
{
"answer_id": 1567728,
"author": "remcycles",
"author_id": 182734,
"author_profile": "https://Stackoverflow.com/users/182734",
"pm_score": 2,
"selected": false,
"text": "<p>Another nice tool for viewing exe and dll manifests is <a href=\"http://weblogs.asp.net/kennykerr/archive/2007/07/10/manifest-view-1-0.aspx\" rel=\"nofollow noreferrer\">Manifest View</a>, which fittingly enough will not run on a clean install of XP, because <em>it</em> depends on 9.0.21022.</p>\n"
},
{
"answer_id": 2153085,
"author": "Dimitri C.",
"author_id": 74612,
"author_profile": "https://Stackoverflow.com/users/74612",
"pm_score": 4,
"selected": false,
"text": "<p>To understand the problem, I think it is important to realize that there are <b>four version numbers involved</b>: </p>\n\n<ul>\n<li>(A) The version of the VC header files to which the .exe is compiled.</li>\n<li>(B) The version of the manifest file that is embedded in the resources section of that .exe. By default, this manifest file is automatically generated by Visual Studio.</li>\n<li>(C) The version of the VC .DLLs (part of the side-by-side assembly) you copy in the same directory as the .exe.</li>\n<li>(D) The version of the VC manifest files (part of the side-by-side assembly) you copy in the same directory as the .exe.</li>\n</ul>\n\n<p>There are two versions of the VC 2008 DLL's in the running:</p>\n\n<ul>\n<li>v1: 9.0.21022.8</li>\n<li>v2: 9.0.30729.4148</li>\n</ul>\n\n<p>For clarity, I'll use the v1/v2 notation. The following table shows a number of possible situations:</p>\n\n<pre><code>Situation | .exe (A) | embedded manifest (B) | VC DLLs (C) | VC manifests (D)\n-----------------------------------------------------------------------------\n1 | v2 | v1 | v1 | v1 \n2 | v2 | v1 | v2 | v2 \n3 | v2 | v1 | v2 | v1\n4 | v2 | v2 | v2 | v2\n</code></pre>\n\n<p>The results of these situations when running the .exe on a clean Vista SP1 installation are:</p>\n\n<ul>\n<li><p>Situation 1: a popup is shown, saying: \"The procedure entry point XYZXYZ could not be located in the dynamic link library\".</p></li>\n<li><p>Situation 2: nothing seems to happen when running the .exe, but the following event is logged in Windows' \"Event Viewer / Application log\":</p>\n\n<p>Activation context generation failed for \"C:\\Path\\file.exe\".Error in manifest or policy file \"C:\\Path\\Microsoft.VC90.CRT.MANIFEST\" on line 4. Component identity found in manifest does not match the identity of the component requested. Reference is Microsoft.VC90.CRT,processorArchitecture=\"x86\",publicKeyToken=\"1fc8b3b9a1e18e3b\",type=\"win32\",version=\"9.0.21022.8\". Definition is Microsoft</p></li>\n<li><p>Situation 3: everything seems to work fine. This is <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/1567715#1567715\">remicles2's solution</a>.</p></li>\n<li><p>Situation 4: this is <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808\">how it should be done</a>. Regrettably, as Roel indicates, it can be rather hard to implement.</p></li>\n</ul>\n\n<p>Now, my situation (and I think it is the same as <a href=\"https://stackoverflow.com/users/1441/crashmstr\">crashmstr's</a>) is nr 1. The problem is that Visual Studio for one reason or another generates client code (A) for v2, but for one reason or another, generates a v1 manifest file (B). I have no idea where version (A) can be configured.</p>\n\n<p><b>Note</b> that this whole explanation is still in the context of <a href=\"http://msdn.microsoft.com/en-us/library/aa375674%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">private assemblies</a>.</p>\n\n<p><b>Update</b>: finally I start to understand what is going on. Apparently, <a href=\"https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740\">Visual Studio generates client code (A) for v2 by default</a>, contrary to what I've read on some Microsoft blogs. The _BIND_TO_CURRENT_VCLIBS_VERSION flag only selects the version in the generated manifest file (B), but this version will be ignored when running the application.</p>\n\n<h2>Conclusion</h2>\n\n<p>An .exe that is compiled by Visual Studio 2008 links to the newest versions of the VC90 DLLs by default. You can <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808\">use the _BIND_TO_CURRENT_VCLIBS_VERSION flag</a> to control which version of the VC90 libraries will be generated in the manifest file. This indeed avoids situation 2 where you get the error message \"manifest does not match the identity of the component requested\". It also explains why situation 3 works fine, as even without the _BIND_TO_CURRENT_VCLIBS_VERSION flag the application is linked to the newest versions of the VC DLLs.</p>\n\n<p>The situation is even weirder with public side-by-side assemblies, where vcredist was run, putting the VC 9.0 DLLs in the Windows SxS directory. Even if the .exe's manifest file states that the old versions of the DLLs should be used (this is the case when the _BIND_TO_CURRENT_VCLIBS_VERSION flag is not set), Windows <b>ignores</b> this version number by default! Instead, Windows will use a newer version if present on the system, except <a href=\"https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740\">when an \"application configuration file\"</a> is used.</p>\n\n<p>Am I the only one who thinks this is confusing?</p>\n\n<p>So <b>in summary</b>: </p>\n\n<ul>\n<li>For private assemblies, use the _BIND_TO_CURRENT_VCLIBS_VERSION flag in the .exe's project and <em>all</em> dependent .lib projects. </li>\n<li>For public assemblies, this is not required, as Windows will automatically select the correct version of the .DLLs from the SxS directory.</li>\n</ul>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59635",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1441/"
]
| Since our switch from Visual Studio 6 to Visual Studio 2008, we've been using the MFC90.dll and msvc[pr]90.dlls along with the manifest files in a private side-by-side configuration so as to not worry about versions or installing them to the system.
Pre-SP1, this was working fine (and still works fine on our developer machines). Now that we've done some testing post-SP1 I've been pulling my hair out since yesterday morning.
First off, our NSIS installer script pulls the dlls and manifest files from the redist folder. These were no longer correct, as the app still links to the RTM version.
So I added the define for `_BIND_TO_CURRENT_VCLIBS_VERSION=1` to all of our projects so that they will use the SP1 DLLs in the redist folder (or subsequent ones as new service packs come out). It took me hours to find this.
I've double checked the generated manifest files in the intermediate files folder from the compilation, and they correctly list the 9.0.30729.1 SP1 versions. I've double and triple checked depends on a clean machine: it all links to the local dlls with no errors.
Running the app still gets the following error:
>
>
> >
> > The application failed to initialize properly (0xc0150002). Click on OK to terminate the application.
> >
> >
> >
>
>
>
None of the searches I've done on google or microsoft have come up with anything that relates to my specific issues (but there are hits back to 2005 with this error message).
Any one had any similar problem with SP1?
Options:* Find the problem and fix it so it works as it should (preferred)
* Install the redist
* dig out the old RTM dlls and manifest files and remove the #define to use the current ones. (I've got them in an earlier installer build, since Microsoft blasts them out of your redist folder!)
**Edit:** I've tried re-building with the define turned off (link to RTM dlls), and that works as long as the RTM dlls are installed in the folder. If the SP1 dlls are dropped in, it gets the following error:
>
> c:\Program Files\...\...\X.exe
>
>
> This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.
>
>
>
Has no-one else had to deal with this issue?
**Edit:** Just for grins, I downloaded and ran the vcredist\_x86.exe for VS2008SP1 on my test machine. ***It*** works. With the SP1 DLLs. And my RTM linked app. But **NOT** in a private side-by-side distribution that worked pre-SP1. | I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
```
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
```
into *every* project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.
There are more flags that define what versions to bind to; it's documented on <http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx> . As an alternative to the lines above, you can also put
```
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
```
which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).
Then, check what the embedded manifest says. Download XM Resource Editor: <http://www.wilsonc.demon.co.uk/d10resourceeditor.htm>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.
What I found is that in many cases, *both* versions were included in the manifest. This means that some libraries use the sp1 version and others don't.
A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the `_BIND_TO_CURRENT_CRT_VERSION` preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.
Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied. |
59,642 | <p>What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application. </p>
| [
{
"answer_id": 70808,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 6,
"selected": true,
"text": "<p>I have battled this problem myself last week and consider myself somewhat of an expert now ;)</p>\n\n<p>I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put</p>\n\n<pre><code>#define _BIND_TO_CURRENT_MFC_VERSION 1\n#define _BIND_TO_CURRENT_CRT_VERSION 1\n</code></pre>\n\n<p>into <em>every</em> project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.</p>\n\n<p>There are more flags that define what versions to bind to; it's documented on <a href=\"http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx</a> . As an alternative to the lines above, you can also put</p>\n\n<pre><code>#define _BIND_TO_CURRENT_VCLIBS_VERSION 1\n</code></pre>\n\n<p>which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).</p>\n\n<p>Then, check what the embedded manifest says. Download XM Resource Editor: <a href=\"http://www.wilsonc.demon.co.uk/d10resourceeditor.htm\" rel=\"nofollow noreferrer\">http://www.wilsonc.demon.co.uk/d10resourceeditor.htm</a>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.</p>\n\n<p>What I found is that in many cases, <em>both</em> versions were included in the manifest. This means that some libraries use the sp1 version and others don't.</p>\n\n<p>A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\\Program Files\\Microsoft Visual Studio 9.0\\VC\\crt\\include\\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the <code>_BIND_TO_CURRENT_CRT_VERSION</code> preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.</p>\n\n<p>Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied.</p>\n"
},
{
"answer_id": 72619,
"author": "Roel",
"author_id": 11449,
"author_profile": "https://Stackoverflow.com/users/11449",
"pm_score": 2,
"selected": false,
"text": "<p>I just remembered another trick that I used to find out which static libraries were ill-behaving: 'grep' through the static libraries for the string '21022'. HOWEVER, don't use the 'normal' grep tools like wingrep because they won't show you these strings (they think it's a binary file and look for the raw, non-unicode string). Use the 'strings' utility from the resource kit (now in the Russinovich site I think). That one will grep through binaries ok. So you let this 'strings' go through your whole source tree and you'll see the binary files (dlls and static libraries) that contain references to the wrong manifest (or to the manifest with the wrong version in it).</p>\n"
},
{
"answer_id": 1567715,
"author": "remcycles",
"author_id": 182734,
"author_profile": "https://Stackoverflow.com/users/182734",
"pm_score": 2,
"selected": false,
"text": "<p>For your third option, you can probably find the DLLs and manifests for the 9.0.21022 version in the C:\\WINDOWS\\WinSxS directory on your dev machine. If you can, then you can setup your own redist directory and install those files with your app.</p>\n\n<p>Alternatively, you can use the 9.0.30729.1 ones supplied with Visual Studio and forge the manifest you install with your app to report that it supplies the 9.0.21022 DLLs, and not 9.0.30729.1. The runtime linker doesn't seem to mind. See this <a href=\"http://blog.kalmbach-software.de/2009/05/27/deployment-of-vc2008-apps-without-installing-anything/\" rel=\"nofollow noreferrer\">blog</a>, which has been immensely helpful for solving these problems, for more information.</p>\n\n<p>Both workarounds fixed the problems I had with deploying the DLLs as private assemblies with VS2008 Express.</p>\n\n<p>Roel's answer is the way to go for your first option (\"fix it right\"), but if you depend on a library that depends on 9.0.21022 (and your manifest therefore lists both versions), then the third option may be the only way to go if you don't want to run vcredist_x86.exe.</p>\n"
},
{
"answer_id": 1567728,
"author": "remcycles",
"author_id": 182734,
"author_profile": "https://Stackoverflow.com/users/182734",
"pm_score": 2,
"selected": false,
"text": "<p>Another nice tool for viewing exe and dll manifests is <a href=\"http://weblogs.asp.net/kennykerr/archive/2007/07/10/manifest-view-1-0.aspx\" rel=\"nofollow noreferrer\">Manifest View</a>, which fittingly enough will not run on a clean install of XP, because <em>it</em> depends on 9.0.21022.</p>\n"
},
{
"answer_id": 2153085,
"author": "Dimitri C.",
"author_id": 74612,
"author_profile": "https://Stackoverflow.com/users/74612",
"pm_score": 4,
"selected": false,
"text": "<p>To understand the problem, I think it is important to realize that there are <b>four version numbers involved</b>: </p>\n\n<ul>\n<li>(A) The version of the VC header files to which the .exe is compiled.</li>\n<li>(B) The version of the manifest file that is embedded in the resources section of that .exe. By default, this manifest file is automatically generated by Visual Studio.</li>\n<li>(C) The version of the VC .DLLs (part of the side-by-side assembly) you copy in the same directory as the .exe.</li>\n<li>(D) The version of the VC manifest files (part of the side-by-side assembly) you copy in the same directory as the .exe.</li>\n</ul>\n\n<p>There are two versions of the VC 2008 DLL's in the running:</p>\n\n<ul>\n<li>v1: 9.0.21022.8</li>\n<li>v2: 9.0.30729.4148</li>\n</ul>\n\n<p>For clarity, I'll use the v1/v2 notation. The following table shows a number of possible situations:</p>\n\n<pre><code>Situation | .exe (A) | embedded manifest (B) | VC DLLs (C) | VC manifests (D)\n-----------------------------------------------------------------------------\n1 | v2 | v1 | v1 | v1 \n2 | v2 | v1 | v2 | v2 \n3 | v2 | v1 | v2 | v1\n4 | v2 | v2 | v2 | v2\n</code></pre>\n\n<p>The results of these situations when running the .exe on a clean Vista SP1 installation are:</p>\n\n<ul>\n<li><p>Situation 1: a popup is shown, saying: \"The procedure entry point XYZXYZ could not be located in the dynamic link library\".</p></li>\n<li><p>Situation 2: nothing seems to happen when running the .exe, but the following event is logged in Windows' \"Event Viewer / Application log\":</p>\n\n<p>Activation context generation failed for \"C:\\Path\\file.exe\".Error in manifest or policy file \"C:\\Path\\Microsoft.VC90.CRT.MANIFEST\" on line 4. Component identity found in manifest does not match the identity of the component requested. Reference is Microsoft.VC90.CRT,processorArchitecture=\"x86\",publicKeyToken=\"1fc8b3b9a1e18e3b\",type=\"win32\",version=\"9.0.21022.8\". Definition is Microsoft</p></li>\n<li><p>Situation 3: everything seems to work fine. This is <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/1567715#1567715\">remicles2's solution</a>.</p></li>\n<li><p>Situation 4: this is <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808\">how it should be done</a>. Regrettably, as Roel indicates, it can be rather hard to implement.</p></li>\n</ul>\n\n<p>Now, my situation (and I think it is the same as <a href=\"https://stackoverflow.com/users/1441/crashmstr\">crashmstr's</a>) is nr 1. The problem is that Visual Studio for one reason or another generates client code (A) for v2, but for one reason or another, generates a v1 manifest file (B). I have no idea where version (A) can be configured.</p>\n\n<p><b>Note</b> that this whole explanation is still in the context of <a href=\"http://msdn.microsoft.com/en-us/library/aa375674%28VS.85%29.aspx\" rel=\"nofollow noreferrer\">private assemblies</a>.</p>\n\n<p><b>Update</b>: finally I start to understand what is going on. Apparently, <a href=\"https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740\">Visual Studio generates client code (A) for v2 by default</a>, contrary to what I've read on some Microsoft blogs. The _BIND_TO_CURRENT_VCLIBS_VERSION flag only selects the version in the generated manifest file (B), but this version will be ignored when running the application.</p>\n\n<h2>Conclusion</h2>\n\n<p>An .exe that is compiled by Visual Studio 2008 links to the newest versions of the VC90 DLLs by default. You can <a href=\"https://stackoverflow.com/questions/59635/app-does-not-run-with-vs-2008-sp1-dlls-previous-version-works-with-rtm-versions/70808#70808\">use the _BIND_TO_CURRENT_VCLIBS_VERSION flag</a> to control which version of the VC90 libraries will be generated in the manifest file. This indeed avoids situation 2 where you get the error message \"manifest does not match the identity of the component requested\". It also explains why situation 3 works fine, as even without the _BIND_TO_CURRENT_VCLIBS_VERSION flag the application is linked to the newest versions of the VC DLLs.</p>\n\n<p>The situation is even weirder with public side-by-side assemblies, where vcredist was run, putting the VC 9.0 DLLs in the Windows SxS directory. Even if the .exe's manifest file states that the old versions of the DLLs should be used (this is the case when the _BIND_TO_CURRENT_VCLIBS_VERSION flag is not set), Windows <b>ignores</b> this version number by default! Instead, Windows will use a newer version if present on the system, except <a href=\"https://stackoverflow.com/questions/2289593/how-to-select-the-version-of-the-vc-2008-dlls-the-application-should-be-linked-to/2289740#2289740\">when an \"application configuration file\"</a> is used.</p>\n\n<p>Am I the only one who thinks this is confusing?</p>\n\n<p>So <b>in summary</b>: </p>\n\n<ul>\n<li>For private assemblies, use the _BIND_TO_CURRENT_VCLIBS_VERSION flag in the .exe's project and <em>all</em> dependent .lib projects. </li>\n<li>For public assemblies, this is not required, as Windows will automatically select the correct version of the .DLLs from the SxS directory.</li>\n</ul>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59642",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2723/"
]
| What's the best way to determine which version of the .NET Compact Frameworks (including Service Packs) is installed on a device through a .NET application. | I have battled this problem myself last week and consider myself somewhat of an expert now ;)
I'm 99% sure that not all dlls and static libraries were recompiled with the SP1 version. You need to put
```
#define _BIND_TO_CURRENT_MFC_VERSION 1
#define _BIND_TO_CURRENT_CRT_VERSION 1
```
into *every* project you're using. For every project of a real-world size, it's very easy to forget some small lib that wasn't recompiled.
There are more flags that define what versions to bind to; it's documented on <http://msdn.microsoft.com/en-us/library/cc664727%28v=vs.90%29.aspx> . As an alternative to the lines above, you can also put
```
#define _BIND_TO_CURRENT_VCLIBS_VERSION 1
```
which will bind to the latest version of all VC libs (CRT, MFC, ATL, OpenMP).
Then, check what the embedded manifest says. Download XM Resource Editor: <http://www.wilsonc.demon.co.uk/d10resourceeditor.htm>. Open every dll and exe in your solution. Look under 'XP Theme Manifest'. Check that the 'version' attribute on the right-hand side is '9.0.30729.1'. If it's '9.0.21022', some static library is pulling in the manifest for the old version.
What I found is that in many cases, *both* versions were included in the manifest. This means that some libraries use the sp1 version and others don't.
A great way to debug which libraries don't have the preprocessor directives set: temporarily modify your platform headers so that compilation stops when it tries to embed the old manifest. Open C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\include\crtassem.h. Search for the '21022' string. In that define, put something invalid (change 'define' to 'blehbleh' or so). This way, when you're compiling a project where the `_BIND_TO_CURRENT_CRT_VERSION` preprocessor flag is not set, your compilation will stop and you'll know that you need to add them or made sure that it's applied everywhere.
Also make sure to use Dependency Walker so that you know what dlls are being pulled in. It's easiest to install a fresh Windows XP copy with no updates (only SP2) on a virtual machine. This way you know for sure that there is nothing in the SxS folder that is being used instead of the side-by-side dlls that you supplied. |
59,648 | <p>I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: <em><a href="http://www.gallup.com" rel="nofollow noreferrer">www.gallup.com</a></em> and <em><a href="http://www.rassmussenreports.com" rel="nofollow noreferrer">www.rassmussenreports.com</a></em></p>
<p>I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)</p>
<p>Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations.</p>
<p>And this is my problem. At the end of the test I have an array in a single variable that looks something like this:</p>
<pre><code>[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0]
</code></pre>
<p>The program currently produces one array for each correct simulation. <em>I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?</em></p>
<p>How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.</p>
<p>Code testing for McCain:</p>
<pre><code> test = []
while x < 5:
test = round(100*random.random())
mctest.append(test)
x = x +1
mctestavg = (mctest[0] + mctest[1] + mctest[2])/3
#mcavg is real data
if mctestavg == mcavg[2]:
mcwork = mctest
</code></pre>
<p>How do I repeat without creating multiple mcwork vars?</p>
| [
{
"answer_id": 59662,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>Are you talking about doing this?</p>\n\n<pre><code>>>> a = [ ['a', 'b'], ['c', 'd'] ]\n>>> a[1]\n['c', 'd']\n>>> a[1][1]\n'd'\n</code></pre>\n"
},
{
"answer_id": 59663,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 1,
"selected": false,
"text": "<p>Lists in python can contain any type of object -- If I understand the question correctly, will a <code>list</code> of <code>list</code>s do the job? Something like this (assuming you have a function <code>generate_poll_data()</code> which creates your data:</p>\n\n<pre><code>data = []\n\nfor in xrange(num_iterations):\n data.append(generate_poll_data())\n</code></pre>\n\n<p>Then, <code>data[n]</code> will be the list of data from the <code>(n-1)</code>th run.</p>\n"
},
{
"answer_id": 59709,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>since you are thinking in <em>variables</em>, you might prefer a dictionary over a list of lists:</p>\n\n<pre><code>data = {}\ndata['a'] = [generate_poll_data()]\ndata['b'] = [generate_poll_data()]\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 59762,
"author": "Vinay",
"author_id": 6171,
"author_profile": "https://Stackoverflow.com/users/6171",
"pm_score": 1,
"selected": false,
"text": "<p>I would strongly consider using <a href=\"https://numpy.org\" rel=\"nofollow noreferrer\">NumPy</a> to do this. You get efficient N-dimensional arrays that you can quickly and easily process.</p>\n"
},
{
"answer_id": 59778,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": true,
"text": "<p>Would something like this work?</p>\n<pre><code>from random import randint \n\nmcworks = []\n\nfor n in xrange(NUM_ITERATIONS):\n mctest = [randint(0, 100) for i in xrange(5)]\n if sum(mctest[:3])/3 == mcavg[2]:\n mcworks.append(mctest) # mcavg is real data\n</code></pre>\n<p>In the end, you are left with a list of valid <code>mctest</code> lists.</p>\n<p>What I changed:</p>\n<ul>\n<li>Used a <a href=\"https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000\" rel=\"nofollow noreferrer\">list comprehension</a> to build the data instead of a for loop</li>\n<li>Used <code>random.randint</code> to get random integers</li>\n<li>Used <a href=\"http://docs.python.org/tut/node5.html\" rel=\"nofollow noreferrer\">slices</a> and <code>sum</code> to calculate the average of the first three items</li>\n<li>(To answer your actual question :-) ) Put the results in a list <code>mcworks</code>, instead of creating a new variable for every iteration</li>\n</ul>\n"
},
{
"answer_id": 53864491,
"author": "Mattias",
"author_id": 8265788,
"author_profile": "https://Stackoverflow.com/users/8265788",
"pm_score": 0,
"selected": false,
"text": "<p>A neat way to do it is to use a list of lists in combination with Pandas. Then you are able to create a 3-day rolling average. \nThis makes it easy to search through the results by just adding the real ones as another column, and using the loc function for finding which ones that match.</p>\n\n<pre><code>rand_vals = [randint(0, 100) for i in range(5))]\ndf = pd.DataFrame(data=rand_vals, columns=['generated data'])\ndf['3 day avg'] = df['generated data'].rolling(3).mean()\ndf['mcavg'] = mcavg # the list of real data\n# Extract the resulting list of values\nres = df.loc[df['3 day avg'] == df['mcavg']]['3 day avg'].values\n</code></pre>\n\n<p>This is also neat if you intend to use the same random values for different polls/persons, just add another column with their real values and perform the same search for them. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6163/"
]
| I am writing a program to simulate the actual polling data companies like Gallup or Rasmussen publish daily: *[www.gallup.com](http://www.gallup.com)* and *[www.rassmussenreports.com](http://www.rassmussenreports.com)*
I'm using a brute force method, where the computer generates some random daily polling data and then calculates three day averages to see if the average of the random data matches pollsters numbers. (Most companies poll numbers are three day averages)
Currently, it works well for one iteration, but my goal is to have it produce the most common simulation that matches the average polling data. I could then change the code of anywhere from 1 to 1000 iterations.
And this is my problem. At the end of the test I have an array in a single variable that looks something like this:
```
[40.1, 39.4, 56.7, 60.0, 20.0 ..... 19.0]
```
The program currently produces one array for each correct simulation. *I can store each array in a single variable, but I then have to have a program that could generate 1 to 1000 variables depending on how many iterations I requested!?*
How do I avoid this? I know there is an intelligent way of doing this that doesn't require the program to generate variables to store arrays depending on how many simulations I want.
Code testing for McCain:
```
test = []
while x < 5:
test = round(100*random.random())
mctest.append(test)
x = x +1
mctestavg = (mctest[0] + mctest[1] + mctest[2])/3
#mcavg is real data
if mctestavg == mcavg[2]:
mcwork = mctest
```
How do I repeat without creating multiple mcwork vars? | Would something like this work?
```
from random import randint
mcworks = []
for n in xrange(NUM_ITERATIONS):
mctest = [randint(0, 100) for i in xrange(5)]
if sum(mctest[:3])/3 == mcavg[2]:
mcworks.append(mctest) # mcavg is real data
```
In the end, you are left with a list of valid `mctest` lists.
What I changed:
* Used a [list comprehension](https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000) to build the data instead of a for loop
* Used `random.randint` to get random integers
* Used [slices](http://docs.python.org/tut/node5.html) and `sum` to calculate the average of the first three items
* (To answer your actual question :-) ) Put the results in a list `mcworks`, instead of creating a new variable for every iteration |
59,651 | <p>I have a web page that I have hooked up to a <a href="http://en.wikipedia.org/wiki/Stored_procedure" rel="nofollow noreferrer">stored procedure</a>. In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int. </p>
<p><a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> seems to want to default to <em>int32</em>, but the number won't get higher than 6. Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?</p>
<p>specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer.</p>
| [
{
"answer_id": 59662,
"author": "Nick Stinemates",
"author_id": 4960,
"author_profile": "https://Stackoverflow.com/users/4960",
"pm_score": 2,
"selected": false,
"text": "<p>Are you talking about doing this?</p>\n\n<pre><code>>>> a = [ ['a', 'b'], ['c', 'd'] ]\n>>> a[1]\n['c', 'd']\n>>> a[1][1]\n'd'\n</code></pre>\n"
},
{
"answer_id": 59663,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 1,
"selected": false,
"text": "<p>Lists in python can contain any type of object -- If I understand the question correctly, will a <code>list</code> of <code>list</code>s do the job? Something like this (assuming you have a function <code>generate_poll_data()</code> which creates your data:</p>\n\n<pre><code>data = []\n\nfor in xrange(num_iterations):\n data.append(generate_poll_data())\n</code></pre>\n\n<p>Then, <code>data[n]</code> will be the list of data from the <code>(n-1)</code>th run.</p>\n"
},
{
"answer_id": 59709,
"author": "Daren Thomas",
"author_id": 2260,
"author_profile": "https://Stackoverflow.com/users/2260",
"pm_score": 1,
"selected": false,
"text": "<p>since you are thinking in <em>variables</em>, you might prefer a dictionary over a list of lists:</p>\n\n<pre><code>data = {}\ndata['a'] = [generate_poll_data()]\ndata['b'] = [generate_poll_data()]\n</code></pre>\n\n<p>etc.</p>\n"
},
{
"answer_id": 59762,
"author": "Vinay",
"author_id": 6171,
"author_profile": "https://Stackoverflow.com/users/6171",
"pm_score": 1,
"selected": false,
"text": "<p>I would strongly consider using <a href=\"https://numpy.org\" rel=\"nofollow noreferrer\">NumPy</a> to do this. You get efficient N-dimensional arrays that you can quickly and easily process.</p>\n"
},
{
"answer_id": 59778,
"author": "dF.",
"author_id": 3002,
"author_profile": "https://Stackoverflow.com/users/3002",
"pm_score": 3,
"selected": true,
"text": "<p>Would something like this work?</p>\n<pre><code>from random import randint \n\nmcworks = []\n\nfor n in xrange(NUM_ITERATIONS):\n mctest = [randint(0, 100) for i in xrange(5)]\n if sum(mctest[:3])/3 == mcavg[2]:\n mcworks.append(mctest) # mcavg is real data\n</code></pre>\n<p>In the end, you are left with a list of valid <code>mctest</code> lists.</p>\n<p>What I changed:</p>\n<ul>\n<li>Used a <a href=\"https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000\" rel=\"nofollow noreferrer\">list comprehension</a> to build the data instead of a for loop</li>\n<li>Used <code>random.randint</code> to get random integers</li>\n<li>Used <a href=\"http://docs.python.org/tut/node5.html\" rel=\"nofollow noreferrer\">slices</a> and <code>sum</code> to calculate the average of the first three items</li>\n<li>(To answer your actual question :-) ) Put the results in a list <code>mcworks</code>, instead of creating a new variable for every iteration</li>\n</ul>\n"
},
{
"answer_id": 53864491,
"author": "Mattias",
"author_id": 8265788,
"author_profile": "https://Stackoverflow.com/users/8265788",
"pm_score": 0,
"selected": false,
"text": "<p>A neat way to do it is to use a list of lists in combination with Pandas. Then you are able to create a 3-day rolling average. \nThis makes it easy to search through the results by just adding the real ones as another column, and using the loc function for finding which ones that match.</p>\n\n<pre><code>rand_vals = [randint(0, 100) for i in range(5))]\ndf = pd.DataFrame(data=rand_vals, columns=['generated data'])\ndf['3 day avg'] = df['generated data'].rolling(3).mean()\ndf['mcavg'] = mcavg # the list of real data\n# Extract the resulting list of values\nres = df.loc[df['3 day avg'] == df['mcavg']]['3 day avg'].values\n</code></pre>\n\n<p>This is also neat if you intend to use the same random values for different polls/persons, just add another column with their real values and perform the same search for them. </p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/730/"
]
| I have a web page that I have hooked up to a [stored procedure](http://en.wikipedia.org/wiki/Stored_procedure). In this SQL data source, I have a parameter that I'm passing back to the stored procedure of type int.
[ASP.NET](http://en.wikipedia.org/wiki/ASP.NET) seems to want to default to *int32*, but the number won't get higher than 6. Is it ok to override the ASP.NET default and put in 16 or will there be a conflict somewhere down the road?
specification: the database field has a length of 4 and precision of 10, if that makes a difference in the answer. | Would something like this work?
```
from random import randint
mcworks = []
for n in xrange(NUM_ITERATIONS):
mctest = [randint(0, 100) for i in xrange(5)]
if sum(mctest[:3])/3 == mcavg[2]:
mcworks.append(mctest) # mcavg is real data
```
In the end, you are left with a list of valid `mctest` lists.
What I changed:
* Used a [list comprehension](https://web.archive.org/web/20080928230016/http://docs.python.org:80/tut/node7.html#SECTION007140000000000000000) to build the data instead of a for loop
* Used `random.randint` to get random integers
* Used [slices](http://docs.python.org/tut/node5.html) and `sum` to calculate the average of the first three items
* (To answer your actual question :-) ) Put the results in a list `mcworks`, instead of creating a new variable for every iteration |
59,653 | <p>Is there a way to get at the ItemContaner of a selected item in a listbox? In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0. </p>
<p>I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size. I also want to get the relative position of the selected item for animations. Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.</p>
<p>I should clarify i'm not adding items to the listbox explicitly. I am using data binding in xaml and DataTemplates. What I have trouble accessing is the ItemContainer of the selected item's DataTemplate.</p>
| [
{
"answer_id": 86980,
"author": "dcstraw",
"author_id": 10391,
"author_profile": "https://Stackoverflow.com/users/10391",
"pm_score": 0,
"selected": false,
"text": "<p>If you are adding non-UI elements to the listbox (such as strings or non-UI data objects), then this is probably pretty difficult. However if you wrap your items in some sort of FrameworkElement-derived object before adding them to the listbox, you can use TransformToVisual to get the relative size and use Height and Width to set the size of the item.</p>\n\n<p>In general you can wrap your objects in a ContentControl like the following. Instead of:</p>\n\n<pre><code>_ListBox.Items.Add(obj0);\n_ListBox.Items.Add(obj1);\n</code></pre>\n\n<p>Do this:</p>\n\n<pre><code>_ListBox.Items.Add(new ContentControl { Content = obj0 });\n_ListBox.Items.Add(new ContentControl { Content = obj1 });\n</code></pre>\n\n<p>Now when you get _ListBox.SelectedItem you can cast it to ContentControl and set the size and get the relative position. If you need the original object, simply get the value of the item's Content property.</p>\n"
},
{
"answer_id": 162051,
"author": "MaxM",
"author_id": 4226,
"author_profile": "https://Stackoverflow.com/users/4226",
"pm_score": 2,
"selected": false,
"text": "<p>There is a way to obtain the Panel containing the item's UIElement and the mapping of items to UIElements. You have to inherit from ListBox (this actually works for any ItemsControl) and override PrepareContainerForItemOverride:</p>\n\n<pre><code>protected override void PrepareContainerForItemOverride(DependencyObject element, object item)\n {\n base.PrepareContainerForItemOverride(element, item);\n var el = element as FrameworkElement;\n if (el != null)\n {\n // here is the elements's panel:\n _itemsHost = el.Parent as Panel;\n\n // item is original item inserted in Items or ItemsSource\n // we can save the mapping between items and FrameworElements:\n _elementMapping[item] = el;\n }\n }\n</code></pre>\n\n<p>This is kind of hackish, but it works just fine.</p>\n"
},
{
"answer_id": 1500946,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 0,
"selected": false,
"text": "<p>It appears that you can use relative binding to get at the Item Container from the ItemTemplate.</p>\n\n<pre><code><TextBlock YourTargetProperty=\"{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ListBoxItem}}, Mode=OneWay, Path=YourSourceProperty}\" />\n</code></pre>\n\n<p>I found this solution <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/fbe80312-67aa-42ca-bd99-89b6d79e06ae\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 10407613,
"author": "Parrhesia Joe",
"author_id": 542909,
"author_profile": "https://Stackoverflow.com/users/542909",
"pm_score": 0,
"selected": false,
"text": "<p>Update for silverlight 5.</p>\n\n<pre><code> <ListBox ItemsSource=\"{Binding Properties}\">\n <ListBox.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding IsSelected, RelativeSource={RelativeSource AncestorType=ListBoxItem}}\" />\n </DataTemplate>\n </ListBox.ItemTemplate>\n</code></pre>\n\n<p>RelativeSource AncestorType is now supported, making this much easier.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
]
| Is there a way to get at the ItemContaner of a selected item in a listbox? In Silverlight 2.0 Beta 1 I could, but the container is hidden in Beta 2 of Silverlight 2.0.
I'm trying to resize the listbox item when it is unselected to a specific size and when selected to a variable size. I also want to get the relative position of the selected item for animations. Growing to a variable size and getting the relative pasition is why i need to get to the listbox item.
I should clarify i'm not adding items to the listbox explicitly. I am using data binding in xaml and DataTemplates. What I have trouble accessing is the ItemContainer of the selected item's DataTemplate. | There is a way to obtain the Panel containing the item's UIElement and the mapping of items to UIElements. You have to inherit from ListBox (this actually works for any ItemsControl) and override PrepareContainerForItemOverride:
```
protected override void PrepareContainerForItemOverride(DependencyObject element, object item)
{
base.PrepareContainerForItemOverride(element, item);
var el = element as FrameworkElement;
if (el != null)
{
// here is the elements's panel:
_itemsHost = el.Parent as Panel;
// item is original item inserted in Items or ItemsSource
// we can save the mapping between items and FrameworElements:
_elementMapping[item] = el;
}
}
```
This is kind of hackish, but it works just fine. |
59,655 | <p>Given a controller method like: </p>
<pre><code>def show
@model = Model.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => model }
end
end
</code></pre>
<p>What's the best way to write an integration test that asserts that the return has the expected XML?</p>
| [
{
"answer_id": 59714,
"author": "Michael Sepcot",
"author_id": 6033,
"author_profile": "https://Stackoverflow.com/users/6033",
"pm_score": 0,
"selected": false,
"text": "<p>Set the request objects accept header:</p>\n\n<pre><code>@request.accept = 'text/xml' # or 'application/xml' I forget which\n</code></pre>\n\n<p>Then you can assert the response body is equal to what you were expecting</p>\n\n<pre><code>assert_equal '<some>xml</some>', @response.body\n</code></pre>\n"
},
{
"answer_id": 60261,
"author": "btandyco",
"author_id": 6189,
"author_profile": "https://Stackoverflow.com/users/6189",
"pm_score": 3,
"selected": false,
"text": "<p>This is the idiomatic way of testing the xml response from a controller.</p>\n\n<pre><code>class ProductsControllerTest < ActionController::TestCase\n def test_should_get_index_formatted_for_xml\n @request.env['HTTP_ACCEPT'] = 'application/xml'\n get :index\n assert_response :success\n end\nend\n</code></pre>\n"
},
{
"answer_id": 60626,
"author": "ntalbott",
"author_id": 6284,
"author_profile": "https://Stackoverflow.com/users/6284",
"pm_score": 5,
"selected": true,
"text": "<p>A combination of using the format and assert_select in an integration test works great:</p>\n\n<pre><code>class ProductsTest < ActionController::IntegrationTest\n def test_contents_of_xml\n get '/index/1.xml'\n assert_select 'product name', /widget/\n end\nend\n</code></pre>\n\n<p>For more details check out <a href=\"http://apidock.com/rails/ActionController/Assertions/SelectorAssertions/assert_select\" rel=\"noreferrer\">assert_select</a> in the Rails docs.</p>\n"
},
{
"answer_id": 613309,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>These 2 answers are great, except that my results include the datetime fields, which are gong to be different in most circumstances, so the <code>assert_equal</code> fails. It appears that I will need to process the include <code>@response.body</code> using an XML parser, and then compare the individual fields, the number of elements, etc. Or is there an easier way?</p>\n"
},
{
"answer_id": 3532203,
"author": "bjnord",
"author_id": 291754,
"author_profile": "https://Stackoverflow.com/users/291754",
"pm_score": 3,
"selected": false,
"text": "<p>The answer from ntalbott shows a get action. The post action is a little trickier; if you want to send the new object as an XML message, and have the XML attributes show up in the params hash in the controller, you have to get the headers right. Here's an example (Rails 2.3.x):</p>\n\n<pre><code>class TruckTest < ActionController::IntegrationTest\n def test_new_truck\n paint_color = 'blue'\n fuzzy_dice_count = 2\n truck = Truck.new({:paint_color => paint_color, :fuzzy_dice_count => fuzzy_dice_count})\n @headers ||= {}\n @headers['HTTP_ACCEPT'] = @headers['CONTENT_TYPE'] = 'application/xml'\n post '/trucks.xml', truck.to_xml, @headers\n #puts @response.body\n assert_select 'truck>paint_color', paint_color\n assert_select 'truck>fuzzy_dice_count', fuzzy_dice_count.to_s\n end\nend\n</code></pre>\n\n<p>You can see here that the 2nd argument to post doesn't have to be a parameters hash; it can be a string (containing XML), <strong>if</strong> the headers are right. The 3rd argument, @headers, is the part that took me a lot of research to figure out.</p>\n\n<p>(Note also the use of to_s when comparing an integer value in assert_select.)</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59655",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4748/"
]
| Given a controller method like:
```
def show
@model = Model.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => model }
end
end
```
What's the best way to write an integration test that asserts that the return has the expected XML? | A combination of using the format and assert\_select in an integration test works great:
```
class ProductsTest < ActionController::IntegrationTest
def test_contents_of_xml
get '/index/1.xml'
assert_select 'product name', /widget/
end
end
```
For more details check out [assert\_select](http://apidock.com/rails/ActionController/Assertions/SelectorAssertions/assert_select) in the Rails docs. |
59,670 | <p>I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:</p>
<blockquote>
<p>warning: deprecated conversion from string constant to ‘char*’</p>
</blockquote>
<p>Obviously, the correct way to fix this is to find every declaration like</p>
<pre><code>char *s = "constant string";
</code></pre>
<p>or function call like:</p>
<pre><code>void foo(char *s);
foo("constant string");
</code></pre>
<p>and make them <code>const char</code> pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with <a href="https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror" rel="nofollow noreferrer">-Werror</a>, so I need some way to stifle these warnings. How can I do that?</p>
| [
{
"answer_id": 59687,
"author": "DGentry",
"author_id": 4761,
"author_profile": "https://Stackoverflow.com/users/4761",
"pm_score": 9,
"selected": true,
"text": "<p>I believe passing <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings\" rel=\"nofollow noreferrer\">-Wno-write-strings</a> to GCC will suppress this warning.</p>\n"
},
{
"answer_id": 59690,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 6,
"selected": false,
"text": "<p>Check out GCC's <a href=\"http://gcc.gnu.org/onlinedocs/gcc/Diagnostic-Pragmas.html\" rel=\"nofollow noreferrer\">Diagnostic Pragma</a> support, and the list of <a href=\"http://docs.redhat.com/docs/en-US/Red_Hat_Enterprise_Linux/4/html/Using_the_GNU_Compiler_Collection/warning-options.html\" rel=\"nofollow noreferrer\">-W warning options</a>.</p>\n<p>For GCC, you can use <code>#pragma warning</code> directives like explained <a href=\"https://stackoverflow.com/a/8140772/2436175\">here</a>.</p>\n"
},
{
"answer_id": 59741,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 5,
"selected": false,
"text": "<p>If it's an active code base, you might still want to upgrade the code base. Of course, performing the changes manually isn't feasible but I believe that this problem could be solved once and for all by one single <code>sed</code> command. I haven't tried it, though, so take the following with a grain of salt.</p>\n<pre class=\"lang-none prettyprint-override\"><code>find . -exec sed -E -i .backup -n \\\n -e 's/char\\s*\\*\\s*(\\w+)\\s*= "/char const* \\1 = "/g' {} \\;\n</code></pre>\n<p>This might not find all places (even not considering function calls) but it would alleviate the problem and make it possible to perform the few remaining changes manually.</p>\n"
},
{
"answer_id": 67649,
"author": "James Antill",
"author_id": 10314,
"author_profile": "https://Stackoverflow.com/users/10314",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <p>The problem right now is that I'm running with -Werror</p>\n</blockquote>\n\n<p>This is your real problem, IMO. You can try some automated ways of moving from (char *) to (const char *) but I would put money on them not just working. You will have to have a human involved for at least some of the work.\nFor the short term, just ignore the warning (but IMO leave it on, or it'll never get fixed) and just remove the -Werror.</p>\n"
},
{
"answer_id": 237636,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-deprecated\" rel=\"nofollow noreferrer\">-Wno-deprecated</a> option to ignore deprecated warning messages.</p>\n"
},
{
"answer_id": 541079,
"author": "BlackShift",
"author_id": 2097,
"author_profile": "https://Stackoverflow.com/users/2097",
"pm_score": 6,
"selected": false,
"text": "<p>I had a similar problem, and I solved it like this:</p>\n<pre><code>#include <string.h>\n\nextern void foo(char* m);\n \nint main() {\n // warning: deprecated conversion from string constant to ‘char*’\n //foo("Hello");\n \n // no more warning\n char msg[] = "Hello";\n foo(msg);\n}\n</code></pre>\n<p>I did not have access to foo in order to adapt it to accept <code>const char*</code>, which would be a better solution because foo did not change <code>m</code>.</p>\n"
},
{
"answer_id": 826858,
"author": "BillAtHRST",
"author_id": 69158,
"author_profile": "https://Stackoverflow.com/users/69158",
"pm_score": 0,
"selected": false,
"text": "<p>You can also create a writable string from a string constant by calling <code>strdup()</code>.</p>\n\n<p>For instance, this code generates a warning:</p>\n\n<pre><code>putenv(\"DEBUG=1\");\n</code></pre>\n\n<p>However, the following code does not (it makes a copy of the string on the heap before passing it to <code>putenv</code>):</p>\n\n<pre><code>putenv(strdup(\"DEBUG=1\"));\n</code></pre>\n\n<p>In this case (and perhaps in most others) turning off the warning is a bad idea -- it's there for a reason. The other alternative (making all strings writable by default) is potentially inefficient.</p>\n\n<p>Listen to what the compiler is telling you! </p>\n"
},
{
"answer_id": 1309789,
"author": "vy32",
"author_id": 51167,
"author_profile": "https://Stackoverflow.com/users/51167",
"pm_score": 5,
"selected": false,
"text": "<p>I can't use the compiler switch. So I have turned this:</p>\n\n<pre><code>char *setf = tigetstr(\"setf\");\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>char *setf = tigetstr((char *)\"setf\");\n</code></pre>\n"
},
{
"answer_id": 2461387,
"author": "alexsid",
"author_id": 295560,
"author_profile": "https://Stackoverflow.com/users/295560",
"pm_score": 3,
"selected": false,
"text": "<p><code>Test string</code> is const string. So you can solve like this:</p>\n\n<pre><code>char str[] = \"Test string\";\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>const char* str = \"Test string\";\nprintf(str);\n</code></pre>\n"
},
{
"answer_id": 3553118,
"author": "shindow",
"author_id": 415712,
"author_profile": "https://Stackoverflow.com/users/415712",
"pm_score": -1,
"selected": false,
"text": "<p>See this situation:</p>\n<pre><code>typedef struct tagPyTypeObject\n{\n PyObject_HEAD;\n char *name;\n PrintFun print;\n AddFun add;\n HashFun hash;\n} PyTypeObject;\n\nPyTypeObject PyDict_Type=\n{\n PyObject_HEAD_INIT(&PyType_Type),\n "dict",\n dict_print,\n 0,\n 0\n};\n</code></pre>\n<p>Watch the <em>name</em> field. Using <code>gcc</code>, it compiles without warning, but in <code>g++</code> it will. I don't know why.</p>\n"
},
{
"answer_id": 4500719,
"author": "Dario",
"author_id": 550107,
"author_profile": "https://Stackoverflow.com/users/550107",
"pm_score": 2,
"selected": false,
"text": "<p>Just use type casting:</p>\n<pre><code>(char*) "test"\n</code></pre>\n"
},
{
"answer_id": 8140772,
"author": "EdH",
"author_id": 136087,
"author_profile": "https://Stackoverflow.com/users/136087",
"pm_score": 5,
"selected": false,
"text": "<p>Here is how to do it inline in a file, so you don't have to modify your Makefile.</p>\n\n<pre><code>// gets rid of annoying \"deprecated conversion from string constant blah blah\" warning\n#pragma GCC diagnostic ignored \"-Wwrite-strings\"\n</code></pre>\n\n<p>You can then later...</p>\n\n<pre><code>#pragma GCC diagnostic pop\n</code></pre>\n"
},
{
"answer_id": 10584743,
"author": "msn",
"author_id": 1393907,
"author_profile": "https://Stackoverflow.com/users/1393907",
"pm_score": -1,
"selected": false,
"text": "<p>Re <a href=\"https://stackoverflow.com/questions/59670/how-to-get-rid-of-deprecated-conversion-from-string-constant-to-char-warnin/3553118#3553118\">shindow's "answer"</a>:</p>\n<blockquote>\n<pre><code>PyTypeObject PyDict_Type=\n{\n ...\n\nPyTypeObject PyDict_Type=\n{\n PyObject_HEAD_INIT(&PyType_Type),\n "dict",\n dict_print,\n 0,\n 0\n};\n</code></pre>\n<p>Watch the <em>name</em> field. Using <code>gcc</code>, it compiles without warning, but in <code>g++</code> it will. I don't know why.</p>\n</blockquote>\n<p>In <em>gcc (Compiling C)</em>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings\" rel=\"nofollow noreferrer\">-Wno-write-strings</a> is active by default.</p>\n<p>In <em>g++ (Compiling C++)</em>, <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wwrite-strings\" rel=\"nofollow noreferrer\">-Wwrite-strings</a> is active by default</p>\n<p>This is why there is a different behaviour.</p>\n<p>For us, using macros of <code>Boost_python</code> generates such warnings.\nSo we use <em>-Wno-write-strings</em> when compiling C++ since we always use <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror\" rel=\"nofollow noreferrer\">-Werror</a>.</p>\n"
},
{
"answer_id": 10952861,
"author": "Md. Arafat Al Mahmud",
"author_id": 1096516,
"author_profile": "https://Stackoverflow.com/users/1096516",
"pm_score": 0,
"selected": false,
"text": "<p>Just use the <a href=\"https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-w\" rel=\"nofollow noreferrer\">-w</a> option for <code>g++</code>.</p>\n<p>Example:</p>\n<pre><code>g++ -w -o simple.o simple.cpp -lpthread\n</code></pre>\n<p>Remember this doesn't avoid deprecation. Rather, it prevents showing warning message on the terminal.</p>\n<p>Now if you really want to avoid deprecation, use the <em>const</em> keyword like this:</p>\n<pre><code>const char* s = "constant string"; \n</code></pre>\n"
},
{
"answer_id": 16867229,
"author": "John",
"author_id": 1735922,
"author_profile": "https://Stackoverflow.com/users/1735922",
"pm_score": 9,
"selected": false,
"text": "<p>Any functions into which you pass string literals <code>\"I am a string literal\"</code> should use <code>char const *</code> as the type instead of <code>char*</code>.</p>\n\n<p>If you're going to fix something, fix it right.</p>\n\n<p><strong>Explanation:</strong></p>\n\n<p>You can not use string literals to initialise strings that will be modified, because they are of type <code>const char*</code>. Casting away the constness to later modify them is <a href=\"https://stackoverflow.com/questions/3801557/can-we-change-the-value-of-an-object-defined-with-const-through-pointers\">undefined behaviour</a>, so you have to copy your <code>const char*</code> strings <code>char</code> by <code>char</code> into dynamically allocated <code>char*</code> strings in order to modify them.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>#include <iostream>\n\nvoid print(char* ch);\n\nvoid print(const char* ch) {\n std::cout<<ch;\n}\n\nint main() {\n print(\"Hello\");\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 24758381,
"author": "tejp124",
"author_id": 2514026,
"author_profile": "https://Stackoverflow.com/users/2514026",
"pm_score": 2,
"selected": false,
"text": "<p>Do typecasting from constant string to char pointer i.e.</p>\n\n<pre><code>char *s = (char *) \"constant string\";\n</code></pre>\n"
},
{
"answer_id": 26194079,
"author": "John",
"author_id": 4108715,
"author_profile": "https://Stackoverflow.com/users/4108715",
"pm_score": 4,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>void foo(char *s);\nfoo(\"constant string\");\n</code></pre>\n\n<p>This works:</p>\n\n<pre><code>void foo(const char s[]);\nfoo(\"constant string\");\n</code></pre>\n"
},
{
"answer_id": 30255068,
"author": "appapurapu",
"author_id": 2568673,
"author_profile": "https://Stackoverflow.com/users/2568673",
"pm_score": 4,
"selected": false,
"text": "<p>In C++, use the <code>const_cast</code> as like below</p>\n\n<pre><code>char* str = const_cast<char*>(\"Test string\");\n</code></pre>\n"
},
{
"answer_id": 33046116,
"author": "takataka",
"author_id": 5429122,
"author_profile": "https://Stackoverflow.com/users/5429122",
"pm_score": 5,
"selected": false,
"text": "<p>Replace</p>\n\n<pre><code>char *str = \"hello\";\n</code></pre>\n\n<p>with</p>\n\n<pre><code>char *str = (char*)\"hello\";\n</code></pre>\n\n<p>or if you are calling in function:</p>\n\n<pre><code>foo(\"hello\");\n</code></pre>\n\n<p>replace this with</p>\n\n<pre><code>foo((char*) \"hello\");\n</code></pre>\n"
},
{
"answer_id": 35813713,
"author": "Micheal Morrow",
"author_id": 5133527,
"author_profile": "https://Stackoverflow.com/users/5133527",
"pm_score": 0,
"selected": false,
"text": "<p>Picking from here and there, here comes this solution. This compiles clean.</p>\n<pre><code>const char * timeServer[] = { "pool.ntp.org" }; // 0 - Worldwide \n#define WHICH_NTP 0 // Which NTP server name to use.\n...\nsendNTPpacket(const_cast<char*>(timeServer[WHICH_NTP])); // send an NTP packet to a server\n...\nvoid sendNTPpacket(char* address) { code }\n</code></pre>\n<p>I know there's only one item in the timeServer array. But there could be more. The rest were commented out for now to save memory.</p>\n"
},
{
"answer_id": 47925509,
"author": "Sohrab",
"author_id": 2505235,
"author_profile": "https://Stackoverflow.com/users/2505235",
"pm_score": 1,
"selected": false,
"text": "<p>In C++, replace:</p>\n<pre><code>char *str = "hello";\n</code></pre>\n<p>with:</p>\n<pre><code>std::string str ("hello");\n</code></pre>\n<p>And if you want to compare it:</p>\n<pre><code>str.compare("HALLO");\n</code></pre>\n"
},
{
"answer_id": 49181562,
"author": "MyGEARStationcom",
"author_id": 5365814,
"author_profile": "https://Stackoverflow.com/users/5365814",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<p>I don't understand how to apply your solution :( – kalmanIsAGameChanger</p>\n</blockquote>\n<p>Working with an Arduino <a href=\"http://www.arduino.cc/en/Tutorial/Sketch\" rel=\"nofollow noreferrer\">sketch</a>, I had a function causing my warnings.</p>\n<p>Original function:</p>\n<pre><code>char StrContains(char *str, char *sfind)\n</code></pre>\n<p>To stop the warnings, I added the <em>const</em> in front of the char *str and the char *sfind.</p>\n<p>Modified:</p>\n<pre><code>char StrContains(const char *str, const char *sfind).\n</code></pre>\n<p>All warnings went away.</p>\n"
},
{
"answer_id": 63867734,
"author": "Anjan Parajuli",
"author_id": 13458906,
"author_profile": "https://Stackoverflow.com/users/13458906",
"pm_score": 0,
"selected": false,
"text": "<p>While passing <em>string constants</em> to functions, write it as:</p>\n<pre><code>void setpart(const char name[]);\n\nsetpart("Hello");\n</code></pre>\n<p>Instead of <code>const char name[]</code>, you could also write <code>const char \\*name</code>.</p>\n<p>It worked for me to remove this error:</p>\n<pre class=\"lang-none prettyprint-override\"><code>[Warning] deprecated conversion from string constant to 'char*' [-Wwrite-strings]\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59670",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3830/"
]
| I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:
>
> warning: deprecated conversion from string constant to ‘char\*’
>
>
>
Obviously, the correct way to fix this is to find every declaration like
```
char *s = "constant string";
```
or function call like:
```
void foo(char *s);
foo("constant string");
```
and make them `const char` pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with [-Werror](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror), so I need some way to stifle these warnings. How can I do that? | I believe passing [-Wno-write-strings](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings) to GCC will suppress this warning. |
59,680 | <p>In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server?</p>
| [
{
"answer_id": 59683,
"author": "Derek",
"author_id": 5440,
"author_profile": "https://Stackoverflow.com/users/5440",
"pm_score": 3,
"selected": false,
"text": "<pre><code>Set s = New NotesSession\nSet db = s.CurrentDatabase\n\nIf db.Server <> \"\" Then\n Set sName = New NotesName(db.Server)\nElse\n Set sName = New NotesName(s.Username)\nEnd If\n</code></pre>\n"
},
{
"answer_id": 62801,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>'initialize event of a WebQueryOpen agent\n\nDim s As New notessession \nDim servername As String\nservername = s.UserName\n</code></pre>\n"
},
{
"answer_id": 76770,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The sample code already provided is good but I also do it this way and just get the hierarchical name of the server:</p>\n\n<pre><code>Set s = New NotesSession\nSet db = s.CurrentDatabase\nIf db.Server <> \"\" Then\n Set sName = New NotesName(db.Server)\nElse\n Set sName = New NotesName(s.Username)\nEnd If\nServerName = sName.Abbreviated\n</code></pre>\n"
},
{
"answer_id": 2446498,
"author": "angryITguy",
"author_id": 193467,
"author_profile": "https://Stackoverflow.com/users/193467",
"pm_score": 0,
"selected": false,
"text": "<p>Gary's answer is the most appropriate. You can actually identify the server name using hierarchical syntax to.</p>\n\n<pre><code>dim session as new notesSession\ndim strCurrServer as string\ndim nmServer as notesName\n\nstrCurrServer = session.currentagent.servername\n' this bit is optional \nset nmServer = new notesName(strCurrServer)\n' then you can do stuff like this\nprint nmServer.Abbreviated \n</code></pre>\n\n<p>That would be the fastest (dirtiest?) way to get the server name from the webquery open agent. The notesName class is a handy object for dealing with hierarchical names\n<a href=\"http://publib.boulder.ibm.com/infocenter/domhelp/v8r0/index.jsp?topic=/com.ibm.designer.domino.main.doc/H_NOTESNAME_CLASS.html\" rel=\"nofollow noreferrer\">link text</a></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59680",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5440/"
]
| In a LotusScript Agent that is being run via WebQueryOpen, how do you get the name of the current server? | ```
Set s = New NotesSession
Set db = s.CurrentDatabase
If db.Server <> "" Then
Set sName = New NotesName(db.Server)
Else
Set sName = New NotesName(s.Username)
End If
``` |
59,711 | <p>Is there an equivalent operator to Haskell's list difference operator <code>\\</code> in F#?</p>
| [
{
"answer_id": 59814,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 3,
"selected": false,
"text": "<p>Nope... Just write it and make it an infix operator --using the set of special characters. Backslash (<code>\\</code>) is not in the list below, so it will not work as an infix operator. See the <a href=\"http://research.microsoft.com/fsharp/manual/spec2.aspx#_Toc207785578\" rel=\"nofollow noreferrer\">manual</a>:</p>\n\n<blockquote>\n <p>infix-op :=</p>\n\n<pre><code>or || & && <OP >OP $OP = |OP &OP ^OP :: -OP +OP *OP /OP %OP\n\n**OP\n</code></pre>\n \n <p>prefix-op :=</p>\n\n<pre><code>!OP ?OP ~OP -OP +OP % %% & &&\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 827771,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming you really want conventional set difference rather than the weird ordered-but-unsorted multiset subtraction that Haskell apparently provides, just convert the lists to sets using the built-in <code>set</code> function and then use the built-in <code>-</code> operator to compute the set difference:</p>\n\n<pre><code>set xs - set ys\n</code></pre>\n\n<p>For example:</p>\n\n<pre><code>> set [1..5] - set [2..4];;\nval it : Set<int> = seq [1; 5]\n</code></pre>\n"
},
{
"answer_id": 6085288,
"author": "Hans",
"author_id": 472522,
"author_profile": "https://Stackoverflow.com/users/472522",
"pm_score": 2,
"selected": false,
"text": "<p>Filter items from the set of the subtrahend:</p>\n\n<pre><code>let ( /-/ ) xs ys =\n let ySet = set ys\n let notInYSet x = not <| Set.contains x ySet\n List.filter notInYSet xs\n</code></pre>\n"
},
{
"answer_id": 12435807,
"author": "Ramon Snir",
"author_id": 327201,
"author_profile": "https://Stackoverflow.com/users/327201",
"pm_score": 4,
"selected": true,
"text": "<p>Was bounced, yet I believe it is worth to write here the implementation of <code>( /-/ )</code> (the F# version of Haskell's <code>\\\\</code>):</p>\n\n<pre><code>let flip f x y = f y x\n\nlet rec delete x = function\n | [] -> []\n | h :: t when x = h -> t\n | h :: t -> h :: delete x t\n\nlet inline ( /-/ ) xs ys = List.fold (flip delete) xs ys\n</code></pre>\n\n<p>This will operate as Haskell's <code>\\\\</code>, so that <code>(xs @ ys) /-/ xs = ys</code>. For example: <code>(7 :: [1 .. 5] @ [5 .. 11]) /-/ [4 .. 7]</code> evaluates into <code>[1; 2; 3; 5; 7; 8; 9; 10; 11]</code>.</p>\n"
},
{
"answer_id": 27955212,
"author": "Lay González",
"author_id": 1120410,
"author_profile": "https://Stackoverflow.com/users/1120410",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using this:</p>\n\n<pre><code>let (/-/) l1 l2 = List.filter (fun i -> not <| List.exists ((=) i) l2) l1\n</code></pre>\n\n<p>If anyone sees a problem, let me know.</p>\n\n<p>Is for lists, so there could be duplicates in the result. For example:</p>\n\n<pre><code>[1;1;2] /-/ [2;3] would be eq to [1;1]\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4592/"
]
| Is there an equivalent operator to Haskell's list difference operator `\\` in F#? | Was bounced, yet I believe it is worth to write here the implementation of `( /-/ )` (the F# version of Haskell's `\\`):
```
let flip f x y = f y x
let rec delete x = function
| [] -> []
| h :: t when x = h -> t
| h :: t -> h :: delete x t
let inline ( /-/ ) xs ys = List.fold (flip delete) xs ys
```
This will operate as Haskell's `\\`, so that `(xs @ ys) /-/ xs = ys`. For example: `(7 :: [1 .. 5] @ [5 .. 11]) /-/ [4 .. 7]` evaluates into `[1; 2; 3; 5; 7; 8; 9; 10; 11]`. |
59,719 | <p>I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).</p>
<p>Basically, I need to check for IsPostBack in JavaScript.</p>
<p>Thank you.</p>
| [
{
"answer_id": 59724,
"author": "NerdFury",
"author_id": 6146,
"author_profile": "https://Stackoverflow.com/users/6146",
"pm_score": 2,
"selected": false,
"text": "<p>You could put a hidden input on the page, and after the page loads, give it a value. Then you can check that field, if it was in the post data, it's a postback, otherwise it is not.</p>\n\n<p>There were two solutions that used server side code (ASP.NET specific) posted as responses. I think it is worth pointing out that this solution is technology agnostic since it uses client side features only, which are available in all major browsers.</p>\n"
},
{
"answer_id": 59725,
"author": "ctrlShiftBryan",
"author_id": 6161,
"author_profile": "https://Stackoverflow.com/users/6161",
"pm_score": 0,
"selected": false,
"text": "<p>You can create a hidden textbox with a value of 0. Put the onLoad() code in a if block that checks to make sure the hidden text box value is 0. if it is execute the code and set the textbox value to 1.</p>\n"
},
{
"answer_id": 59727,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Here is one way (put this in Page_Load):</p>\n\n<pre><code>if (this.IsPostBack)\n{\n Page.ClientScript.RegisterStartupScript(this.GetType(),\"PostbackKey\",\"<script type='text/javascript'>var isPostBack = true;</script>\");\n}\n</code></pre>\n\n<p>Then just check that variable in the JS.</p>\n"
},
{
"answer_id": 59730,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "<p>Server-side, write:</p>\n\n<pre><code>if(IsPostBack)\n{\n // NOTE: the following uses an overload of RegisterClientScriptBlock() \n // that will surround our string with the needed script tags \n ClientScript.RegisterClientScriptBlock(GetType(), \"IsPostBack\", \"var isPostBack = true;\", true);\n}\n</code></pre>\n\n<p>Then, in your script which runs for the onLoad, check for the existence of that variable:</p>\n\n<pre><code>if(isPostBack) {\n // do your thing\n}\n</code></pre>\n\n<hr>\n\n<p>You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the \"isPostBack\" variable will be undefined, which evaluates as false in that if statement.</p>\n"
},
{
"answer_id": 59739,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 0,
"selected": false,
"text": "<p>Lots of options here.</p>\n\n<p>For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.</p>\n\n<p>The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:</p>\n\n<pre><code><html>\n\n<?php\nif ($_POST['myVar']) {\n //postback\n echo '<script>var postingBack = true;</script>';\n //Do other processing\n} else {\n echo '<script>var postingBack = false;</script>'\n } ?>\n<script>\nfunction myLoader() {\n if (postingBack == false) {\n //Do stuff\n }\n }\n\n<body onLoad=\"myLoader():\"> ...\n</code></pre>\n"
},
{
"answer_id": 3557484,
"author": "Faustin",
"author_id": 429637,
"author_profile": "https://Stackoverflow.com/users/429637",
"pm_score": 5,
"selected": false,
"text": "<p>There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:</p>\n\n<pre><code>if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}\n</code></pre>\n\n<p>or</p>\n\n<pre><code>if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}\n</code></pre>\n"
},
{
"answer_id": 3981656,
"author": "md1337",
"author_id": 303468,
"author_profile": "https://Stackoverflow.com/users/303468",
"pm_score": 3,
"selected": false,
"text": "<p>The solution didn't work for me, I had to adapt it:</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n string script;\n if (IsPostBack)\n {\n script = \"var isPostBack = true;\";\n }\n else\n {\n script = \"var isPostBack = false;\";\n }\n Page.ClientScript.RegisterStartupScript(GetType(), \"IsPostBack\", script, true);\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 4219596,
"author": "Developer_India",
"author_id": 447461,
"author_profile": "https://Stackoverflow.com/users/447461",
"pm_score": 2,
"selected": false,
"text": "<p>Try this, in this JS we can check if it is post back or not and accordingly do operations in the respective loops. </p>\n\n<p></p>\n\n<pre><code> window.onload = isPostBack;\n\n function isPostBack() {\n\n if (!document.getElementById('clientSideIsPostBack')) {\n return false;\n }\n\n if (document.getElementById('clientSideIsPostBack').value == 'Y') {\n\n ***// DO ALL POST BACK RELATED WORK HERE***\n\n return true;\n }\n else {\n\n ***// DO ALL INITIAL LOAD RELATED WORK HERE***\n\n return false;\n }\n }\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 12850538,
"author": "iuppiter",
"author_id": 1566081,
"author_profile": "https://Stackoverflow.com/users/1566081",
"pm_score": 0,
"selected": false,
"text": "<p>Create a global variable in and apply the value</p>\n\n<pre><code><script>\n var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;\n</script>\n</code></pre>\n\n<p>Then you can reference it from elsewhere</p>\n"
},
{
"answer_id": 15159545,
"author": "Wily AO",
"author_id": 2123781,
"author_profile": "https://Stackoverflow.com/users/2123781",
"pm_score": 4,
"selected": false,
"text": "<p>hi try the following ...</p>\n\n<pre><code>function pageLoad (sender, args) {\n\nalert (args._isPartialLoad);\n\n}\n</code></pre>\n\n<p>the result is a Boolean</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3661/"
]
| I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).
Basically, I need to check for IsPostBack in JavaScript.
Thank you. | Server-side, write:
```
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
```
Then, in your script which runs for the onLoad, check for the existence of that variable:
```
if(isPostBack) {
// do your thing
}
```
---
You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement. |
59,726 | <p>Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically?</p>
| [
{
"answer_id": 59738,
"author": "Dale Ragan",
"author_id": 1117,
"author_profile": "https://Stackoverflow.com/users/1117",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"http://msdn.microsoft.com/en-us/library/system.environment.aspx\" rel=\"nofollow noreferrer\">System.Environment</a> class. It has a property for retrieving the machine name, which is retrieved from the NetBios. Unless I am misunderstanding your question.</p>\n"
},
{
"answer_id": 59781,
"author": "chrissie1",
"author_id": 2936,
"author_profile": "https://Stackoverflow.com/users/2936",
"pm_score": 0,
"selected": false,
"text": "<p>or My.Computer.Name</p>\n"
},
{
"answer_id": 229049,
"author": "alexandrul",
"author_id": 19756,
"author_profile": "https://Stackoverflow.com/users/19756",
"pm_score": 1,
"selected": false,
"text": "<p>If you need the computer description, it is stored in registry:</p>\n\n<ul>\n<li>key: <code>HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\lanmanserver\\parameters</code></li>\n<li>value name: <code>srvcomment</code></li>\n<li>data type: <code>REG_SZ (string)</code></li>\n</ul>\n\n<p>AFAIK it has nothing to do with any domain server, or with the network the PC is attached to.</p>\n\n<p>For anything related to the network, I am using the following:</p>\n\n<ul>\n<li>NETBIOS name: <code>System.Environment.MachineName</code></li>\n<li>host name: <code>System.Net.Dns.GetHostName()</code></li>\n<li>DNS name: <code>System.Net.Dns.GetHostEntry(\"LocalHost\").HostName</code></li>\n</ul>\n\n<p>If the PC has multiple NETBIOS names, I do not know any other method but to group the names based on the IP address they resolve to, and even this is not reliable if the PC has multiple network interfaces.</p>\n"
},
{
"answer_id": 231431,
"author": "Murali Suriar",
"author_id": 6306,
"author_profile": "https://Stackoverflow.com/users/6306",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not a .NET programmer, but the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.dns.gethostentry.aspx\" rel=\"nofollow noreferrer\">System.Net.DNS.GetHostEntry</a> method looks like what you need. It returns an instance of the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.iphostentry_members.aspx\" rel=\"nofollow noreferrer\">IPHostEntry</a> class which contains the <a href=\"http://msdn.microsoft.com/en-us/library/system.net.iphostentry.aliases.aspx\" rel=\"nofollow noreferrer\">Aliases</a> property.</p>\n"
},
{
"answer_id": 239489,
"author": "msulis",
"author_id": 9317,
"author_profile": "https://Stackoverflow.com/users/9317",
"pm_score": 3,
"selected": true,
"text": "<p>Since you can have multiple network interfaces, each of which can have multiple IPs, and any single IP can have multiple names that can resolve to it, there may be more than one.</p>\n\n<p>If you want to know all the names by which your DNS server knows your machine, you can loop through them all like this:</p>\n\n<pre><code>public ArrayList GetAllDnsNames() {\n ArrayList names = new ArrayList();\n IPHostEntry host;\n //check each Network Interface\n foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {\n //check each IP address claimed by this Network Interface\n foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) {\n //get the DNS host entry for this IP address\n host = System.Net.Dns.GetHostEntry(i.Address.ToString());\n if (!names.Contains(host.HostName)) {\n names.Add(host.HostName);\n }\n //check each alias, adding each to the list\n foreach (string s in host.Aliases) {\n if (!names.Contains(s)) {\n names.Add(s);\n }\n }\n }\n }\n //add \"simple\" host name - above loop returns fully qualified domain names (FQDNs)\n //but this method returns just the machine name without domain information\n names.Add(System.Net.Dns.GetHostName());\n\n return names;\n}\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5287/"
]
| Is there a way in .net 2.0 to discover the network alias for the machine that my code is running on? Specifically, if my workgroup sees my machine as //jekkedev01, how do I retrieve that name programmatically? | Since you can have multiple network interfaces, each of which can have multiple IPs, and any single IP can have multiple names that can resolve to it, there may be more than one.
If you want to know all the names by which your DNS server knows your machine, you can loop through them all like this:
```
public ArrayList GetAllDnsNames() {
ArrayList names = new ArrayList();
IPHostEntry host;
//check each Network Interface
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) {
//check each IP address claimed by this Network Interface
foreach (UnicastIPAddressInformation i in nic.GetIPProperties().UnicastAddresses) {
//get the DNS host entry for this IP address
host = System.Net.Dns.GetHostEntry(i.Address.ToString());
if (!names.Contains(host.HostName)) {
names.Add(host.HostName);
}
//check each alias, adding each to the list
foreach (string s in host.Aliases) {
if (!names.Contains(s)) {
names.Add(s);
}
}
}
}
//add "simple" host name - above loop returns fully qualified domain names (FQDNs)
//but this method returns just the machine name without domain information
names.Add(System.Net.Dns.GetHostName());
return names;
}
``` |
59,734 | <p>My application is using <strong>Dojo 1.1.1</strong> on an <em>SSL-only</em> website. It is currently taking advantage of <code>dijit.ProgressBar</code> and a <code>dijit.form.DateTextBox</code>.</p>
<p>Everything works fabulous in <em>Firefox 2 & 3</em>, but as soon as I try the same scripts in <em>IE7</em> the results are an annoying Security Information dialog:</p>
<blockquote>
<p>This page contains both secure and non-secure items. Do you want to display the non-secure items?</p>
</blockquote>
<p>I have scrutinized the page for any <em>non-HTTPS</em> reference to no avail. It appears to be something specific to <code>dojo.js</code>. There use to be an <code>iframe</code> glitch where the <code>src</code> was set to nothing, but this appears to be fixed now (on review of the source).</p>
<p>Anyone else having this problem? What are the best-practices for getting <em>Dojo</em> to play well with <em>IE</em> on an <em>SSL-only</em> web server?</p>
| [
{
"answer_id": 60433,
"author": "Till",
"author_id": 2859,
"author_profile": "https://Stackoverflow.com/users/2859",
"pm_score": 1,
"selected": false,
"text": "<p>If your page is loading files from a non-https URL Firefox should tell you the same thing. Instead of an error the lock symbol at the bottom (in the status bar) should be crossed out. Are you sure that is not the case?</p>\n\n<p>If you see the symbol, click on it and check which files are \"unsecure\".</p>\n"
},
{
"answer_id": 72805,
"author": "esarjeant",
"author_id": 644,
"author_profile": "https://Stackoverflow.com/users/644",
"pm_score": 3,
"selected": false,
"text": "<p>After reviewing the JavaScript sourcecode for Dijit, I thought it was likely the error results from an \"insecure\" refrence to a dynamically generated IFRAME. Note there are two versions of the script file, the uncompressed represents the original source (dijit.js.uncompressed.js) and the standard (dijit.js) has been compressed for optimal transfer time. </p>\n\n<p>Since the uncompressed version is the most readable, I will describe my solution based on that. At line #1023, an IFRAME is rendered in JavaScript:</p>\n\n<pre><code>if(dojo.isIE){\n var html=\"<iframe src='javascript:\\\"\\\"'\"\n + \" style='position: absolute; left: 0px; top: 0px;\"\n + \"z-index: -1; filter:Alpha(Opacity=\\\"0\\\");'>\";\n iframe = dojo.doc.createElement(html);\n}else{...\n</code></pre>\n\n<p>What's the problem? IE doesn't know if the src for the IFRAME is \"secure\" - so I replaced it with the following:</p>\n\n<pre><code>if(dojo.isIE){\n var html=\"<iframe src='javascript:void(0);'\"\n + \" style='position: absolute; left: 0px; top: 0px;\"\n + \"z-index: -1; filter:Alpha(Opacity=\\\"0\\\");'>\";\n iframe = dojo.doc.createElement(html);\n}else{...\n</code></pre>\n\n<p>This is the most common problem with JavaScript toolkits and SSL in IE. Since IFRAME's are used as shims due to poor overlay support for DIV's, this problem is extremely prevalent. </p>\n\n<p>My first 5-10 page reloads are fine, but then the security error starts popping up again. How is this possible? The same page is \"secure\" for 5 reloads and then it is selected by IE as \"insecure\" when loaded the 6th time.</p>\n\n<p>As it turns out, there is also a background image being set in the onload event for dijit.wai (line #1325). This reads something like this;</p>\n\n<pre><code>div.style.cssText = 'border: 1px solid;'\n + 'border-color:red green;'\n + 'position: absolute;'\n + 'height: 5px;'\n + 'top: -999px;'\n + 'background-image: url(\"' + dojo.moduleUrl(\"dojo\", \"resources/blank.gif\") + '\");';\n</code></pre>\n\n<p>This won't work because the background-image tag doesn't include HTTPs. Despite the fact that the location is relative, IE7 doesn't know if it's secure so the warning is posed.</p>\n\n<p>In this particular instance, this CSS is used to test for Accessibility (A11y) in Dojo. Since this is not something my application will support and since there are other general buggy issues with this method, I opted to remove everything in the onload() for dijit.wai.</p>\n\n<p>All is good! No sporadic security problems with the page loads.</p>\n"
},
{
"answer_id": 7589230,
"author": "ZMorek",
"author_id": 671432,
"author_profile": "https://Stackoverflow.com/users/671432",
"pm_score": 1,
"selected": false,
"text": "<p>If you're using CDN you can include all modules by HTTPS as seen <a href=\"https://groups.google.com/group/google-ajax-search-api/browse_thread/thread/08f8643c75311d05\" rel=\"nofollow\">here</a>.</p>\n\n<pre><code><script type=\"text/javascript\">\ndjConfig = {\n modulePaths: {\n \"dojo\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo\",\n \"dijit\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dijit\",\n \"dojox\": \"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojox\"\n }\n};\n\n</script>\n<script src=\"https://ajax.googleapis.com/ajax/libs/dojo/1.3.2/dojo/dojo.xd.js\" type=\"text/javascript\"></script>\n</code></pre>\n\n<p>You can test with various versions if you want. Currently the most recent is <code>1.6.1</code></p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/644/"
]
| My application is using **Dojo 1.1.1** on an *SSL-only* website. It is currently taking advantage of `dijit.ProgressBar` and a `dijit.form.DateTextBox`.
Everything works fabulous in *Firefox 2 & 3*, but as soon as I try the same scripts in *IE7* the results are an annoying Security Information dialog:
>
> This page contains both secure and non-secure items. Do you want to display the non-secure items?
>
>
>
I have scrutinized the page for any *non-HTTPS* reference to no avail. It appears to be something specific to `dojo.js`. There use to be an `iframe` glitch where the `src` was set to nothing, but this appears to be fixed now (on review of the source).
Anyone else having this problem? What are the best-practices for getting *Dojo* to play well with *IE* on an *SSL-only* web server? | After reviewing the JavaScript sourcecode for Dijit, I thought it was likely the error results from an "insecure" refrence to a dynamically generated IFRAME. Note there are two versions of the script file, the uncompressed represents the original source (dijit.js.uncompressed.js) and the standard (dijit.js) has been compressed for optimal transfer time.
Since the uncompressed version is the most readable, I will describe my solution based on that. At line #1023, an IFRAME is rendered in JavaScript:
```
if(dojo.isIE){
var html="<iframe src='javascript:\"\"'"
+ " style='position: absolute; left: 0px; top: 0px;"
+ "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
iframe = dojo.doc.createElement(html);
}else{...
```
What's the problem? IE doesn't know if the src for the IFRAME is "secure" - so I replaced it with the following:
```
if(dojo.isIE){
var html="<iframe src='javascript:void(0);'"
+ " style='position: absolute; left: 0px; top: 0px;"
+ "z-index: -1; filter:Alpha(Opacity=\"0\");'>";
iframe = dojo.doc.createElement(html);
}else{...
```
This is the most common problem with JavaScript toolkits and SSL in IE. Since IFRAME's are used as shims due to poor overlay support for DIV's, this problem is extremely prevalent.
My first 5-10 page reloads are fine, but then the security error starts popping up again. How is this possible? The same page is "secure" for 5 reloads and then it is selected by IE as "insecure" when loaded the 6th time.
As it turns out, there is also a background image being set in the onload event for dijit.wai (line #1325). This reads something like this;
```
div.style.cssText = 'border: 1px solid;'
+ 'border-color:red green;'
+ 'position: absolute;'
+ 'height: 5px;'
+ 'top: -999px;'
+ 'background-image: url("' + dojo.moduleUrl("dojo", "resources/blank.gif") + '");';
```
This won't work because the background-image tag doesn't include HTTPs. Despite the fact that the location is relative, IE7 doesn't know if it's secure so the warning is posed.
In this particular instance, this CSS is used to test for Accessibility (A11y) in Dojo. Since this is not something my application will support and since there are other general buggy issues with this method, I opted to remove everything in the onload() for dijit.wai.
All is good! No sporadic security problems with the page loads. |
59,743 | <p>How many possible combinations of the variables a,b,c,d,e are possible if I know that:</p>
<pre><code>a+b+c+d+e = 500
</code></pre>
<p>and that they are all integers and >= 0, so I know they are finite.</p>
| [
{
"answer_id": 59748,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>If they are a real numbers then infinite ... otherwise it is a bit trickier.</p>\n\n<p>(OK, for any computer representation of a real number there would be a finite count ... but it would be big!)</p>\n"
},
{
"answer_id": 59783,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 1,
"selected": false,
"text": "<p>One way of looking at the problem is as follows:</p>\n\n<p>First, a can be any value from 0 to 500. Then if follows that b+c+d+e = 500-a. This reduces the problem by one variable. Recurse until done. </p>\n\n<p>For example, if a is 500, then b+c+d+e=0 which means that for the case of a = 500, there is only one combination of values for b,c,d and e.</p>\n\n<p>If a is 300, then b+c+d+e=200, which is in fact the same problem as the original problem, just reduced by one variable.</p>\n\n<p>Note: As Chris points out, this is a horrible way of actually trying to solve the problem.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/59743/number-of-possible-combinations#59833\" title=\"See his reply\">link text</a></p>\n"
},
{
"answer_id": 59792,
"author": "Leahn Novash",
"author_id": 5954,
"author_profile": "https://Stackoverflow.com/users/5954",
"pm_score": -1,
"selected": false,
"text": "<p>Including negatives? Infinite.</p>\n\n<p>Including only positives? In this case they wouldn't be called \"integers\", but \"naturals\", instead. In this case... I can't really solve this, I wish I could, but my math is too rusty. There is probably some crazy integral way to solve this. I can give some pointers for the math skilled around.</p>\n\n<p>being x the end result,\nthe range of a would be from 0 to x,\nthe range of b would be from 0 to (x - a),\nthe range of c would be from 0 to (x - a - b),\nand so forth until the e.</p>\n\n<p>The answer is the sum of all those possibilities.</p>\n\n<p>I am trying to find some more direct formula on Google, but I am really low on my Google-Fu today...</p>\n"
},
{
"answer_id": 59824,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p><strong>The answer to your question is 2656615626</strong>.</p>\n\n<p>Here's the code that generates the answer:</p>\n\n<pre><code>public static long getNumCombinations( int summands, int sum )\n{\n if ( summands <= 1 )\n return 1;\n long combos = 0;\n for ( int a = 0 ; a <= sum ; a++ )\n combos += getNumCombinations( summands-1, sum-a );\n return combos;\n}\n</code></pre>\n\n<p>In your case, <code>summands</code> is 5 and <code>sum</code> is 500.</p>\n\n<p><strong>Note that this code is slow</strong>. If you need speed, cache the results from <code>summand,sum</code> pairs.</p>\n\n<p>I'm assuming you want numbers <code>>=0</code>. If you want <code>>0</code>, replace the loop initialization with <code>a = 1</code> and the loop condition with <code>a < sum</code>. I'm also assuming you want permutations (e.g. <code>1+2+3+4+5</code> plus <code>2+1+3+4+5</code> etc). You could change the for-loop if you wanted <code>a >= b >= c >= d >= e</code>.</p>\n"
},
{
"answer_id": 59831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this problem for my dad a couple months ago...extend for your use. These tend to be one time problems so I didn't go for the most reusable...</p>\n\n<p>a+b+c+d = sum</p>\n\n<p>i = number of combinations</p>\n\n<pre><code> for (a=0;a<=sum;a++)\n {\n for (b = 0; b <= (sum - a); b++)\n {\n for (c = 0; c <= (sum - a - b); c++)\n {\n //d = sum - a - b - c;\n i++\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 59833,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "<p>@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are \"overlapping subproblems.\" I.e., If you choose <code>a</code> as <code>1</code> and <code>b</code> as <code>2</code>, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing <code>a</code> as <code>2</code> and <code>b</code> as <code>1</code>. (The number of such coincidences explodes as the numbers grow.)</p>\n\n<p>The traditional way to attack such a problem is <a href=\"http://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">dynamic programming</a>: build a table bottom-up of the solutions to the sub-problems (starting with \"how many combinations of 1 variable add up to 0?\") then building up through iteration (the solution to \"how many combinations of <em>n</em> variables add up to <em>k</em>?\" is the sum of the solutions to \"how many combinations of <em>n-1</em> variables add up to <em>j</em>?\" with 0 <= <em>j</em> <= <em>k</em>). </p>\n\n<pre><code>public static long getCombos( int n, int sum ) {\n // tab[i][j] is how many combinations of (i+1) vars add up to j\n long[][] tab = new long[n][sum+1];\n // # of combos of 1 var for any sum is 1\n for( int j=0; j < tab[0].length; ++j ) {\n tab[0][j] = 1;\n }\n for( int i=1; i < tab.length; ++i ) {\n for( int j=0; j < tab[i].length; ++j ) {\n // # combos of (i+1) vars adding up to j is the sum of the #\n // of combos of i vars adding up to k, for all 0 <= k <= j\n // (choosing i vars forces the choice of the (i+1)st).\n tab[i][j] = 0;\n for( int k=0; k <= j; ++k ) {\n tab[i][j] += tab[i-1][k];\n }\n }\n }\n return tab[n-1][sum];\n}\n</code></pre>\n\n<pre>\n$ time java Combos\n2656615626\n\nreal 0m0.151s\nuser 0m0.120s\nsys 0m0.012s\n</pre>\n"
},
{
"answer_id": 60107,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>This would actually be a good question to ask on an interview as it is simple enough that you could write up on a white board, but complex enough that it might trip someone up if they don't think carefully enough about it. Also, you can also for two different answers which cause the implementation to be quite different.</p>\n\n<p><strong>Order Matters</strong><br />\nIf the order matters then any solution needs to allow for zero to appear for any of the variables; thus, the most straight forward solution would be as follows:</p>\n\n<pre><code>public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 0; a <= 500; a++) {\n for (int b = 0; b <= (500 - a); b++) {\n for (int c = 0; c <= (500 - a - b); c++) {\n for (int d = 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n</code></pre>\n\n<p>Which returns 2656615626.</p>\n\n<p><strong>Order Does Not Matter</strong><br />\nIf the order does not matter then the solution is not that much harder as you just need to make sure that zero isn't possible unless sum has already been found.</p>\n\n<pre><code>public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 1; a <= 500; a++) {\n for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) {\n for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) {\n for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n</code></pre>\n\n<p>Which returns 2573155876.</p>\n"
},
{
"answer_id": 13333456,
"author": "neel",
"author_id": 1215889,
"author_profile": "https://Stackoverflow.com/users/1215889",
"pm_score": 0,
"selected": false,
"text": "<p>It has general formulae, if<br>\na + b + c + d = N<br>\nThen number of non-negative integral solution will be <code>C(N + number_of_variable - 1, N)</code></p>\n"
},
{
"answer_id": 19784359,
"author": "user2955441",
"author_id": 2955441,
"author_profile": "https://Stackoverflow.com/users/2955441",
"pm_score": 0,
"selected": false,
"text": "<p>@Chris Conway answer is correct. I have tested with a simple code that is suitable for smaller sums.</p>\n\n<pre><code> long counter = 0;\n int sum=25;\n\n for (int a = 0; a <= sum; a++) {\n for (int b = 0; b <= sum ; b++) {\n for (int c = 0; c <= sum; c++) {\n for (int d = 0; d <= sum; d++) {\n for (int e = 0; e <= sum; e++) {\n if ((a+b+c+d+e)==sum) counter=counter+1L;\n\n }\n }\n }\n }\n }\n System.out.println(\"counter e \"+counter);\n</code></pre>\n"
},
{
"answer_id": 44703816,
"author": "Neil Wang",
"author_id": 8128469,
"author_profile": "https://Stackoverflow.com/users/8128469",
"pm_score": 0,
"selected": false,
"text": "<p>The answer in math is 504!/(500! * 4!).</p>\n\n<p>Formally, for x1+x2+...xk=n, the number of combination of nonnegative number x1,...xk is the binomial coefficient: (k-1)-combination out of a set containing (n+k-1) elements.</p>\n\n<p>The intuition is to choose (k-1) points from (n+k-1) points and use the number of points between two chosen points to represent a number in x1,..xk.</p>\n\n<p>Sorry about the poor math edition for my fist time answering Stack Overflow.</p>\n\n<p><code>Just a test for code block</code></p>\n\n<pre><code>Just a test for code block\n\n Just a test for code block\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1815/"
]
| How many possible combinations of the variables a,b,c,d,e are possible if I know that:
```
a+b+c+d+e = 500
```
and that they are all integers and >= 0, so I know they are finite. | @Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose `a` as `1` and `b` as `2`, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing `a` as `2` and `b` as `1`. (The number of such coincidences explodes as the numbers grow.)
The traditional way to attack such a problem is [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming): build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of *n* variables add up to *k*?" is the sum of the solutions to "how many combinations of *n-1* variables add up to *j*?" with 0 <= *j* <= *k*).
```
public static long getCombos( int n, int sum ) {
// tab[i][j] is how many combinations of (i+1) vars add up to j
long[][] tab = new long[n][sum+1];
// # of combos of 1 var for any sum is 1
for( int j=0; j < tab[0].length; ++j ) {
tab[0][j] = 1;
}
for( int i=1; i < tab.length; ++i ) {
for( int j=0; j < tab[i].length; ++j ) {
// # combos of (i+1) vars adding up to j is the sum of the #
// of combos of i vars adding up to k, for all 0 <= k <= j
// (choosing i vars forces the choice of the (i+1)st).
tab[i][j] = 0;
for( int k=0; k <= j; ++k ) {
tab[i][j] += tab[i-1][k];
}
}
}
return tab[n-1][sum];
}
```
```
$ time java Combos
2656615626
real 0m0.151s
user 0m0.120s
sys 0m0.012s
``` |
59,761 | <p>I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks.</p>
<p>Long Edit: </p>
<p>@apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page).</p>
<p>As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched.</p>
<p>This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done.</p>
<p>Thanks.</p>
| [
{
"answer_id": 59748,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 0,
"selected": false,
"text": "<p>If they are a real numbers then infinite ... otherwise it is a bit trickier.</p>\n\n<p>(OK, for any computer representation of a real number there would be a finite count ... but it would be big!)</p>\n"
},
{
"answer_id": 59783,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 1,
"selected": false,
"text": "<p>One way of looking at the problem is as follows:</p>\n\n<p>First, a can be any value from 0 to 500. Then if follows that b+c+d+e = 500-a. This reduces the problem by one variable. Recurse until done. </p>\n\n<p>For example, if a is 500, then b+c+d+e=0 which means that for the case of a = 500, there is only one combination of values for b,c,d and e.</p>\n\n<p>If a is 300, then b+c+d+e=200, which is in fact the same problem as the original problem, just reduced by one variable.</p>\n\n<p>Note: As Chris points out, this is a horrible way of actually trying to solve the problem.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/59743/number-of-possible-combinations#59833\" title=\"See his reply\">link text</a></p>\n"
},
{
"answer_id": 59792,
"author": "Leahn Novash",
"author_id": 5954,
"author_profile": "https://Stackoverflow.com/users/5954",
"pm_score": -1,
"selected": false,
"text": "<p>Including negatives? Infinite.</p>\n\n<p>Including only positives? In this case they wouldn't be called \"integers\", but \"naturals\", instead. In this case... I can't really solve this, I wish I could, but my math is too rusty. There is probably some crazy integral way to solve this. I can give some pointers for the math skilled around.</p>\n\n<p>being x the end result,\nthe range of a would be from 0 to x,\nthe range of b would be from 0 to (x - a),\nthe range of c would be from 0 to (x - a - b),\nand so forth until the e.</p>\n\n<p>The answer is the sum of all those possibilities.</p>\n\n<p>I am trying to find some more direct formula on Google, but I am really low on my Google-Fu today...</p>\n"
},
{
"answer_id": 59824,
"author": "Jason Cohen",
"author_id": 4926,
"author_profile": "https://Stackoverflow.com/users/4926",
"pm_score": 3,
"selected": false,
"text": "<p><strong>The answer to your question is 2656615626</strong>.</p>\n\n<p>Here's the code that generates the answer:</p>\n\n<pre><code>public static long getNumCombinations( int summands, int sum )\n{\n if ( summands <= 1 )\n return 1;\n long combos = 0;\n for ( int a = 0 ; a <= sum ; a++ )\n combos += getNumCombinations( summands-1, sum-a );\n return combos;\n}\n</code></pre>\n\n<p>In your case, <code>summands</code> is 5 and <code>sum</code> is 500.</p>\n\n<p><strong>Note that this code is slow</strong>. If you need speed, cache the results from <code>summand,sum</code> pairs.</p>\n\n<p>I'm assuming you want numbers <code>>=0</code>. If you want <code>>0</code>, replace the loop initialization with <code>a = 1</code> and the loop condition with <code>a < sum</code>. I'm also assuming you want permutations (e.g. <code>1+2+3+4+5</code> plus <code>2+1+3+4+5</code> etc). You could change the for-loop if you wanted <code>a >= b >= c >= d >= e</code>.</p>\n"
},
{
"answer_id": 59831,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I solved this problem for my dad a couple months ago...extend for your use. These tend to be one time problems so I didn't go for the most reusable...</p>\n\n<p>a+b+c+d = sum</p>\n\n<p>i = number of combinations</p>\n\n<pre><code> for (a=0;a<=sum;a++)\n {\n for (b = 0; b <= (sum - a); b++)\n {\n for (c = 0; c <= (sum - a - b); c++)\n {\n //d = sum - a - b - c;\n i++\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 59833,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 5,
"selected": true,
"text": "<p>@Torlack, @Jason Cohen: Recursion is a bad idea here, because there are \"overlapping subproblems.\" I.e., If you choose <code>a</code> as <code>1</code> and <code>b</code> as <code>2</code>, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing <code>a</code> as <code>2</code> and <code>b</code> as <code>1</code>. (The number of such coincidences explodes as the numbers grow.)</p>\n\n<p>The traditional way to attack such a problem is <a href=\"http://en.wikipedia.org/wiki/Dynamic_programming\" rel=\"nofollow noreferrer\">dynamic programming</a>: build a table bottom-up of the solutions to the sub-problems (starting with \"how many combinations of 1 variable add up to 0?\") then building up through iteration (the solution to \"how many combinations of <em>n</em> variables add up to <em>k</em>?\" is the sum of the solutions to \"how many combinations of <em>n-1</em> variables add up to <em>j</em>?\" with 0 <= <em>j</em> <= <em>k</em>). </p>\n\n<pre><code>public static long getCombos( int n, int sum ) {\n // tab[i][j] is how many combinations of (i+1) vars add up to j\n long[][] tab = new long[n][sum+1];\n // # of combos of 1 var for any sum is 1\n for( int j=0; j < tab[0].length; ++j ) {\n tab[0][j] = 1;\n }\n for( int i=1; i < tab.length; ++i ) {\n for( int j=0; j < tab[i].length; ++j ) {\n // # combos of (i+1) vars adding up to j is the sum of the #\n // of combos of i vars adding up to k, for all 0 <= k <= j\n // (choosing i vars forces the choice of the (i+1)st).\n tab[i][j] = 0;\n for( int k=0; k <= j; ++k ) {\n tab[i][j] += tab[i-1][k];\n }\n }\n }\n return tab[n-1][sum];\n}\n</code></pre>\n\n<pre>\n$ time java Combos\n2656615626\n\nreal 0m0.151s\nuser 0m0.120s\nsys 0m0.012s\n</pre>\n"
},
{
"answer_id": 60107,
"author": "rjzii",
"author_id": 1185,
"author_profile": "https://Stackoverflow.com/users/1185",
"pm_score": 2,
"selected": false,
"text": "<p>This would actually be a good question to ask on an interview as it is simple enough that you could write up on a white board, but complex enough that it might trip someone up if they don't think carefully enough about it. Also, you can also for two different answers which cause the implementation to be quite different.</p>\n\n<p><strong>Order Matters</strong><br />\nIf the order matters then any solution needs to allow for zero to appear for any of the variables; thus, the most straight forward solution would be as follows:</p>\n\n<pre><code>public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 0; a <= 500; a++) {\n for (int b = 0; b <= (500 - a); b++) {\n for (int c = 0; c <= (500 - a - b); c++) {\n for (int d = 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n</code></pre>\n\n<p>Which returns 2656615626.</p>\n\n<p><strong>Order Does Not Matter</strong><br />\nIf the order does not matter then the solution is not that much harder as you just need to make sure that zero isn't possible unless sum has already been found.</p>\n\n<pre><code>public class Combos {\n public static void main() {\n long counter = 0;\n\n for (int a = 1; a <= 500; a++) {\n for (int b = (a != 500) ? 1 : 0; b <= (500 - a); b++) {\n for (int c = (a + b != 500) ? 1 : 0; c <= (500 - a - b); c++) {\n for (int d = (a + b + c != 500) ? 1 : 0; d <= (500 - a - b - c); d++) {\n counter++;\n }\n }\n }\n }\n System.out.println(counter);\n }\n}\n</code></pre>\n\n<p>Which returns 2573155876.</p>\n"
},
{
"answer_id": 13333456,
"author": "neel",
"author_id": 1215889,
"author_profile": "https://Stackoverflow.com/users/1215889",
"pm_score": 0,
"selected": false,
"text": "<p>It has general formulae, if<br>\na + b + c + d = N<br>\nThen number of non-negative integral solution will be <code>C(N + number_of_variable - 1, N)</code></p>\n"
},
{
"answer_id": 19784359,
"author": "user2955441",
"author_id": 2955441,
"author_profile": "https://Stackoverflow.com/users/2955441",
"pm_score": 0,
"selected": false,
"text": "<p>@Chris Conway answer is correct. I have tested with a simple code that is suitable for smaller sums.</p>\n\n<pre><code> long counter = 0;\n int sum=25;\n\n for (int a = 0; a <= sum; a++) {\n for (int b = 0; b <= sum ; b++) {\n for (int c = 0; c <= sum; c++) {\n for (int d = 0; d <= sum; d++) {\n for (int e = 0; e <= sum; e++) {\n if ((a+b+c+d+e)==sum) counter=counter+1L;\n\n }\n }\n }\n }\n }\n System.out.println(\"counter e \"+counter);\n</code></pre>\n"
},
{
"answer_id": 44703816,
"author": "Neil Wang",
"author_id": 8128469,
"author_profile": "https://Stackoverflow.com/users/8128469",
"pm_score": 0,
"selected": false,
"text": "<p>The answer in math is 504!/(500! * 4!).</p>\n\n<p>Formally, for x1+x2+...xk=n, the number of combination of nonnegative number x1,...xk is the binomial coefficient: (k-1)-combination out of a set containing (n+k-1) elements.</p>\n\n<p>The intuition is to choose (k-1) points from (n+k-1) points and use the number of points between two chosen points to represent a number in x1,..xk.</p>\n\n<p>Sorry about the poor math edition for my fist time answering Stack Overflow.</p>\n\n<p><code>Just a test for code block</code></p>\n\n<pre><code>Just a test for code block\n\n Just a test for code block\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/78/"
]
| I need to disable specific keys (Ctrl and Backspace) in Internet Explorer 6. Is there a registry hack to do this. It has to be IE6. Thanks.
Long Edit:
@apandit: Whoops. I need to more specific about the backspace thing. When I say disable backspace, I mean disable the ability for Backspace to mimic the Back browser button. In IE, pressing Backspace when the focus is not in a text entry field is equivalent to pressing Back (browsing to the previous page).
As for the Ctrl key. There are some pages which have links which create new IE windows. I have the popup blocker turned on, which block this. But, Ctrl clicking result in the new window being launched.
This is for a kiosk application, which is currently a web based application. Clients do not have the funds at this time to make their site kiosk friendly. Things like URL filtering and disabling the URL entry field is already done.
Thanks. | @Torlack, @Jason Cohen: Recursion is a bad idea here, because there are "overlapping subproblems." I.e., If you choose `a` as `1` and `b` as `2`, then you have 3 variables left that should add up to 497; you arrive at the same subproblem by choosing `a` as `2` and `b` as `1`. (The number of such coincidences explodes as the numbers grow.)
The traditional way to attack such a problem is [dynamic programming](http://en.wikipedia.org/wiki/Dynamic_programming): build a table bottom-up of the solutions to the sub-problems (starting with "how many combinations of 1 variable add up to 0?") then building up through iteration (the solution to "how many combinations of *n* variables add up to *k*?" is the sum of the solutions to "how many combinations of *n-1* variables add up to *j*?" with 0 <= *j* <= *k*).
```
public static long getCombos( int n, int sum ) {
// tab[i][j] is how many combinations of (i+1) vars add up to j
long[][] tab = new long[n][sum+1];
// # of combos of 1 var for any sum is 1
for( int j=0; j < tab[0].length; ++j ) {
tab[0][j] = 1;
}
for( int i=1; i < tab.length; ++i ) {
for( int j=0; j < tab[i].length; ++j ) {
// # combos of (i+1) vars adding up to j is the sum of the #
// of combos of i vars adding up to k, for all 0 <= k <= j
// (choosing i vars forces the choice of the (i+1)st).
tab[i][j] = 0;
for( int k=0; k <= j; ++k ) {
tab[i][j] += tab[i-1][k];
}
}
}
return tab[n-1][sum];
}
```
```
$ time java Combos
2656615626
real 0m0.151s
user 0m0.120s
sys 0m0.012s
``` |
59,766 | <p>I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?</p>
| [
{
"answer_id": 59770,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 7,
"selected": true,
"text": "<p>At the top of your external JavaScript file, add the following:</p>\n\n<pre><code>/// <reference path=\"jQuery.js\"/>\n</code></pre>\n\n<p>Make sure the path is correct, relative to the file's position in the folder structure, etc.</p>\n\n<p>Also, any references need to be at the top of the file, before <em>any</em> other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different...</p>\n\n<p>Once you have done that and <em>saved the file</em>, hit <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>J</kbd> to force Visual Studio to update Intellisense.</p>\n"
},
{
"answer_id": 199940,
"author": "Chris Pietschmann",
"author_id": 7831,
"author_profile": "https://Stackoverflow.com/users/7831",
"pm_score": 3,
"selected": false,
"text": "<p>You'll want to look at this link:</p>\n\n<p><a href=\"http://blogs.ipona.com/james/archive/2008/02/15/JQuery-IntelliSense-in-Visual-Studio-2008.aspx\" rel=\"nofollow noreferrer\">http://blogs.ipona.com/james/archive/2008/02/15/JQuery-IntelliSense-in-Visual-Studio-2008.aspx</a></p>\n\n<p>UPDATE: There is a new HotFix for Visual Studio 2008 and a new jQuery Intellisense Documentation file that brings full jQuery Intellisense to VS'08. Below are links to get these two:</p>\n\n<p><a href=\"http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx</a></p>\n\n<p><a href=\"http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx\" rel=\"nofollow noreferrer\">http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx</a></p>\n"
},
{
"answer_id": 271359,
"author": "JD Courtoy",
"author_id": 23468,
"author_profile": "https://Stackoverflow.com/users/23468",
"pm_score": 4,
"selected": false,
"text": "<p>There is an officially supported jQuery documentation JavaScript file for Visual Studio 2008. This file is only an interim fix until Microsoft releases a hotfix that will more adequately address the issue.</p>\n\n<p>Embedded in ASPX:</p>\n\n<pre><code><% if (false) { %>\n <script src=\"jquery-1.2.6-vsdoc.js\" type=\"text/javascript\"></script>\n<% } %>\n</code></pre>\n\n<p>Embedded in JavaScript:</p>\n\n<pre><code>/// <reference path=\"jquery-1.2.6-vsdoc.js\" />\n</code></pre>\n\n<p>Pick it up here: <a href=\"http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6-vsdoc.js\" rel=\"nofollow noreferrer\">jquery-1.2.6-vsdoc.js</a></p>\n\n<p><strong>References</strong>:</p>\n\n<ul>\n<li><a href=\"http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx\" rel=\"nofollow noreferrer\">Rich Intellisense for jQuery</a></li>\n<li><a href=\"http://www.hanselman.com/blog/ASPNETAndJQuery.aspx\" rel=\"nofollow noreferrer\">Scott Hanselman - ASP.NET and jQuery</a></li>\n</ul>\n"
},
{
"answer_id": 285970,
"author": "Alan Oursland",
"author_id": 37189,
"author_profile": "https://Stackoverflow.com/users/37189",
"pm_score": 2,
"selected": false,
"text": "<p>You shouldn't need to actually reference the \"-vsdoc\" version. If you put the jquery-1.2.6-vsdoc.js in the same directory as jquery-1.2.6.js then Visual Studio will know to covert a jquery-1.2.6.js reference to jquery-1.2.6-vsdoc.js.</p>\n\n<p>I think that will actually work for any file.</p>\n\n<p>Hmmm... that gives a good workaround for another question on this site...</p>\n\n<p>Edit: This feature only works with VS2008 Service Pack 1.</p>\n"
},
{
"answer_id": 334742,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For inline JavaScript, use:</p>\n\n<p>/// <reference path=\"~\\js\\jquery-vsdoc.js\"/></p>\n\n<p>Note the <strong><em>back</em></strong> slashes.</p>\n\n<p>This will not work:</p>\n\n<p>/// <reference path=\"~/js/jquery-vsdoc.js\"/></p>\n"
},
{
"answer_id": 589373,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you're not using a minimized jQuery file.</p>\n<p>Use <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>J</kbd> to make it work after adding JavaScript files to the project.</p>\n"
},
{
"answer_id": 940270,
"author": "nikmd23",
"author_id": 107289,
"author_profile": "https://Stackoverflow.com/users/107289",
"pm_score": 2,
"selected": false,
"text": "<p>If you are including the annotated jQuery file in your source solely for intellisense, I recommend leveraging preprocessor directives to remove it from your view when you compile. Ala:</p>\n\n<pre><code><% #if (false) %>\n <!-- This block is here for jquery intellisense only. It will be removed by the compiler! -->\n <script type=\"text/javascript\" src=\"Scripts/jquery-1.3.2-vsdoc.js\"></script>\n<% #endif %>\n</code></pre>\n\n<p>Then later in your code you can <em>really</em> reference jQuery. This is handy when using the <a href=\"http://code.google.com/apis/ajaxlibs/\" rel=\"nofollow noreferrer\">Google AJAX Libraries API</a>, because you get all the benefits Google provides you, plus intellisense.</p>\n\n<p>Here is a sample of using the Libraries API:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>\n<script type=\"text/javascript\">\n google.load(\"jquery\", \"1.3.2\", { uncompressed: false });\n</script>\n</code></pre>\n"
},
{
"answer_id": 2416994,
"author": "Raghav",
"author_id": 148657,
"author_profile": "https://Stackoverflow.com/users/148657",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://codeasp.net/articles/jquery-intellisense-in-visual-studio-2008/102/tips-tricks-of-visual-studio\" rel=\"nofollow noreferrer\">jQuery Intellisense in Visual Studio 2008</a></p>\n"
},
{
"answer_id": 3984041,
"author": "Steve Miller",
"author_id": 482497,
"author_profile": "https://Stackoverflow.com/users/482497",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to pick up the Intellisense file from the Microsoft CDN you can use:</p>\n\n<pre><code>/// <reference path=\"http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.1-vsdoc.js\" />\n</code></pre>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59766",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1284/"
]
| I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong? | At the top of your external JavaScript file, add the following:
```
/// <reference path="jQuery.js"/>
```
Make sure the path is correct, relative to the file's position in the folder structure, etc.
Also, any references need to be at the top of the file, before *any* other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different...
Once you have done that and *saved the file*, hit `Ctrl` + `Shift` + `J` to force Visual Studio to update Intellisense. |
59,790 | <p>I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp_xml_preparedocument that is used to get transfer XMLs to an object and throught code. </p>
<p>I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. </p>
| [
{
"answer_id": 59882,
"author": "HigherAbstraction",
"author_id": 5945,
"author_profile": "https://Stackoverflow.com/users/5945",
"pm_score": 0,
"selected": false,
"text": "<p>If your XML conforms to a particular XSD schema, you can look into using the \"xsd.exe\" command line tool to generate C# object classes that you can bind the XML to, and then form your insert statements using the properties of those objects: <a href=\"http://msdn.microsoft.com/en-us/library/x6c1kb0s(VS.71).aspx\" rel=\"nofollow noreferrer\">MSDN XSD Doc</a></p>\n"
},
{
"answer_id": 59917,
"author": "J Healy",
"author_id": 5946,
"author_profile": "https://Stackoverflow.com/users/5946",
"pm_score": 0,
"selected": false,
"text": "<p>Peruse this document and it will give you the options:</p>\n\n<p>MSDN: <a href=\"http://msdn.microsoft.com/en-us/library/ms345110(SQL.90).aspx\" rel=\"nofollow noreferrer\">XML Options in Microsoft SQL Server 2005</a></p>\n"
},
{
"answer_id": 60139,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 2,
"selected": false,
"text": "<p>In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking:</p>\n\n<p><strong>How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?</strong></p>\n\n<p>A fairly straight forward solution that you already mentioned is the <em>sp_xml_preparedocument</em>, combined with <em>openxml</em>. </p>\n\n<p>Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on <a href=\"http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx\" rel=\"nofollow noreferrer\">Using OPENXML</a>.</p>\n\n<pre><code>declare @XmlDocumentHandle int\ndeclare @XmlDocument nvarchar(1000)\nset @XmlDocument = N'<ROOT>\n<Customer>\n <FirstName>Will</FirstName>\n <LastName>Smith</LastName>\n</Customer>\n</ROOT>'\n\n-- Create temp table to insert data into\ncreate table #Customer \n( \n FirstName varchar(20),\n LastName varchar(20) \n)\n-- Create an internal representation of the XML document.\nexec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument\n\n-- Insert using openxml allows us to read the structure\ninsert into #Customer\nselect \n FirstName = XmlFirstName,\n LastName = XmlLastName\nfrom openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 )\nwith \n(\n XmlFirstName varchar(20) 'FirstName',\n XmlLastName varchar(20) 'LastName'\n)\nwhere ( XmlFirstName = 'Will' and XmlLastName = 'Smith' )\n\n-- Cleanup xml document\nexec sp_xml_removedocument @XmlDocumentHandle\n\n-- Show the data\nselect * \nfrom #Customer\n\n-- Drop tmp table\ndrop table #Customer\n</code></pre>\n\n<p>If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a <em>string</em> should give you a fairly straight forward way of importing xml into your existing table(s).</p>\n"
},
{
"answer_id": 87072,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You may want to use XSLT to transfer your XML into SQL statements... ie</p>\n\n<pre><code><xml type=\"user\">\n <data>1</data>\n <data>2</data>\n<xml>\n</code></pre>\n\n<p>Then the XSLT would look like</p>\n\n<pre><code><xsl:template match=\"xml\">\n INSERT INTO <xsl:value-of select=\"@type\" /> (data1, data2) VALUES (\n '<xsl:value-of select=\"data[1]\" />',\n '<xsl:value-of select=\"data[2]\" />');\n</xsl:template>\n</code></pre>\n\n<p>The match statement most likely won't be the root node, but hopefully you get the idea. You may also need to wrap the non xsl:value-of parts in xsl:text to prevent extra characters from being dumped into the query. And you'd have to make sure the output of the XSLT was text. That said you could get a list of SQL statements that you could run through the DB. or you could use XSLT to output a T-SQL statement that you could load as a stored procedure.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
]
| I have been hearing the podcast blog for a while, I hope I dont break this.
The question is this: I have to insert an xml to a database. This will be for already defined tables and fields. So what is the best way to accomplish this? So far I am leaning toward programatic. I have been seeing varios options, one is Data Transfer Objects (DTO), in the SQL Server there is the sp\_xml\_preparedocument that is used to get transfer XMLs to an object and throught code.
I am using CSharp and SQL Server 2005. The fields are not XML fields, they are the usual SQL datatypes. | In an attempt to try and help, we may need some clarification. Maybe by restating the problem you can let us know if this is what you're asking:
**How can one import existing xml into a SQL 2005 database, without relying on the built-in xml type?**
A fairly straight forward solution that you already mentioned is the *sp\_xml\_preparedocument*, combined with *openxml*.
Hopefully the following example illustrates the correct usage. For a more complete example checkout the MSDN docs on [Using OPENXML](http://msdn.microsoft.com/en-us/library/ms187897(SQL.90).aspx).
```
declare @XmlDocumentHandle int
declare @XmlDocument nvarchar(1000)
set @XmlDocument = N'<ROOT>
<Customer>
<FirstName>Will</FirstName>
<LastName>Smith</LastName>
</Customer>
</ROOT>'
-- Create temp table to insert data into
create table #Customer
(
FirstName varchar(20),
LastName varchar(20)
)
-- Create an internal representation of the XML document.
exec sp_xml_preparedocument @XmlDocumentHandle output, @XmlDocument
-- Insert using openxml allows us to read the structure
insert into #Customer
select
FirstName = XmlFirstName,
LastName = XmlLastName
from openxml ( @XmlDocumentHandle, '/ROOT/Customer',2 )
with
(
XmlFirstName varchar(20) 'FirstName',
XmlLastName varchar(20) 'LastName'
)
where ( XmlFirstName = 'Will' and XmlLastName = 'Smith' )
-- Cleanup xml document
exec sp_xml_removedocument @XmlDocumentHandle
-- Show the data
select *
from #Customer
-- Drop tmp table
drop table #Customer
```
If you have an xml file and are using C#, then defining a stored procedure that does something like the above and then passing the entire xml file contents to the stored procedure as a *string* should give you a fairly straight forward way of importing xml into your existing table(s). |
59,816 | <p>I'm having some problems integrating MS MapPoint 2009 into my WinForms .Net 2.0 application in C#. I've added the ActiveX MapPoint control onto a form and have no problems getting it to display a maps and locations; my concern is the time it takes to load a map once it is created. </p>
<p>The tests on my development machine have shown the average load time to be between 3 and 5 seconds, during which the application is totally locked. While this isn't totally unacceptable, it's an awfully long time to lose control of the application. Also, because the GUI thread is locked, I cannot show a loading dialog or something to mask the load time. </p>
<p>The line that hangs is this: (where axMappointControl1 is the MapPoint control)</p>
<pre><code>axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica);
</code></pre>
<p>I've tried executing the NewMap method on another thread but the GUI thread still ends up being blocked.</p>
<p>My questions are: </p>
<ul>
<li>What can I do to speed up MapPoint when it loads?</li>
<li>Is there any way to load MapPoint so that it won't block the GUI thread?</li>
</ul>
<p>Any help is greatly appreciated.</p>
| [
{
"answer_id": 96314,
"author": "Frosty",
"author_id": 7476,
"author_profile": "https://Stackoverflow.com/users/7476",
"pm_score": 3,
"selected": true,
"text": "<p>According to <a href=\"http://www.mapforums.com/load-new-map-separate-thread-keep-ui-responsive-4605.html\" rel=\"nofollow noreferrer\">these</a> <a href=\"http://www.mapforums.com/activex-performance-net-3415.html\" rel=\"nofollow noreferrer\">threads</a> at mapforums.com the slowness of ActiveX startup is well known and unavoidable (though the question of threading to help with GUI responsiveness is still open.</p>\n\n<p>One thing suggested was to abandon the ActiveX version in favor of the MapPoint.Application object instead.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 4594911,
"author": "winwaed",
"author_id": 481927,
"author_profile": "https://Stackoverflow.com/users/481927",
"pm_score": 1,
"selected": false,
"text": "<p>Yes the Application version runs on its own thread - so this should be a quicker alternative - easier to do your own stuff whilst it is starting up. However, MapPoint 2010 tends to take a few seconds to start up when started by a user.</p>\n\n<p>I would create a temporary GUI thread and use this to display a splash screen during start up and/or do any thread-safe initialisation that you need to do. </p>\n\n<p>All calls to a MapPoint instance (or ActiveX control) must be from the same thread that create the MapPoint control or application object.</p>\n"
}
]
| 2008/09/12 | [
"https://Stackoverflow.com/questions/59816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1314/"
]
| I'm having some problems integrating MS MapPoint 2009 into my WinForms .Net 2.0 application in C#. I've added the ActiveX MapPoint control onto a form and have no problems getting it to display a maps and locations; my concern is the time it takes to load a map once it is created.
The tests on my development machine have shown the average load time to be between 3 and 5 seconds, during which the application is totally locked. While this isn't totally unacceptable, it's an awfully long time to lose control of the application. Also, because the GUI thread is locked, I cannot show a loading dialog or something to mask the load time.
The line that hangs is this: (where axMappointControl1 is the MapPoint control)
```
axMappointControl1.NewMap(MapPoint.GeoMapRegion.geoMapNorthAmerica);
```
I've tried executing the NewMap method on another thread but the GUI thread still ends up being blocked.
My questions are:
* What can I do to speed up MapPoint when it loads?
* Is there any way to load MapPoint so that it won't block the GUI thread?
Any help is greatly appreciated. | According to [these](http://www.mapforums.com/load-new-map-separate-thread-keep-ui-responsive-4605.html) [threads](http://www.mapforums.com/activex-performance-net-3415.html) at mapforums.com the slowness of ActiveX startup is well known and unavoidable (though the question of threading to help with GUI responsiveness is still open.
One thing suggested was to abandon the ActiveX version in favor of the MapPoint.Application object instead.
Hope that helps. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.