Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a project I am working on. based off a backup SQl Server database from a production server. They have over 16,000 user email addresses, and I want to corrupt them so the system (which has automatic emailers) will not send any emails to valid addresses. But I still want the users, and I want them in a way that I can reverse what I do (which is why I dont want to delete them). The SQL I am trying is: > UPDATE Contact SET > EmailAddress = EmailAddress + '.x' But it isnt working, what am I doing wrong? Error Message is as follows: ``` --------------------------- Microsoft SQL Server Management Studio Express --------------------------- SQL Execution Error. Executed SQL statement: UPDATE Contact SET EmailAddress = EmailAddress + '.x' Error Source: .Net SqlClient Data Provider Error Message: String or binary data would be truncated. The statement has been terminated. --------------------------- OK Help --------------------------- ```
The issue is that `EmailAddress +".x"` results in some of your data being to long for the given field. You could do: ``` select * from Contact where len(EmailAddress +".x") > LENFIELD ``` Replace LENFIELD with the length of the column defined on the table. If you just want to mung the data why not just set all the fields to a single email address? Or modify the rows that are causing the error to occur to be shorter.
Can you be more specific about any errors that you get? I've just knocked up an example and it works fine. Edit - EmailAddress fields you're trying to update are already close to the full size for the field, to make sure the edit applies to all the required record, you need to change add 2 to the column size for that field BTW Sql to convert it back again ``` update Contact set EmailAddress = SUBSTRING(EmailAddress , 0 , len(EmailAddress ) - 1) where SUBSTRING(EmailAddress , len(EmailAddress ) - 1, 2) = '.x' ```
How to Append String at the end of a Given a Column in SQL Server?
[ "", "sql", "sql-server", "" ]
I'm learning C#. From what I know, you have to set things up correctly to have the garbage collector actually delete everything as it should be. I'm looking for wisdom learned over the years from you, the intelligent. I'm coming from a C++ background and am VERY used to code-smells and development patterns. I want to learn what code-smells are like in C#. Give me advice! What are the best ways to get things deleted? How can you figure out when you have "memory leaks"? --- Edit: I am trying to develop a punch-list of "stuff to always do for memory management" --- Thanks, so much.
C#, the .NET Framework uses Managed Memory and everything (but allocated unmanaged resources) is garbage collected. It is safe to assume that managed types are always garbage collected. That includes `arrays`, `classes` and `structures`. Feel free to do `int[] stuff = new int[32];` and forget about it. If you open a file, database connection, or any other unmanaged resource in a class, implement the IDisposable interface and in your Dispose method de-allocate the unmanaged resource. Any class which implements IDisposable should be explicitly closed, or used in a (I think cool) Using block like; ``` using (StreamReader reader = new StreamReader("myfile.txt")) { ... your code here } ``` Here .NET will dispose reader when out of the { } scope.
The first thing with GC is that it is non-deterministic; if you want a resource cleaned up promptly, implement `IDisposable` and use `using`; that doesn't collect the managed memory, but can help a lot with unmanaged resources and onward chains. In particular, things to watch out for: * lots of pinning (places a lot of restrictions on what the GC can do) * lots of finalizers (you don't usually need them; slows down GC) * static events - easy way to keep a lot of large object graphs alive ;-p * events on an inexpensive long-life object, that can see an expensive object that should have been cleaned up * "captured variables" accidentally keeping graphs alive For investigating memory leaks... "SOS" is one of the easiest routes; you can use SOS to find all instances of a type, and what can see it, etc.
What are ways to solve Memory Leaks in C#
[ "", "c#", ".net", "memory-leaks", "garbage-collection", "" ]
I have inherited a large source tree, C#, Visual Studio 2008. It has many quality issues, one of them is that the code is generally badly formatted. I am looking for a tool, preferably a plugin for Visual Studio, that will go over the whole solution and apply the same basic formatting that Visual Studio itself applies when, for example, you close a curly brace around a block of code. Any suggestions?
ok, so why not try a macro, if you want to do the entire solution, there is a vb example here <http://blogs.msdn.com/kevinpilchbisson/archive/2004/05/17/133371.aspx> it opens each file and applies the same formatting that VS does, but the macro will work across an entire solution (may not be that wise to run it if your solution is huge), beyond reflecting the internals of the format document code in VS and inling it into some sort of stream, this appears to be the easiest way to make use of what i consider to be a very useful feature in visual studio
In vs2005, you can do Edit->Advanced->Format Document for a single file, which will (I believe) do what you're asking. I assume vs2008 has a similar function somewhere.
Tool to automatically reformat whole C# source tree in VS2008?
[ "", "c#", "visual-studio", "visual-studio-2008", "formatting", "" ]
I'm trying to get all the DOM nodes that are within a range object, what's the best way to do this? ``` var selection = window.getSelection(); //what the user has selected var range = selection.getRangeAt(0); //the first range of the selection var startNode = range.startContainer; var endNode = range.endContainer; var allNodes = /*insert magic*/; ``` I've been been thinking of a way for the last few hours and came up with this: ``` var getNextNode = function(node, skipChildren){ //if there are child nodes and we didn't come from a child node if (node.firstChild && !skipChildren) { return node.firstChild; } if (!node.parentNode){ return null; } return node.nextSibling || getNextNode(node.parentNode, true); }; var getNodesInRange = function(range){ var startNode = range.startContainer.childNodes[range.startOffset] || range.startContainer;//it's a text node var endNode = range.endContainer.childNodes[range.endOffset] || range.endContainer; if (startNode == endNode && startNode.childNodes.length === 0) { return [startNode]; }; var nodes = []; do { nodes.push(startNode); } while ((startNode = getNextNode(startNode)) && (startNode != endNode)); return nodes; }; ``` However when the end node is the parent of the start node it returns everything on the page. I'm sure I'm overlooking something obvious? Or maybe going about it in totally the wrong way. [MDC/DOM/range](https://developer.mozilla.org/en/DOM/range)
The getNextNode will skip your desired endNode recursively if its a parent node. Perform the conditional break check inside of the getNextNode instead: ``` var getNextNode = function(node, skipChildren, endNode){ //if there are child nodes and we didn't come from a child node if (endNode == node) { return null; } if (node.firstChild && !skipChildren) { return node.firstChild; } if (!node.parentNode){ return null; } return node.nextSibling || getNextNode(node.parentNode, true, endNode); }; ``` and in while statement: ``` while (startNode = getNextNode(startNode, false , endNode)); ```
Here's an implementation I came up with to solve this: ``` function getNextNode(node) { if (node.firstChild) return node.firstChild; while (node) { if (node.nextSibling) return node.nextSibling; node = node.parentNode; } } function getNodesInRange(range) { var start = range.startContainer; var end = range.endContainer; var commonAncestor = range.commonAncestorContainer; var nodes = []; var node; // walk parent nodes from start to common ancestor for (node = start.parentNode; node; node = node.parentNode) { nodes.push(node); if (node == commonAncestor) break; } nodes.reverse(); // walk children and siblings from start until end is found for (node = start; node; node = getNextNode(node)) { nodes.push(node); if (node == end) break; } return nodes; } ```
How to get nodes lying inside a range with javascript?
[ "", "javascript", "dom", "range", "traversal", "" ]
I have 2 tables: ``` tblAuthors - id - username tblPosts - id - authorid ``` So if I create a new Post ``` var post = new Post { Id=Guid.NewId(), Author=new Author { UserName="username", Id="id in database } }; ``` The author of the post is already in the database, but the post itself is not... So I want to do: ``` entities.AddToPosts(obj); ``` but it tries to add the Author and the Post... is there a way to have it Save the author and add the post? Or just ignore the Author completely? I have both the Post and the Author as my own POCO business objects, that were pulled from the database and then converted to my business layer. I don't want to have to re-pull them because I could have modified either in my business layer. So I just want to attach the objects. I don't want to keep the data objects around, I pull them out and convert them to business objects and then don't touch them again until I want to push back to the database and I convert the business objects to data objects.
This functionality isn't completely supported in EF yet, I had to the following: ``` var post = new Post { Id=Guid.NewId(), AuthorReference.EntityKey = new EntityKey("Authors", "Id", authorIdValue) }; entities.AddToPost(post); ```
Shouldn't you first retrieve the Author record from the database to be able to set it in the Post object? So you would you get: ``` var author = Author.Select(a => a.Id).FirstOrDefault(); var post = new Post { Id=Guid.NewId(), Author=author }; entities.AddToPosts(obj); ``` Maybe you could use the [Attach](http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx) and [AttachTo](http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attachto.aspx) ObjectContext to attach the object, but is not mentioned in the MSDN library whether a query to the database is executed. With some tracing you could check whether a database query occurs.
How do I add an object with the entity framework when it has a foreign key object that already exists
[ "", "c#", "entity-framework", ".net-3.5", "" ]
I am interested in using functors (function objects) in Java. With quick googling I found these 3 packages: * Java Generics Algorithms: <http://jga.sourceforge.net/> * Commons functor: <http://commons.apache.org/sandbox/functor/> * Mango: <http://www.jezuk.co.uk/cgi-bin/view/mango> and of 3, JGA seemed like it might have the best design. But I suspect others here who have actually used one or more of the packages might be able to offer more insight as to pros and cons of these (and perhaps other) functor packages.
[The Google Collections Library](http://code.google.com/p/google-collections/) provides a `Function` interface that is similar (though probably not as in depth).
## Mango Provides interfaces for 0, 1, and 2 argument functions. Uses Java generics. Good range of algorithms for working with functions. ## JGA Provides classes for 0, 1, 2 and arbitrary number of argument functions. Domain objects subclass these. Uses Java generics. Extensive range of algorithms. Includes JFXG (Java Functor eXpression Grammar) - a parsed language intended to make it easy to create arbitrarily complex functors. Provides multiple algorithms for working with functions. ## Apache Commons Functor Provides interfaces for 0, 1, and 2 argument functions as well as 0, 1 and 2 argument procedures (which return no value). Uses Java generics. Good range of algorithms. ## Google Guava (was Google collections) Provides Function and Predicate interfaces for single argument functions. Uses Java generics. Provides only the compose method for combining functions. Pretty basic. ## FunctionalJ Provides interfaces and classes for 0, 1, 2 and arbitrary number of argument functions. Uses Java generics. Existing methods can be turned into functions via the provided function reflection classes.
Best Java Functor lib: JGA, commons functor, mango, or...?
[ "", "java", "functor", "" ]
For sometime now, I have been trying to wrap my head around the reason why some “cannibal” classes are allowed to compile. Before I continue, perhaps I should explain what I call a “cannibal” class. Not sure if I just invented that term or if it has been around for a while or even if I am using it correctly but that is not important right now. I basically call a cannibal class a class that consumes itself. In other words a class whose interface declares members of its own type. For example: ``` class Foo { public Foo SomeFoo; } ``` As you can see above, class Foo has a member of type Foo (itself). Now, the first time I saw this (looong time ago) I didn’t thing it was going to compile but it to my surprise it does compile. The reason why I didn’t thing this would compile is because to me this screams some type of recursive nightmare. To complicate things a little further, I decided to try the same thing but making the class a struct such as: ``` struct Foo { public Foo SomeFoo; } ``` Unfortunately, this does not compile, instead you get error: ***Struct member 'Foo.SomeFoo' of type 'Foo' causes a cycle in the struct layout*** To me, a compile error makes more sense that no error but I am sure there most be a logical explanation to this behavior so I was wondering if anyone of you guys could explain this behavior. Thanks.
The reason you can't design a struct like this is because structs have to be initialized when they are allocated with some default values. So, when you have a struct `Foo` like you described and you create a `Foo`... ``` Foo x; // x = default(Foo) ``` it calls the default constructor for `Foo`. However, that default constructor has to give a default value for the `Foo.SomeFoo` field. Well, how's it find that? It has to call `default(Foo)`. Which, in order to construct a `Foo`, has to give a default value for the `Foo.SomeFoo` field... As you surmised, this is a recursive nightmare. Since you can create a null reference to a class, and refrain from actually creating an instance of the class immediately, there's no problem; you can call `new Foo()` and `Foo.SomeFoo` will just be null. No recursion necessary. **ADDENDUM**: When you're thinking about this, if you're still confused, I think the other answers have another good way of considering it (same essential problem, different approach) -- when the program allocates memory for a `Foo`, how's it supposed to do it? What's `sizeof(Foo)` when `Foo` contains some stuff, and then another whole `Foo`? You can't do that. Instead, if it were a class, it would just have to allocate a couple bytes for a reference to a `Foo`, not an actual `Foo`, and there's no problem.
The difference lies in the fact that Foo is a reference type. The class memory layout will have a pointer to a Foo instance and this will be fine. In the case of the structure, you have basically an infintely recusrsive memory layout, that cannot work. Now, if your class tries to instantiate a Foo in its own constructor, then you will have a Stack overflow problem.
Cannibal Classes
[ "", "c#", ".net", "" ]
I have a WSDL file for a web service. I'm using JAX-WS/wsimport to generate a client interface to the web service. I don't know ahead of time the host that the web service will be running on, and I can almost guarantee it won't be <http://localhost:8080>. How to I specify the host URL at runtime, e.g. from a command-line argument? The generated constructor `MyService(URL wsdlLocation, QName serviceName)` doesn't seem like what I want, but maybe it is? Perhaps one of the variants of `Service.getPort(...)`? Thanks!
The constructor should work fine for your needs, when you create MyService, pass it the url of the WSDL you want i.e. <http://someurl:someport/service?wsdl>.
If you have a look in the generated source close to the generated constructor, you should be able to figure out what to put in it from the default constructor, should look something like: ``` public OrdersService() { super(WSDL_LOCATION, new QName("http://namespace.org/order/v1", "OrdersService")); } ``` You should be able to find the def of WSDL\_LOCATION in the static field further up in the class.
How do I specify host and port when accessing a web service from JAX-WS-generated code?
[ "", "java", "web-services", "jax-ws", "" ]
I've read about unit testing and heard a lot of hullabaloo by others touting its usefulness, and would like to see it in action. As such, I've selected this basic class from a simple application that I created. I have no idea how testing would help me, and am hoping one of you will be able to help me see the benefit of it by pointing out what parts of this code can be tested, and what those tests might look like. So, how would I write unit tests for the following code? ``` public class Hole : INotifyPropertyChanged { #region Field Definitions private double _AbsX; private double _AbsY; private double _CanvasX { get; set; } private double _CanvasY { get; set; } private bool _Visible; private double _HoleDia = 20; private HoleTypes _HoleType; private int _HoleNumber; private double _StrokeThickness = 1; private Brush _StrokeColor = new SolidColorBrush(Colors.Black); private HolePattern _ParentPattern; #endregion public enum HoleTypes { Drilled, Tapped, CounterBored, CounterSunk }; public Ellipse HoleEntity = new Ellipse(); public Ellipse HoleDecorator = new Ellipse(); public TextBlock HoleLabel = new TextBlock(); private static DoubleCollection HiddenLinePattern = new DoubleCollection(new double[] { 5, 5 }); public int HoleNumber { get { return _HoleNumber; } set { _HoleNumber = value; HoleLabel.Text = value.ToString(); NotifyPropertyChanged("HoleNumber"); } } public double HoleLabelX { get; set; } public double HoleLabelY { get; set; } public string AbsXDisplay { get; set; } public string AbsYDisplay { get; set; } public event PropertyChangedEventHandler PropertyChanged; //public event MouseEventHandler MouseActivity; // Constructor public Hole() { //_HoleDia = 20.0; _Visible = true; //this.ParentPattern = WhoIsTheParent; HoleEntity.Tag = this; HoleEntity.Width = _HoleDia; HoleEntity.Height = _HoleDia; HoleDecorator.Tag = this; HoleDecorator.Width = 0; HoleDecorator.Height = 0; //HoleLabel.Text = x.ToString(); HoleLabel.TextAlignment = TextAlignment.Center; HoleLabel.Foreground = new SolidColorBrush(Colors.White); HoleLabel.FontSize = 12; this.StrokeThickness = _StrokeThickness; this.StrokeColor = _StrokeColor; //HoleEntity.Stroke = Brushes.Black; //HoleDecorator.Stroke = HoleEntity.Stroke; //HoleDecorator.StrokeThickness = HoleEntity.StrokeThickness; //HiddenLinePattern=DoubleCollection(new double[]{5, 5}); } public void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #region Properties public HolePattern ParentPattern { get { return _ParentPattern; } set { _ParentPattern = value; } } public bool Visible { get { return _Visible; } set { _Visible = value; HoleEntity.Visibility = value ? Visibility.Visible : Visibility.Collapsed; HoleDecorator.Visibility = HoleEntity.Visibility; SetCoordDisplayValues(); NotifyPropertyChanged("Visible"); } } public double AbsX { get { return _AbsX; } set { _AbsX = value; SetCoordDisplayValues(); NotifyPropertyChanged("AbsX"); } } public double AbsY { get { return _AbsY; } set { _AbsY = value; SetCoordDisplayValues(); NotifyPropertyChanged("AbsY"); } } private void SetCoordDisplayValues() { AbsXDisplay = HoleEntity.Visibility == Visibility.Visible ? String.Format("{0:f4}", _AbsX) : ""; AbsYDisplay = HoleEntity.Visibility == Visibility.Visible ? String.Format("{0:f4}", _AbsY) : ""; NotifyPropertyChanged("AbsXDisplay"); NotifyPropertyChanged("AbsYDisplay"); } public double CanvasX { get { return _CanvasX; } set { if (value == _CanvasX) { return; } _CanvasX = value; UpdateEntities(); NotifyPropertyChanged("CanvasX"); } } public double CanvasY { get { return _CanvasY; } set { if (value == _CanvasY) { return; } _CanvasY = value; UpdateEntities(); NotifyPropertyChanged("CanvasY"); } } public HoleTypes HoleType { get { return _HoleType; } set { if (value != _HoleType) { _HoleType = value; UpdateHoleType(); NotifyPropertyChanged("HoleType"); } } } public double HoleDia { get { return _HoleDia; } set { if (value != _HoleDia) { _HoleDia = value; HoleEntity.Width = value; HoleEntity.Height = value; UpdateHoleType(); NotifyPropertyChanged("HoleDia"); } } } public double StrokeThickness { get { return _StrokeThickness; } //Setting this StrokeThickness will also set Decorator set { _StrokeThickness = value; this.HoleEntity.StrokeThickness = value; this.HoleDecorator.StrokeThickness = value; NotifyPropertyChanged("StrokeThickness"); } } public Brush StrokeColor { get { return _StrokeColor; } //Setting this StrokeThickness will also set Decorator set { _StrokeColor = value; this.HoleEntity.Stroke = value; this.HoleDecorator.Stroke = value; NotifyPropertyChanged("StrokeColor"); } } #endregion #region Methods private void UpdateEntities() { //-- Update Margins for graph positioning HoleEntity.Margin = new Thickness (CanvasX - HoleDia / 2, CanvasY - HoleDia / 2, 0, 0); HoleDecorator.Margin = new Thickness (CanvasX - HoleDecorator.Width / 2, CanvasY - HoleDecorator.Width / 2, 0, 0); HoleLabel.Margin = new Thickness ((CanvasX * 1.0) - HoleLabel.FontSize * .3, (CanvasY * 1.0) - HoleLabel.FontSize * .6, 0, 0); } private void UpdateHoleType() { switch (this.HoleType) { case HoleTypes.Drilled: //Drilled only HoleDecorator.Visibility = Visibility.Collapsed; break; case HoleTypes.Tapped: // Drilled & Tapped HoleDecorator.Visibility = (this.Visible == true) ? Visibility.Visible : Visibility.Collapsed; HoleDecorator.Width = HoleEntity.Width * 1.2; HoleDecorator.Height = HoleDecorator.Width; HoleDecorator.StrokeDashArray = LinePatterns.HiddenLinePattern(1); break; case HoleTypes.CounterBored: // Drilled & CounterBored HoleDecorator.Visibility = (this.Visible == true) ? Visibility.Visible : Visibility.Collapsed; HoleDecorator.Width = HoleEntity.Width * 1.5; HoleDecorator.Height = HoleDecorator.Width; HoleDecorator.StrokeDashArray = null; break; case HoleTypes.CounterSunk: // Drilled & CounterSunk HoleDecorator.Visibility = (this.Visible == true) ? Visibility.Visible : Visibility.Collapsed; HoleDecorator.Width = HoleEntity.Width * 1.8; HoleDecorator.Height = HoleDecorator.Width; HoleDecorator.StrokeDashArray = null; break; } UpdateEntities(); } #endregion } ```
Here's an example. Keep in mind your sample code lacked definitions for a number of dependencies: ``` [TestFixture()] public class TestHole { private Hole _unitUnderTest; [SetUp()] public void SetUp() { _unitUnderTest = new Hole(); } [TearDown()] public void TearDown() { _unitUnderTest = null; } [Test] public void TestConstructorHole() { Hole testHole = new Hole(); Assert.IsNotNull(testHole, "Constructor of type, Hole failed to create instance."); } [Test] public void TestNotifyPropertyChanged() { string info = null; _unitUnderTest.NotifyPropertyChanged(info); } } ``` You can see that it is testing that the constructor is producing a valid object (usually not necessary with a full test fixture in place, construction is usually well exercised) and it is also testing the only public method in the class. In this case you would need an event handler delegate and an Assert to check the info parameter's contents. The goal is to write tests that exercise each method of your class. Usually this includes upper and lower bounds as well as failure conditions.
Unit Test Example: * Verify that PropertyChanged Event is fired with the correct event args. Use reflection in the test to iterate all of the properties setting the values and checking for the event. Usually this is done with a testing framework such as [NUnit](http://www.nunit.com/index.php). (Kind of funny cause you will notice that the ParentPattern property doesn't fire the event.)
Practice Examples Testing C# code
[ "", "c#", "unit-testing", "" ]
I have been playing with this a while, and just cannot see an obvious solution. I want to remove the recursion from the XinY\_Go function. ``` def XinY_Go(x,y,index,slots): if (y - index) == 1: slots[index] = x print slots slots[index] = 0 return for i in range(x+1): slots[index] = x-i XinY_Go(x-(x-i), y, index + 1, slots) def XinY(x,y): return XinY_Go(x,y,0,[0] * y) ``` The function is calculating the number of ways to put X marbles in Y slots. Here is some sample output: ``` >>> xy.XinY(1,2) [1, 0] [0, 1] >>> xy.XinY(2,3) [2, 0, 0] [1, 1, 0] [1, 0, 1] [0, 2, 0] [0, 1, 1] [0, 0, 2] ```
A naive implementation of [@Joel Coehoorn's suggestion](https://stackoverflow.com/questions/616416/is-it-possible-to-remove-recursion-from-this-function/616432#616432) follows: ``` def XinY_Stack(x, y): stack = [(x, 0, [0]*y)] while stack: x, index, slots = stack.pop() if (y - index) == 1: slots[index] = x print slots slots[index] = 0 else: for i in range(x + 1): slots[index] = x-i stack.append((i, index + 1, slots[:])) ``` Example: ``` >>> XinY_Stack(2, 3) [0, 0, 2] [0, 1, 1] [0, 2, 0] [1, 0, 1] [1, 1, 0] [2, 0, 0] ``` ### Based on [`itertools.product`](http://docs.python.org/library/itertools.html#itertools.product) ``` def XinY_Product(nmarbles, nslots): return (slots for slots in product(xrange(nmarbles + 1), repeat=nslots) if sum(slots) == nmarbles) ``` ### Based on nested loops ``` def XinY_Iter(nmarbles, nslots): assert 0 < nslots < 22 # 22 -> too many statically nested blocks if nslots == 1: return iter([nmarbles]) # generate code for iter solution TAB = " " loopvars = [] stmt = ["def f(n):\n"] for i in range(nslots - 1): var = "m%d" % i stmt += [TAB * (i + 1), "for %s in xrange(n - (%s)):\n" % (var, '+'.join(loopvars) or 0)] loopvars.append(var) stmt += [TAB * (i + 2), "yield ", ','.join(loopvars), ', n - 1 - (', '+'.join(loopvars), ')\n'] print ''.join(stmt) # exec the code within empty namespace ns = {} exec(''.join(stmt), ns, ns) return ns['f'](nmarbles + 1) ``` Example: ``` >>> list(XinY_Product(2, 3)) [(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)] >>> list(XinY_Iter(2, 3)) def f(n): for m0 in xrange(n - (0)): for m1 in xrange(n - (m0)): yield m0,m1, n - 1 - (m0+m1) [(0, 0, 2), (0, 1, 1), (0, 2, 0), (1, 0, 1), (1, 1, 0), (2, 0, 0)] ```
Everything we think of as recursion can also be thought of as a stack-based problem, where the recursive function just uses the program's call stack rather than creating a separate stack. That means any recursive function can be re-written using a stack instead. I don't know python well enough to give you an implementation, but that should point you in the right direction. But in a nutshell, push the initial arguments for the function onto the stack and add a loop that runs as long as the size of the stack is greater than zero. Pop once per loop iteration, push every time the function currently calls itself.
Is it possible to remove recursion from this function?
[ "", "python", "recursion", "" ]
I'm trying to do the simplest thing, to show an alert popup through javascript from my code-behind of a user control (ascx.cs). I've tried ``` protected void btnSave_Click(object sender, EventArgs e) { ScriptManager.RegisterStartupScript(btnSave, GetType(), "uniqueID", "alert('hello');", true); } ``` as well as ``` Page.ClientScript.RegisterStartupScript(GetType(), "uniqueID", "alert('hello');", true); ``` but nothing seems to work for me. The control is located within an RadAjaxPanel (telerik) in an ASPX page. I'm missing something obvious here. Any ideas what? **EDIT:** The javascript is not injected into the html source as far as I can see. I look for the ID and the actual alert statement in the html.
Ah, the problem was the Telerik RadAjaxPanel. I just had to set the EnableOutsideScripts to true on them, like so: ``` <telerik:RadAjaxPanel ID="ajaxpanel" runat="server" LoadingPanelID="ajaxLoadingPanel" EnableOutsideScripts="true"> ``` And then I could use the following code: ``` ScriptManager.RegisterStartupScript(btnSave, GetType(), "uniqueID", "alert('hello');", true); ```
Pass page's type to *client script type* parameter : ``` Page.ClientScript.RegisterClientScriptBlock(typeof(MyPage), "myPostBackScript", script, true); ``` **EDIT :** Normally this code works, but I don't know how telerik's control effects the injected script. I think you should open HTML source of the page and try to find injected script. This will help us to solve your problem.
Can't get no javascript to execute on an ASP.NET user control
[ "", "c#", "asp.net", "telerik", "scriptmanager", "clientscript", "" ]
As (hopefully) we all know, `vector<bool>` is totally broken and can't be treated as a C array. What is the best way to get this functionality? So far, the ideas I have thought of are: * Use a `vector<char>` instead, or * Use a wrapper class and have `vector<bool_wrapper>` How do you guys handle this problem? I need the `c_array()` functionality. As a side question, if I don't need the `c_array()` method, what is the best way to approach this problem if I need random access? Should I use a deque or something else? Edit: * I do need dynamic sizing. * For those who don't know, `vector<bool>` is specialized so that each `bool` takes 1 bit. Thus you can't convert it to a C-style array. * I guess "wrapper" is a bit of a misnomer. I was thinking something like this: Of course, then I have to read into a `my_bool` due to possible alignment issues :( ``` struct my_bool { bool the_bool; }; vector<my_bool> haha_i_tricked_you; ```
Use [`std::deque`](http://en.cppreference.com/w/cpp/container/deque) if you don't need the array, yes. Otherwise use an alternative `vector` that doesn't specialize on `bool`, such as the one in [Boost Container](http://www.boost.org/doc/libs/1_48_0/doc/html/container/Cpp11_conformance.html#container.Cpp11_conformance.Vector_bool).
That's an interesting problem. If you need what would have been a std::vector if it was not specialized, then maybe something like that would work fine with your case : ``` #include <vector> #include <iostream> #include <algorithm> class Bool { public: Bool(): m_value(){} Bool( bool value ) : m_value(value){} operator bool() const { return m_value; } // the following operators are to allow bool* b = &v[0]; (v is a vector here). bool* operator& () { return &m_value; } const bool* operator& () const { return &m_value; } private: bool m_value; }; int main() { std::vector<Bool> working_solution(10, false); working_solution[5] = true; working_solution[7] = true; for( int i = 0; i < working_solution.size(); ++i ) { std::cout<< "Id " << i << " = " << working_solution[i] << "(" <<(working_solution[i] ? "true" : "false") << ")" <<std::endl; // i used ? : to be sure the boolean evaluation is correct } std::sort( working_solution.begin(), working_solution.end()); std::cout<< "--- SORTED! ---" << std::endl; for( int i = 0; i < working_solution.size(); ++i ) { bool* b = &working_solution[i]; // this works! std::cout<< "Id " << i << " = " << working_solution[i] << "(" << (working_solution[i] ? "true" : "false") << ")" <<std::endl; // i used ? : to be sure the boolean evaluation is correct } std::cin.get(); return 0; } ``` I tried this with VC9 and it seems to work fine. The idea of the Bool class is to simulate the bool type by providing the same behavior and size (but not the same type). Almost all the work is done by the bool operator and the default copy constructors here. I added a sort to be sure it react as assumed when using algorithms. Not sure it would suit all cases. If it's right for your needs, it would be less work than rewriting a vector-like class...
Alternative to vector<bool>
[ "", "c++", "stl", "vector", "boolean", "" ]
Genesys is a contact center platform that provides software for working with both hard and soft PBXs. There are also a number of ancillary services they provide to support the wider contact center business. I'm aware of the .NET and Java SDKs that Genesys supply on a first hand basis. Is there SDK support for any other languages and, specifically, is there an official Python library for interacting with their services? Alternatively, are there any 3rd party libraries that are designed to interact with Genesys services for Python?
If they are providing a C library, you can use ctypes to interact with it.
Just for completeness, one could use ironpython (<http://ironpython.net/>) with the .net libraries from genesys. FWIW, I use the java libs with jython. I was kind of expecting the scripts to be interchangeable (ie. between jython and ironpython) but unfortunately, the API differs in parts. ie. the parameters to some of the functions are different or in a different order.
What languages provide SDKs for interacting with Genesys services?
[ "", "python", "pbx", "genesys", "pabx", "" ]
How do I crop an image using C#?
You can use [`Graphics.DrawImage`][1] to draw a cropped image onto the graphics object from a bitmap. ``` Rectangle cropRect = new Rectangle(...); using (Bitmap src = Image.FromFile("") as Bitmap) { using (Bitmap target = new Bitmap(cropRect.Width, cropRect.Height)) { using (Graphics g = Graphics.FromImage(target)) { g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), cropRect, GraphicsUnit.Pixel); } } } ```
Check out this link: [http://www.switchonthecode.com/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing](http://web.archive.org/web/20130126075626/http://www.switchonthecode.com:80/tutorials/csharp-tutorial-image-editing-saving-cropping-and-resizing) ``` private static Image cropImage(Image img, Rectangle cropArea) { Bitmap bmpImage = new Bitmap(img); return bmpImage.Clone(cropArea, bmpImage.PixelFormat); } ```
How do I crop an image using C#?
[ "", "c#", "image-processing", "" ]
Concerning headers in a library, I see two options, and I'm not sure if the choice really matters. Say I created a library, lets call it `foobar`. Please help me choose the most appropriate option: 1. Have one include in the very root of the library project, lets call it `foobar.h`, which includes all of the headers in the library, such as "src/some\_namespace/SomeClass.h" and so on. Then from outside the library, in the file that I want to use anything to do with the `foobar` library, just `#include <foobar.h>`. 2. Don't have a main include, and instead include only the headers we need in the places that I am to use them, so I may have a whole bunch of includes in a source file. Since I'm using namespaces sometimes as deep as 3, including the headers seems like a bit of a chore. I've opted for option 1 because of how easy it is to implement. OpenGL and many other libraries seem to do this, so it seemed sensible. However, the standard C++ library can require me to include several headers in any given file, why didn't they just have one header file? Unless it's me being and idiot, and they're separate libraries... ### Update: Further to answers, I think it makes sense to provide both options, correct? I'd be pretty annoyed if I wanted to use a std::string but had to include a mass of header files; that would be silly. On the other hand, I'd be irritated if I had to type a mass of `#include` lines when I wanted to use most of a library anyway. ### Forward headers: Thanks to all that advised me of forward headers, this has helped me make the header jungle less complicated! :)
stl, boost and others who have a lot of header files to include they provide you with independent tools and you can use them independently. So if you library is a set of uncoupling tools you have to give a choice to include them as separate parts as well as to include the whole library as the one file.
Think a bit about how your libary will be used, and organize it that way. If someone is unlikely to use one small part without using the whole thing, structure it as one big include. If a small part is independent and useful on its own, make sure you can include just enough for that part. If there's some logical grouping that makes sense, create include files for each group. As with most programming questions, there's no one-size-fits-all answer.
What is the best header structure to use in a library?
[ "", "c++", "header", "" ]
Im looking to improve the search in one of my applications, where I sue regular fulltext searching, which isn't too bad, but Im looking to add some more complex behaviors, such as typo recognition and better relevancy. Are there any solutions out there that can be integrated into an existing application? Im looking to search several tables in a single mysql DB, nothing complicated. It has to work with non-apache servers (I use lighttpd).
Give a look to [`Zend_Search_Lucene`](http://framework.zend.com/manual/en/zend.search.lucene.html) it's a PHP5 port of the [Apache Lucene](http://lucene.apache.org/java/docs/) project, the [query language](http://framework.zend.com/manual/en/zend.search.lucene.query-language.html) is very powerful.
I would say it depends on your current application. Zend Lucene could be a good alternative, but creating the index takes a very long time if there is a lot of data (and could kill your server). [Java Lucene](http://lucene.apache.org) is probably the best one but requires you to run tomcat. [Sphinx](http://www.sphinxsearch.com) is also a good alternative but is a separate server with a PHP api (even a PECL extension) but has some drawback has it recreate the index every time you had something to it (at least the last time I checked it) I think it probably worth an experimentation with a few solution first.
Whats a fast alternative to plain fulltext searching in php?
[ "", "php", "mysql", "search", "" ]
I'm having trouble getting a LINQ compound select to compile. Here is the code: ``` int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; int[] numbersB = { 1, 3, 5, 7, 8 }; var pairs = from a in numbersA, b in numbersB where a < b select new {a, b}; ``` The code is from a tutorial from here, under the heading 'SelectMany - Compound from 1': <http://msdn.microsoft.com/en-us/vcsharp/aa336758.aspx#SelectSimple1> And the compile-time error i get is as follows: A query body must end with a select clause or a group clause The comma just after 'numbersA' is where the error occurs. Now i can't figure out what i've done wrong, since this is just code as per the MS website. Any help would be great thanks.
Your code is not a valid LINQ expression. `from` clause supports a single collection only. You should repeat the whole `from` clause. You probably meant to say: ``` var pairs = from a in numbersA from b in numbersB where a < b select new {a, b}; ```
The equivalent fluent syntax using [SelectMany](http://www.hookedonlinq.com/SelectManyOperator.ashx), just for the record: ``` var pair = numbersA.SelectMany(a => numbersB, (a, b) => new {a, b}) .Where(n => n.a < n.b); ```
LINQ compound select problem
[ "", "c#", "linq", "" ]
So, I'm getting more and more engulfed with test driven development these days and the more code I write while thinking tdd, the more decisions it's seems as though I have to make about the extent of testing that I should write. I would like to set kind of a personal policy as to how much unit testing I should write for my own projects, and was wondering if I get some advice as to how what kind of you approach you all take. Here an example of a decision that I'm currently facing... I have three classes... ``` public class User { public string Username { get; set; } public List<Favorite> Favorties { get; set; } } public class Favorite { public string Username { get; set; } public int rank { get; set; } } public class UserManager { public List<Favorite> GetTop5(User user) { var qry = from fav in user.Favorties.OrderBy(f => f.rank) select fav; return qry.Take<Favorite>(5).ToList(); } } ``` I have a data access layer for the User class for which I already have a "GetUser" test setup. As you can see, in my business logic I have a method UserManager.GetTop5() that returns the top 5 favorites for the User that I just pulled out of the db. This method is very simple and currently involves NO external resources or dependencies. So my question is would you go ahead and write another test for this "GetTop5" function point, even though there's very little chance for failure? Do you setup a test anyway in case you extend upon the functionality in the future? Or do you think that a test here is excessive?
You won't believe this, but here's what Kent Beck had to say, right here on StackOverflow: "I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don't typically make a kind of mistake (like setting the wrong variables in a constructor), I don't test for it. " Link: [Link:](https://stackoverflow.com/questions/153234/how-deep-are-your-unit-tests/153565#153565)
when doing TDD, I write at least one unit test for each *feature*. so, is GetTop5 a feature? if so, it deserves a test. If it's not a feature, then it doesn't need to exist ;-)
Test writing strategy advice
[ "", "c#", "unit-testing", "tdd", "test-first", "" ]
I have an `class A` which uses a heap memory allocation for one of its fields. Class A is instantiated and stored as a pointer field in another class (`class B`. When I'm done with an object of class B, I call `delete`, which I assume calls the destructor... But does this call the destructor of class A as well? ### Edit: From the answers, I take that (please edit if incorrect): 1. `delete` of an instance of B calls B::~B(); 2. which calls `A::~A();` 3. `A::~A` *should* explicitly `delete` all heap-allocated member variables of the A object; 4. Finally the memory block storing said instance of class B is returned to the heap - when *new* was used, it first allocated a block of memory on heap, then invoked constructors to initialize it, now after all destructors have been invoked to finalize the object the block where the object resided is returned to the heap.
The destructor of A will run when its lifetime is over. If you want its memory to be freed and the destructor run, you have to delete it if it was allocated on the heap. If it was allocated on the stack this happens automatically (i.e. when it goes out of scope; see RAII). If it is a member of a class (not a pointer, but a full member), then this will happen when the containing object is destroyed. ``` class A { char *someHeapMemory; public: A() : someHeapMemory(new char[1000]) {} ~A() { delete[] someHeapMemory; } }; class B { A* APtr; public: B() : APtr(new A()) {} ~B() { delete APtr; } }; class C { A Amember; public: C() : Amember() {} ~C() {} // A is freed / destructed automatically. }; int main() { B* BPtr = new B(); delete BPtr; // Calls ~B() which calls ~A() C *CPtr = new C(); delete CPtr; B b; C c; } // b and c are freed/destructed automatically ``` In the above example, every delete and delete[] is needed. And no delete is needed (or indeed able to be used) where I did not use it. `auto_ptr`, `unique_ptr` and `shared_ptr` etc... are great for making this lifetime management much easier: ``` class A { shared_array<char> someHeapMemory; public: A() : someHeapMemory(new char[1000]) {} ~A() { } // someHeapMemory is delete[]d automatically }; class B { shared_ptr<A> APtr; public: B() : APtr(new A()) {} ~B() { } // APtr is deleted automatically }; int main() { shared_ptr<B> BPtr = new B(); } // BPtr is deleted automatically ```
When you call delete on a pointer allocated by new, the destructor of the object pointed to will be called. ``` A * p = new A; delete p; // A:~A() called for you on obkect pointed to by p ```
Does delete on a pointer to a subclass call the base class destructor?
[ "", "c++", "memory-management", "destructor", "delete-operator", "base-class", "" ]
I'm playing around with [Twisted](http://twistedmatrix.com) and documentation found on their homepage doesn't answer all my questions. The topic I am most interested at the moment is Twisted Application Framework. Also some open source servers using twisted framework would provide nice material for studying how it's all tied up together in a bigger project. So far I've checked out iCal and read documentation on twisted website (3x) and few good articles I found in google.
The published book is pretty useless, in my opinion. I recommend starting with the "deferred" docs online, and making absolutely sure you understand what asynchronous means and what deferreds are for. The best online docs that I've found are on the official site, though they could surely use some polishing: <http://twistedmatrix.com/trac/wiki/Documentation> The developers recommend reading the source as well, though if you have specific questions, I've found that the devs hang out and respond on both the IRC channel (**#twisted** on the freenode network) and the online mailing lists (There's [a general](http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python) and a [twisted-web specific](http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-web) list) As for blogs, there's at least the two below (both blogs are by twisted developers). I bet if you asked this same question on the twisted-python mailing list, you'd get a much better and more comprehensive answer than I could possibly give. :-) <http://oubiwann.blogspot.com/> <http://glyph.twistedmatrix.com/>
I think you need to get your concepts right to start with. I found this blog post to be helpful. [Introduction to Asynchronous Programming and Twisted](http://krondo.com/blog/?p=1209)
Where can I find good python Twisted framework documentation, blog entries, articles, etc?
[ "", "python", "twisted", "" ]
I want to measure the speed of a function within a loop. But why my way of doing it always print "0" instead of high-res timing with 9 digits decimal precision (i.e. in nano/micro seconds)? What's the correct way to do it? ``` #include <iomanip> #include <iostream> #include <time.h> int main() { for (int i = 0; i <100; i++) { std::clock_t startTime = std::clock(); // a very fast function in the middle cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl; } return 0; } ``` ### Related Questions: * [How to overcome `clock()`'s low resolution](https://stackoverflow.com/questions/588307/) * [High Resolution Timer with C++ and linux](https://stackoverflow.com/questions/538609/) * [Equivalent of Windows’ `QueryPerformanceCounter` on OSX](https://stackoverflow.com/questions/464618)
Move your time calculation functions outside `for () { .. }` statement then devide total execution time by the number of operations in your testing loop. ``` #include <iostream> #include <ctime> #define NUMBER 10000 // the number of operations // get the difference between start and end time and devide by // the number of operations double diffclock(clock_t clock1, clock_t clock2) { double diffticks = clock1 - clock2; double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER); return diffms; } int main() { // start a timer here clock_t begin = clock(); // execute your functions several times (at least 10'000) for (int i = 0; i < NUMBER; i++) { // a very fast function in the middle func() } // stop timer here clock_t end = clock(); // display results here cout << "Execution time: " << diffclock(end, begin) << " ms." << endl; return 0; } ``` Note: std::clock() lacks sufficient precision for profiling. [Reference](http://www.cplusplus.com/reference/clibrary/ctime/clock.html).
A few pointers: 1. I would be careful with the optimizer, it might throw all your code if I will think that it doesn't do anything. 2. You might want to run the loop 100000 times. 3. Before doing the total time calc store the current time in a variable. 4. Run your program several times.
High Resolution Timing Part of Your Code
[ "", "c++", "time", "high-resolution-clock", "" ]
What's the easiest way to parse a string and extract a number and a letter? I have string that can be in the following format (number|letter or letter|number), i.e "10A", "B5", "C10", "1G", etc. I need to extract the 2 parts, i.e. "10A" -> "10" and "A". **Update:** Thanks to everyone for all the excellent answers
Easiest way is probably to use regular expressions. ``` ((?<number>\d+)(?<letter>[a-zA-Z])|(?<letter>[a-zA-Z])(?<number>\d+)) ``` You can then match it with your string and extract the value from the groups. ``` Match match = regex.Match("10A"); string letter = match.Groups["letter"].Value; int number = int.Parse(match.Groups["number"].Value); ```
The easiest and fastest is to use simple string operations. Use the `IsDigit` method to check where the letter is, and parse the rest of the string to a number: ``` char letter = str[0]; int index = 1; if (Char.IsDigit(letter)) { letter = str[str.Length - 1]; index = 0; } int number = int.Parse(str.Substring(index, str.Length - 1)); ```
String parsing, extracting numbers and letters
[ "", "c#", "regex", "string", "text-parsing", "" ]
How to use a string containing a class name to reference a class itself? See this (not working) exemple... ``` class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print self.__class__.__name__.the_var class SomeSubClass(WrapperClass): var = "abc" class AnotherSubClass(WrapperClass): var = "def" ``` And an obvious error message: ``` >>> b = SomeSubClass() >>> b.display_var() Traceback (most recent call last): File "", line 1, in File "", line 4, in display_var AttributeError: 'str' object has no attribute 'the_var' >>> ``` Thanks!
> How to use a string containing a class name to reference a class itself? Classes aren't special, they're just values contained in variables. If you've said: ``` class X(object): pass ``` in global scope, then the variable ‘X’ will be a reference to the class object. You can get the current script/module's global variables as a dictionary using ‘globals()’, so: ``` classobj= globals()[self.__class__.__name__] print classobj.var ``` (`locals()` is also available for local variables; between them you shouldn't ever need to use the awful `eval()` to access variables.) However as David notes, `self.__class__` is *already* the `classobj`, so there's no need to go running about fetching it from the global variables by name; `self.__class__.var` is fine. Although really: ``` print self.var ``` would be the usual simple way to do it. Class members are available as members of their instances, as long as the instance doesn't overwrite the name with something else.
Depending on where you get this string, any general method may be insecure (one such method is to simply use `eval(string)`. The best method is to define a dict mapping names to classes: ``` class WrapperClass: def display_var(self): #FIXME: self.__class_name__.__name__ is a string print d[self.__class__.__name__].the_var class SomeSubClass(WrapperClass): the_var = "abc" class AnotherSubClass(WrapperClass): the_var = "def" d = {'WrapperClass': WrapperClass, 'SomeSubClass': SomeSubClass, 'AnotherSubClass': AnotherSubClass} AnotherSubClass().display_var() # prints 'def' ```
Python: Reference to a class from a string?
[ "", "python", "" ]
In ASP.net MVC: How should/Can I pass Form data (From the View) to the Controller? This is the way I am heading : * The Controller Index function is passing a ViewModel object to the View. * The ViewModel object contains a paginated list as well as some SelectLists. \_ The ViewModel object also contains a custom class I named theFilter. This class' purpose is to hold the Filter information Posted from the View via a Form. * I want the Index [AcceptVerbs(HttpVerbs.Post)] function to receive theFilter object populated with the form data, as well as the page number (as is it right now) Here are snippets of my code: The Controller/Index postback function: ``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(int? page, CaseFilter caseFilter) { const int pageSize = 10; var cases = caseRepo.FindAllCases(); var paginatedCases = new PaginatedList<Case>(cases, page ?? 0, pageSize); return View(new CaseIndexViewModel(paginatedCases, caseFilter)); } ``` The Filter Class: ``` public class CaseFilter { int iVolume_id = 0, iSubject_id = 0; public CaseFilter() { } public int Volume_id { get { return iVolume_id; } set { iVolume_id = value; } } public int Subject_id { get { return iSubject_id; } set { iSubject_id = value; } } } ``` And the ViewModel class: ``` public class CaseIndexViewModel { public PaginatedList<Case> PaginatedCases { get; private set; } public CaseFilter CaseFilter { get; private set; } public CaseIndexViewModel(PaginatedList<Case> paginatedCases, CaseFilter caseFilter) { PaginatedCases = paginatedCases; CaseFilter = caseFilter; } } ``` Basically I am trying to avoid using Request.Form to populate the Filter class, at least not to use it within the Controller. Any help, suggestions or disses are welcome!
Finally, I do not need to even use the Request Collection. The CaseFilter object is filled automatically as I set it as a parameter in ``` public ActionResult Index(int? page, CaseFilter caseFilter) ``` The code above works as it is.
``` [AcceptVerbs(HttpVerbs.Post)] public ActionResult Index(FormCollection collection) { string valueFromNameTextBox = collection["name"]; } ``` You can index into this collection with the names of all the inputs on the form.
How to pass Form Values to the Controller in .NET MVC
[ "", "c#", "asp.net-mvc", "request", "" ]
I am trying to use Adobe IFilter to search PDF files. My code is written in C# and I am using p/invoke to get an instance of IFilter: ``` [DllImport("query.dll", SetLastError = true, CharSet = CharSet.Unicode)] private extern static int LoadIFilter( string pwcsPath, [MarshalAs(UnmanagedType.IUnknown)] object pUnkOuter, ref IFilter ppIUnk); ``` This works for most PDF files except a few for which this method returns -2147467259 and ppIUnk is coming as null. Does anyone have this type of errors or have any suggestions of how to figure this out?
See the [MSDN docs](http://msdn.microsoft.com/en-us/library/ms691002.aspx) for the `LoadIFilter` function - you *should* be getting one of the error codes, at least according to that page. * E\_ACCESSDENIED = `0x80070005` - The function was denied access to the filter file. * E\_HANDLE = `0x80070006` - The function encountered an invalid handle, probably due to a low-memory situation. * E\_INVALIDARG = `0x80070057` - The function received an invalid parameter. * E\_OUTOFMEMORY = `0x8007000E` - The function did not have sufficient memory or other resources to complete the operation. * E\_FAIL = `0x80000008` - The function encountered an unknown error. (Also, the full set of constant values is listed [here](http://pinvoke.net/default.aspx/Enums/IFilterReturnCodes.html), which seems to be rather longer than that listed on MSDN.) Now, the interesting things is, your error code corresponds to `80004005` in hex, which isn't listed on either or those pages. I'm suspecting pinvoke.net may have it wrong however, as many other sites ([this](http://support.microsoft.com/kb/921292) for example) list it as `E_FAIL`... not that it really helps anyway. Sorry for the inconclusive answer, but maybe it will point you along the right track at least. **Edit:** This error seems to have been documented elsewhere and caused much confusion to many people, with no simple solution. It seems like the cause could be one of several in fact... There's various suggestions [here](http://persistall.com/archive/2005/09/14/20.aspx) and [here](http://www.codeproject.com/KB/cs/IFilter.aspx?display=PrintAll&fid=278909&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2735942) that you may want to try, but I don't think I can help you any more than that, as I have never encountered this error myself in this context. Good luck anyway...
Here's how I solved it: Uninstall Adobe Reader/Acrobat. Install the latest version (again). It should fix the pdf filters. Good luck.
LoadIFilter() returns -2147467259 for some PDF files
[ "", "c#", "pdf", "adobe", "ifilter", "" ]
I'm looking for practical and educational samples of C++ / STL code fitting in few lines. My actual favorites are: 1. Empty a vector freeing its reserved memory: ``` vector <...>().swap (v) ``` (swap with a temporary) 2. Copy a map to a vector: ``` map<T1, T2> myMap; vector< pair<T1, T2> > myVec(myMap.begin(), myMap.end()); // or myVec.assign(myMap.begin(), myMap.end()); ``` 3. Custom, non-boost split: ``` vector<string> &mysplit(const string &s, char delim, vector<string> &elems) { stringstream ss(s); string item; while(getline(ss, item, delim)) { elems.push_back(item); } return elems; } ```
``` // std::back_inserter usage ( std::inserter for map ) std::copy( source.begin(), source.end(), std::back_inserter( container ) ); ``` - ``` // mem_fun and bind usage (but boost better) std::some_algorithm(..., std::mem_fun( func ) ); ``` not so useful, but powerful: check is container sorted ``` std::adjacent_find( container.begin(), container.end(), greater<Container::value_type>() ) == container.end() ``` also examples mentioned by you and dirkgently.
My favorite is copying containers to the output: And copying the input stream into a container. ``` #include <vector> #include <algorithm> #include <iterator> #include <iostream> int main() { std::vector<int> data; std::copy(std::istream_iterator<int>(std::cin), std::istream_iterator<int>(), std::back_inserter(data) ); std::copy(data.begin(),data.end(), std::ostream_iterator<int>(std::cout,"\n") ); } ```
Most useful or amazing STL short liners
[ "", "c++", "stl", "" ]
I'm working on a WinForms SmartClient application, which uses a lot of RichTextBox controls - some in place of the regular TextBox for various reasons. Unfortunately the RichTextBox draws the ugly Win95 3D border instead of the themed XP or Vista style border. Does anyone know of a way to apply the themed border to the RichTextBox? I don't mind subclassing them for this purpose. Thanks!
This is really a hack but one thing you can do is drop a Panel control onto the page. Give it a BorderStyle of FixedSingle (it will be None by default.) Drop your RichTextBox into the panel and set the BorderStyle to none. Then set the Dock property of the RichTextBox to Fill. This will give you a RichTextBox with a flat border.
Back in the day I had to solve this with a panel where the text box is a component inside and had DockPadding set to 3 or 4 pixels. I'd then style that panel to a single pixel. I always found this really annoying!
How do I give the RichTextBox a flat look?
[ "", "c#", "winforms", "richtextbox", "themes", "uxtheme", "" ]
I want to give users access to WebDav using Apache, but I want to autenticate them first and give each user access to a specific folder. All authentication must be done against a Django-based database. I can get the Django-authentication working myself, but I need help with the part where I authenticate each user and provide them with a dedicated webdav user-specific area. Any hints?
You might find that the apache [mod\_authn\_dbd](http://httpd.apache.org/docs/2.2/mod/mod_authn_dbd.html) module gives you what you want. This module lets apache check an SQL database for authentication and authorization. You would use this directive in the `<Location>`, `<Directory>` (etc) area that you are trying to protect: ``` <Directory /usr/www/myhost/private> # other config ere # mod_authn_dbd SQL query to authenticate a user AuthDBDUserPWQuery \ "SELECT password FROM authn WHERE user = %s" </Directory> ``` Strictly speaking, this means you're authenticating against Django's database, not against the Django app itself. Note that you have full control over the query, so you CAN combine it with other parameters in any tables to make sure the user is in good standing, or in certain groups, or whatever, before allowing the authentication. You may need to fuss around a bit to make sure the hashing mechanisms used are the same in both apache and django. If this doesn't suit, consider moving your authentication out of the django database into, say, an LDAP server. With a custom authentication backend (there are existing LDAP implementations for django out there), django will happily use LDAP... and LDAP auth/auth support in Apache is quite robust.
First, for you other readers, my authentication was done against Django using a [WSGI authentication script](http://www.davidfischer.name/2009/10/django-authentication-and-mod_wsgi/). Then, there's the meat of the question, giving each Django user, in this case, their own WebDav dir separated from other users. Assuming the following WebDAV setup in the Apache virtual sites configuration (customarily in */etc/apache2/sites-enabled/*) ``` <Directory /webdav/root/on/server> DAV On # No .htaccess allowed AllowOverride None Options Indexes AuthType Basic AuthName "Login to your webdav area" Require valid-user AuthBasicProvider wsgi WSGIAuthUserScript /where/is/the/authentication-script.wsgi </Directory> ``` Note how there's no public address for WebDav set up yet. This, and the user area thing, is fixed in two lines in the same config file (put these after the ending clause): ``` RewriteEngine On RewriteRule ^/webdav-url/(.*?)$ /webdav/root/on/server/%{LA-U:REMOTE_USER}/$1 ``` Now, webdav is accessed on <http://my-server.com/webdav-url/> The user gets a login prompt and will then land in a subdirectory to the webdav root, having the same name as their username. *LA-U:* makes Apache "look ahead" and let the user sign in *before* determining the mounting path, which is crucial since that path depends on the user name. Without some rewrite-rule there will be no URL, and the user won't get a login prompt. In other words, LA-U avoids a catch-22 for this type of login handling. **Precautions**: requires mod\_rewrite to be enabled, and user names must be valid as dir names without any modification. Also, the user dirs won't be created automatically by these commands, so their existence must be assured in some other way.
Control access to WebDav/Apache using Python
[ "", "python", "django", "apache", "webdav", "" ]
On OS X, I am trying to .exec something, but when a path contains a space, it doesn't work. I've tried surrounding the path with quotes, escaping the space, and even using \u0020. For example, this works: ``` Runtime.getRuntime().exec("open /foldername/toast.sh"); ``` But if there's a space, none of these work: ``` Runtime.getRuntime().exec("open /folder name/toast.sh"); Runtime.getRuntime().exec("open \"/folder name/toast.sh\""); Runtime.getRuntime().exec("open /folder\\ name/toast.sh"); Runtime.getRuntime().exec("open /folder\u0020name/toast.sh"); ``` Ideas? Edit: Escaped backslash... still no worky.
There's a summary of this problem on [Sun's forums](http://forums.sun.com/thread.jspa?threadID=5366547&tstart=1)... seems to be a pretty common issue not restricted to OS X. The last post in the thread summarizes the proposed solution. In essence, use the form of `Runtime.exec` that takes a `String[]` array: ``` String[] args = new String[] { "open", "\"/folder name/toast.sh\"" }; ``` or (the forum suggests this will work too) ``` String[] args = new String[] { "open", "folder name/toast.sh" }; ```
Try this: ``` Runtime.getRuntime().exec("open /folder\\ name/toast.sh"); ``` "\ " will just put a space in the string, but "\ " will put a "\ " in the string, which will be passed to the shell, and the shell will escape the space. If that doesn't work, pass in the arguments as an array, one element for each argument. That way the shell doesn't get involved and you don't need bizarre escapes. ``` Runtime.getRuntime().exec(new String[]{"open", "/folder name/toast.sh"}); ```
Spaces in java execute path for OS X
[ "", "java", "runtime", "escaping", "space", "" ]
INFO: I am working with Microsoft SQL. Ok the title is confusing but here is an example of the table I'm working with: ``` ID Value Signal Read Firmware Date Time 5 123 656 444 217 3/30/2009 11:00:00 AM 5 123 421 333 217 3/30/2009 04:00:00 PM 5 123 111 666 217 3/30/2009 05:00:00 PM 9 321 231 551 216 3/30/2009 09:00:00 AM 9 321 599 887 216 3/30/2009 09:30:00 AM ``` So I want the Query to return: ``` ID Value Signal Read Firmware Date Time 5 123 111 666 217 3/30/2009 05:00:00 PM 9 321 599 887 216 3/30/2009 09:30:00 AM ``` I have tried: ``` SELECT DISTINCT ID, Value, Signal, Read, Firmware, Date, Time FROM .... ``` But this returns all of the results. I have also tried SELECT TOP 1... but I couldn't get that to work. I know this is simple, but I'm confused on how to get this to display only 1 single unique row. Thanks for the help.
Have you tried this? ``` SELECT id, value, MIN(Signal), MIN(Read), MIN(Firmware), MIN(Date), MIN(Time) FROM ... GROUP BY ID, Value ```
The records **are** distinct, there are different `Signal`, `Read` and `Time` values. How would you expect the SQL server to guess which one you'd like? Your example suggests that you're interested in the most recent record of a given `Id`. If that's true, this query should work for you: ``` SELECT table.* FROM table JOIN (SELECT Id, Date, MIN(Time) FROM Table GROUP BY Id, Date) AS selector ON (table.Id = selector.Id AND table.Date = selector.Date and table.Time = selector.Time) ```
Query to return 1 instance of a record with duplicates
[ "", "sql", "database", "" ]
So I've got a class like this: ``` public class A { internal A(int i) { ... } public int Foo { get; set; } } ``` This class is then inherited by a bunch of generated classes, eg: ``` public class B : A { ... } ``` The `int` based constructor isn't exposed to the inherited class (for design reasons I don't want it exposed). In my library which holds the definition for class `A` I've got a method like this: ``` public T Load<T>() where T : A { //do some stuff, create an instance of T from an int, then return it } ``` And then I'd use it like this: ``` B b = Helper.Load<B>(); ``` Since the constructor I want to use isn't exposed to class `B` when I do `typeof(T).GetConstructor(typeof(int))` I don't get the constructor back, so I want thinking that I'd do this: ``` return (T)new A(/*some int */); ``` But that gives me a runtime error `System.InvalidCastException`, that I can't cast a type A to type B. How do I go about achieving this upcasting?
You can just use default constructors so you can instantiate objects of type T with the new() constraint. Then class A can have a virtual (or abstract to your liking) method that takes an int as an argument and initializes the object after the constructor has run. ``` public class A { internal A() { } internal Initialize(int i) { Foo = i; } public int Foo { get; set; } } public class B : A { internal B() { } } ... public T Load<T>() where T : A, new() { var ret = new T(); ret.Initialize(i); return ret; } ``` If you intend some sort of factory pattern, you don't need to hesitate initializing parts of an object outside the constructor call as long as it is done before you return the object to the caller's control.
From what I understood, T derives from A, so you can't cast A to T.
Upcasting in .NET using generics
[ "", "c#", ".net", "" ]
I'm writing a small program (a twitter client) in Java, aimed at Mac OS X. As part of its functionality, it needs to have a place to store the twitter username/password. The natural place would be the mac keychain, but I can't find any way of accessing it. Is there any way of accessing the mac keychain from Java, or failing that, what is your recommendation for where to store the username/password instead?
There is Java keychain API, in that there's an implementation of [KeyStore](http://java.sun.com/j2se/1.5.0/docs/api/java/security/KeyStore.html) on OS X [backed by the keychain](http://developer.apple.com/DOCUMENTATION/Java/Conceptual/Java14Development/04-JavaUIToolkits/JavaUIToolkits.html#//apple_ref/doc/uid/TP40001901-210260). I think the keychain is the best place (if not *the* place) to store the password. It's encrypted with a good algorithm, the user is free to be as permissive or as paranoid over the availability of the keychain to apps as they like, and the password would then be stored with and configured like all of the other passwords the user stores.
I haven't tried this, but it looks like you can access the key chain with the Apple crypto provider (`com.apple.crypto.provider.Apple`), creating a `KeyStore` of type `KeychainStore`. --- Okay, after some experimentation, I was able to access private-key–certificate entries in the `KeychainStore`. However, passwords in my Keychain did not show up (no alias was listed), and when I tried to add a `KeyStore.SecretKeyEntry` (which is what you'd need to hold a password) it failed with the message, "Key is not a PrivateKey". Clearly, Apple has not supported `SecretKeyEntry`. If you still want to protect your Twitter password through the key chain, I think the closest you can get is to generate an RSA key pair, self-sign a certificate, and add a `PrivateKeyEntry` to the keychain. Then you can use the key pair to protect the Twitter password. It isn't terribly difficult to sign certificates yourself, but if you go that route, you might want to check out the BouncyCastle library for help.
Storing username/password on Mac using Java
[ "", "java", "security", "macos", "keychain", "" ]
Is it a bad idea to use the annotations from the > javax.persistence package instead of using the > org.hibernate.annotations annotations I know that using `javax.peristence` does introduce yet another dependency. But if I ignore that, what are the pros/cons?
Quite the opposite. Hibernate is an implementation of the Java Persistence API, and where possible, you should use the standard annotations (in javax.persistence). This way, you could theoretically run your code on other JPA implementations. Only when you need Hibernate-specific functionality should you use the Hibernate annotations. The extra dependency is only on the JPA interface/annotation jar files and very light.
Another cons in: <http://www.mkyong.com/hibernate/cascade-jpa-hibernate-annotation-common-mistake/> where this: ``` @OneToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST,CascadeType.MERGE }, mappedBy = "stock") public Set<StockDailyRecord> getStockDailyRecords() { return this.stockDailyRecords; } ``` with this: ``` stockDailyRecords.setStock(stock); stock.getStockDailyRecords().add(stockDailyRecords); session.save(stock); session.getTransaction().commit(); ``` won't work as `@OneToMany` is from JPA, it expects a JPA cascade – `javax.persistence.CascadeType`. However when you save it with Hibernate session, `org.hibernate.engine.Cascade` will do the following check: ``` if ( style.doCascade( action ) ) { ``` and Hibernate save process will causing a `ACTION_SAVE_UPDATE` action, but the JPA will pass a `ACTION_PERSIST` and `ACTION_MERGE`, it will not match and cause the cascade to fail to execute.
org.hibernate.annotations vs. javax.persistence
[ "", "java", "hibernate", "jpa", "" ]
How do i get rid of the body in my tabControl? and how do i add and remove tabpages? I need to add/remove tabpages in code but hide the body in code or in the editor. I tried making the tabControl hight <20 but no matter what it has a line showing how wide it is.
As far as I know, there's no built-in control for a row of tabs without pages for each tab. You could just cover the body with a Panel. If you adjust the size of the panel carefully, it should look ok.
What do you mean by "hide the body"? If you mean the "page" part of the tab, it's not really a tab page any more if you can only see the labels. What are you trying to accomplish? It may well be that a tab control isn't the best approach.
C# tab gui, Hide the body?
[ "", "c#", "user-interface", "tabcontrol", "" ]
I need to synchronize Windows Media Player with my application. I want to show the current song that WMP is playing in a ListBox in real time, with updates when WMP changes songs. How can I implement this?
A bit of sniffing around in Google gave me this: [http://brandon.fuller.name/archives/hacks/nowplaying/wmp/](http://brandon.fuller.name/archives/hacks/nowplaying/wmp/#overview), it looks like you need to write a plugin for WMP that exposes the information to your application. Depending on what you need/cost, the Plugin on that page might do the job!
Poll HKEY\_CURRENT\_USER\SOFTWARE\Microsoft\MediaPlayer\Player\RecentFileList\File perhaps.
How to interface with Windows Media Player in C#
[ "", "c#", ".net", "windows", "windows-media-player", "" ]
I can't use shared\_ptr in my project, no boost :( So, I'm having a class roughly similar to the one below: ``` class MyClass { private: std::auto_ptr<MyOtherClass> obj; }; ``` Now, I want to store the instances of above class in std::vector. Is it safe? I've [read here](https://stackoverflow.com/questions/111478/why-is-it-wrong-to-use-stdautoptr-with-stl-containers) that it's wrong to use std::auto\_ptr with STL containers. Does it apply to my situation here?
> I've posted a question as a follow-up > to this answer, see > [Class containing auto\_ptr stored in vector](https://stackoverflow.com/questions/704780/class-containing-autoptr-stored-in-vector). Assming your class does not have a user-defined copy constructor, then no, it is probably (see below) not safe. When your class is copied (as will happen when it is added to a vector) the copy constructor of the auto\_ptr will be used. This has the weird behaviour of tranferring ownership of the thing being copied to the copy and, so the thing being copied's pointer is now null. It is possible, though unlikely, that you actually want this behaviour, in which case an auto\_ptr is safe. Assuming you do not, you should either: * add a copy constructor to manage the copying **Note this is not enough - see the follow-up question mentioned above for more info.** or: * use a smarter, possibly reference counted pointer, such as one of the boost smart pointers
It is not safe, bacause when container will copy MyClass instnace default copy operator will call copy for all members - and for auto\_ptr member too and we will have same situation as you describe in your question ( storing auto\_ptr in container ) BTW: for avoid confusion at compile time add ``` private: MyClass& operator=( const MyClass& ); MyClass( const MyClass& ); ``` compiler output error if you will try use copy operators, this can save you from hours of debug.
Is it safe to store objects of a class which has an std::auto_ptr as its member variable in std::vector?
[ "", "c++", "memory-management", "stl", "" ]
My cube isn't rendering as expected when I use GL\_BLEND. ``` glEnable(GL_CULL_FACE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE); ``` I'm also having a similar problem with drawing some semi-opaque vertices in front, which could well be related. > Related: [Why do my semi-opaque vertices make background objects brighter in OpenGL?](https://stackoverflow.com/questions/722033/why-do-my-semi-opaque-vertices-make-background-objects-brighter-in-opengl) Here's what it's supposed to look like: [Normal cube http://img408.imageshack.us/img408/2853/normalcube.png](http://img408.imageshack.us/img408/2853/normalcube.png) And here's what it actually looks like: [Dark cube http://img7.imageshack.us/img7/7133/darkcube.png](http://img7.imageshack.us/img7/7133/darkcube.png) Please see the code used to [create the colored cube](http://pastebin.com/f5393f089), and the code used to actually [draw the cube](http://pastebin.com/f4aa216b6). The cube is being drawn like so: ``` glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix(); glLoadIdentity(); // ... do some translation, rotation, etc ... drawCube(); glPopMatrix(); // ... swap the buffers ... ```
You could try disabling all lighting before drawing the cube: ``` glDisable(GL_LIGHTING); ```
It looks like you have lighting enabled on the second one, try with a glShadeModel( GL\_FLAT ) before drawing,
Why does my colored cube not work with GL_BLEND?
[ "", "c++", "opengl", "blend", "" ]
I have a login form in every page of a website so the user can login from everywhere. I have a login.php file that I refer to it from the form (using 'action'). I use `$_SERVER['HTTP_REFERER']` to redirect the user to the same page he logged in from when he succesfully log in or when he logs out. But if there was a problem logging in, how can I send an error to the same page he is trying to log in?? I have tried sending the error using `$_GET`, like this: ``` // process the script only if the form has been submitted if (array_key_exists('login', $_POST)) { // Login code goes here... // If there was a problem, destroy the session and prepare error message else { $_SESSION = array(); session_destroy(); header('Location: '.$_SERVER['HTTP_REFERER'].'?error'); exit; } ``` But the problem is that a lot of pages in the website are like this `details.php?mid=0172495`. They already recive information from the `$_GET` method and for security reasons I cant use another `$_GET` method... So, How can I pass the error??? Thanks...
To add to what Chad Birch said... In your login script where you redirect, check the HTTP\_REFERER value for the character '?'. If it is present, append '&error' to the HTTP\_REFERER and redirect to that. Otherwise append '?error' to the HTTP\_REFERER and redirect to that.
Since you're already using sessions, after you destroy the session why not create a new one with $\_SESSION['error'] or something similar set? Or alternatively simply don't delete the session at all but set the error which you can immediately check in other pages?
PHP Login System problem... Sending errors from page to page
[ "", "php", "authentication", "" ]
In an extract I am dealing with, I have 2 `datetime` columns. One column stores the dates and another the times as shown. How can I query the table to combine these two fields into 1 column of type `datetime`? **Dates** ``` 2009-03-12 00:00:00.000 2009-03-26 00:00:00.000 2009-03-26 00:00:00.000 ``` **Times** ``` 1899-12-30 12:30:00.000 1899-12-30 10:00:00.000 1899-12-30 10:00:00.000 ```
You can simply add the two. * **if** the `Time part` of your `Date` column is always zero * **and** the `Date part` of your `Time` column is also always zero *(base date: January 1, 1900)* Adding them returns the correct result. ``` SELECT Combined = MyDate + MyTime FROM MyTable ``` ### Rationale (kudos to ErikE/dnolan) > It works like this due to the way the date is stored as two 4-byte > `Integers` with the left 4-bytes being the `date` and the right > 4-bytes being the `time`. Its like doing `$0001 0000 + $0000 0001 = > $0001 0001` ### Edit regarding new SQL Server 2008 types `Date` and `Time` are types introduced in `SQL Server 2008`. If you insist on adding, you can use `Combined = CAST(MyDate AS DATETIME) + CAST(MyTime AS DATETIME)` ### Edit2 regarding loss of precision in SQL Server 2008 and up (kudos to Martin Smith) Have a look at [How to combine date and time to datetime2 in SQL Server?](https://dba.stackexchange.com/questions/51440/how-to-combine-date-and-time-to-datetime2-in-sql-server) to prevent loss of precision using SQL Server 2008 and up.
If the time element of your date column *and* the date element of your time column are both zero then [Lieven's answer](https://stackoverflow.com/a/700649/370103) is what you need. If you can't guarantee that will always be the case then it becomes slightly more complicated: ``` SELECT DATEADD(day, 0, DATEDIFF(day, 0, your_date_column)) + DATEADD(day, 0 - DATEDIFF(day, 0, your_time_column), your_time_column) FROM your_table ```
How to combine date from one field with time from another field - MS SQL Server
[ "", "sql", "sql-server", "datetime", "" ]
I was wondering if anyone had a more elegant way to check for unique key exceptions from SQL in .NET other than parsing the error message? Right now I am calling the sproc in SQL, then using a try catch block in .NET. In the try catch block I parse the error message and it is a Unique key error I throw an instance of a custom error to the calling class, if not I just throw the original exception the the calling class. This seems awfully inefficient to me.
If you catch a SqlException, you should be able to enumerate the "Errors" collection holding a number of "SqlError" objects. The SqlError has among other things properties like "Class" and "Number" - unique key violations are class = 14 and number = 2601. Check for those numbers to find your error precisely. Those are the same error codes you get when you try to execute the query in SQL Management Studio: > Msg 2601, Level 14, State 1, Line 1 > Cannot insert duplicate key row in > object .......... > The statement has been terminated. The "Msg" translates to the "Number" property on SqlError, the "Level" to "Class". ``` try { _cmd.ExecuteNonQuery(); } catch(SqlException sqlExc) { foreach (SqlError error in sqlExc.Errors) { string msg = string.Format("{0}: {1}", error.Number, error.Message); } } ``` That way, you can easily and EXACTLY identify a "unique constraint violated" error. Marc
Why don't you just query if the unique id exists ? It's better then getting exception.
Catching SQL unique key exceptions in .NET
[ "", ".net", "asp.net", "sql", "" ]
Does anybody know if Python has an equivalent to Java's SortedSet interface? Heres what I'm looking for: lets say I have an object of type `foo`, and I know how to compare two objects of type `foo` to see whether `foo1` is "greater than" or "less than" `foo2`. I want a way of storing many objects of type `foo` in a list `L`, so that whenever I traverse the list `L`, I get the objects in order, according to the comparison method I define. ### Edit: I guess I can use a dictionary or a list and `sort()` it every time I modify it, but is this the best way?
Take a look at [BTrees](http://pypi.python.org/pypi?%3Aaction=search&term=btree). It look like you need one of them. As far as I understood you need structure that will support relatively cheap insertion of element into storage structure and cheap sorting operation (or even lack of it). BTrees offers that. I've experience with ZODB.BTrees, and they scale to thousands and millions of elements.
You can use `insort` from the [`bisect`](http://docs.python.org/library/bisect.html#module-bisect) module to insert new elements efficiently in an already sorted list: ``` from bisect import insort items = [1,5,7,9] insort(items, 3) insort(items, 10) print items # -> [1, 3, 5, 7, 9, 10] ``` Note that this does not directly correspond to `SortedSet`, because it uses a list. If you insert the same item more than once you will have duplicates in the list.
Python equivalent to java.util.SortedSet?
[ "", "python", "data-structures", "" ]
We have a WCF service that exposes a "Customer" type, i.e.: ``` [DataContract(Name = "CustomerData", Namespace = "http://www.testing.com")] public partial class Customer { [DataMember] public CustomerLevel Level { get; set; } } ``` You can see the above type has a property that is an enumeration type. The definition for this enum is: ``` [IgnoreCoverage] [DataContract(Namespace = "http://www.testing.com"")] public enum CustomerLevel : int { [EnumMember(Value = "Platinum")] Platinum = 1, [EnumMember(Value = "Gold")] Gold = 2, [EnumMember(Value = "Silver")] Silver = 3, [EnumMember(Value = "Bronze")] Bronze = 4, } ``` The service works fine as long as the server sends a valid enumeration for each customer that it returns. However, if the service returns a CustomerLevel that is not defined in the enumeration the service call times out. An example of a bad CustomerLevel value might be: ``` customer.Level = (CustomerLevel)0; ``` The service also times out if the client attempts to send a non-defined value. Is there any way to allow the non-defined value to flow through to both the client and server and let each of them handle the bad value on their own?
I don't think you're going to get bogus enums to work. What would they deserialize into? If you mean for the client to send integers, then change the type to int, and convert it into the enum on your own (with your own error handling). As to whether the client should time out, please tell us what sort of client you're using. Also, I recommend you look at the network traffic and see how the service responded, if at all. Also look in the Windows event logs to see if the service complained at all. Finally, you may want to turn on WCF tracing to see how the service is reacting to this.
You can do this using a custom IDataContractSurrogate to map the enum to an int then back to an enum. The documentation for creating such surrogates is here: <http://msdn.microsoft.com/en-us/library/ms733064.aspx> Here is a generic version I developed that can handle a list of Enum types. You specify this in the constructor for your DataContractSerializer. For more information, see my blog post here: <http://www.shulerent.com/2012/08/13/handling-invalid-enum-values-in-a-datacontractserializer/> ``` /// <summary> /// IDataContractSurrogate to map Enum to int for handling invalid values /// </summary> public class InvalidEnumContractSurrogate : IDataContractSurrogate { private HashSet<Type> typelist; /// <summary> /// Create new Data Contract Surrogate to handle the specified Enum type /// </summary> /// <param name="type">Enum Type</param> public InvalidEnumContractSurrogate(Type type) { typelist = new HashSet<Type>(); if (!type.IsEnum) throw new ArgumentException(type.Name + " is not an enum","type"); typelist.Add(type); } /// <summary> /// Create new Data Contract Surrogate to handle the specified Enum types /// </summary> /// <param name="types">IEnumerable of Enum Types</param> public InvalidEnumContractSurrogate(IEnumerable<Type> types) { typelist = new HashSet<Type>(); foreach (var type in types) { if (!type.IsEnum) throw new ArgumentException(type.Name + " is not an enum", "type"); typelist.Add(type); } } #region Interface Implementation public Type GetDataContractType(Type type) { //If the provided type is in the list, tell the serializer it is an int if (typelist.Contains(type)) return typeof(int); return type; } public object GetObjectToSerialize(object obj, Type targetType) { //If the type of the object being serialized is in the list, case it to an int if (typelist.Contains(obj.GetType())) return (int)obj; return obj; } public object GetDeserializedObject(object obj, Type targetType) { //If the target type is in the list, convert the value (we are assuming it to be int) to the enum if (typelist.Contains(targetType)) return Enum.ToObject(targetType, obj); return obj; } public void GetKnownCustomDataTypes(System.Collections.ObjectModel.Collection<Type> customDataTypes) { //not used return; } public object GetCustomDataToExport(Type clrType, Type dataContractType) { //Not used return null; } public object GetCustomDataToExport(System.Reflection.MemberInfo memberInfo, Type dataContractType) { //not used return null; } public Type GetReferencedTypeOnImport(string typeName, string typeNamespace, object customData) { //not used return null; } public System.CodeDom.CodeTypeDeclaration ProcessImportedType(System.CodeDom.CodeTypeDeclaration typeDeclaration, System.CodeDom.CodeCompileUnit compileUnit) { //not used return typeDeclaration; } #endregion } ```
Non-defined enumeration values in WCF service
[ "", "c#", "wcf", "" ]
I have a date such as April,1,2009. I want to know what the weekday is, i.e. whether April 1 is a Monday, Tuesday etc. Likewise I want to check weekday of each day in the month of April.
You can use the [DayOfWeek](http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx) property.
Use the [`DayOfWeek`](http://msdn.microsoft.com/en-us/library/system.datetime.dayofweek.aspx) property: ``` new DateTime(2009, 4, 1).DayOfWeek ```
To check weekday of a month
[ "", "c#", "date", "calendar", "" ]
What's the rationale behind the javax package? What goes into java and what into javax? I know a lot of enterprise-y packages are in javax, but so is Swing, the new date and time api (JSR-310) and other J2SE packages.
I think it's a historical thing - if a package is introduced as an addition to an existing JRE, it comes in as `javax`. If it's first introduced as *part* of a JRE (like NIO was, I believe) then it comes in as `java`. Not sure why the new date and time API will end up as `javax` following this logic though... unless it will also be available separately as a library to work with earlier versions (which would be useful). **Note from many years later: it (date and time API) actually ended up being in `java` after all.** I believe there are restrictions on the `java` package - I think classloaders are set up to *only* allow classes within `java.*` to be loaded from `rt.jar` or something similar. (There's certainly a check in `ClassLoader.preDefineClass`.) EDIT: While an official explanation (the search orbfish suggested didn't yield one in the first page or so) is no doubt about "core" vs "extension", I still suspect that in many cases the decision for any particular package has an historical reason behind it too. Is `java.beans` really that "core" to Java, for example?
Originally `javax` was intended to be for extensions, and sometimes things would be promoted out of `javax` into java. One issue was Netscape (and probably IE) limiting classes that could be in the java package. When Swing was set to "graduate" to `java` from `javax` there was sort of a mini-blow up because people realized that they would have to modify all of their imports. Given that backwards compatibility is one of the primary goals of Java they changed their mind. At that point in time, at least for the community (maybe not for Sun) the whole point of `javax` was lost. So now we have some things in javax that probably should be in `java`... but aside from the people that chose the package names I don't know if anyone can figure out what the rationale is on a case-by-case basis.
javax vs java package
[ "", "java", "package", "organization", "java-package", "" ]
when a user searches from google and lands on our site from the results he/she was shown in the results page, is there a way for my site to detect that he came from google?
Check the `$_SERVER['HTTP_REFERER']` variable which should contain the referring URL. Please note that this is not tamper-proof or fail-safe as the `Http-Referer` header can easily been changed or modified by a client. **EDIT:** Just googled for `phpinfo` (because chanes were high that I get a `phpinfo()` page that shows the `$_SERVER['HTTP_REFERER']` variable) to show you how the `Http-Referer` will look like: ``` $_SERVER['HTTP_REFERER'] = "http://www.google.de/search?hl=de&q=phpinfo&btnG=Google-Suche&meta=" ``` As you see, you can also extract the search term used in the google query (or detect if the search was initiated by the Google Chrome address bar)...
It looks like you can use the $\_SERVER['HTTP\_REFERER'] variable. But I think the value is controlled by the client and can't always be guaranteed to exist or accurate.
how do you detect if your website visitor came from a google search result?
[ "", "php", "html", "" ]
I'm creating a popup window with no URL source using window.open(). I don't give it a URL because soon I'll want to post a form to it. However, in the meantime I'd like to display a short "Now loading..." message so the user isn't looking at a blank page for the 2-3 seconds it'll take the form post to go through. I tried adding Javascript that just writes to the popup window's document. That worked great in Firefox and IE 8, but failed with an Access Denied message in IE 6 and 7. Anyone know of a way around this? I would love to be able to a) hard-code some HTML into window.open(), b) learn how to update the popup's DOM in this situation, or c) hear about anything anyone can think of. Below is the code I'm using to spawn the window: ``` var wref = window.open("", winName, "toolbar=1,resizable=1,menubar=1,location=1,status=1,scrollbars=1,width=800,height=600"); if (wref != null) { try {wref.opener = self;} catch (exc) {} // while we wait for the handoff form post to go through, display a simple wait message $j(wref.document.body).html('Now loading &#133;'); // EPIC FAIL wref.focus(); ```
``` <a href="#" onclick="return test();">Test</a> <script type="text/javascript"> function test() { window.open('javascript:opener.write(window);', '_name', 'width=200,height=200'); } function write(w) { w.document.write("Hello, World."); } </script> ``` Works in IE 6, 7 & 8, Opera 9.6, Firefox 2 & 3. Does not work in Safari for Windows 3 & 4 or Google Chrome. When it does work, it results in a pretty ugly URL in the Location box. If the browser support listed above is acceptable, you can use the solution provided, otherwise I'd do what David said and `window.open('Loading.htm' ...)` where `Loading.htm` contains whatever content you want to display (you should probably keep it lightweight otherwise it might take longer to load and render than the form will to POST).
IE considers "about:blank" to be a insecure URL and it won't let you talk to it. I would create a "Now Loading..." static HTML file and open that instead.
IE 6/7 Access Denied trying to access a popup window.document
[ "", "javascript", "internet-explorer", "dom", "" ]
I'm experiencing really weird behavior with the Socket.Connect method in C#. I am attempting a TCP Socket.Connect to a valid IP but closed port and the method is continuing as if I have successfully connected. When I packet sniffed what was going on I saw that the app was receiving RST packets from the remote machine. Yet from the tracing that is in place it is clear that the connect method is not throwing an exception. Any ideas what might be causing this? The code that is running is basically this ``` IPEndPoint iep = new IPEndPoint(System.Net.IPAddress.Parse(m_ipAddress), m_port); Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); tcpSocket.Connect(iep); ``` To add to the mystery... when running this code in a stand alone console application, the result is as expected – the connect method throws an exception. However, when running it in the Windows Service deployment we have the connect method does not throw an exception. **Edit in response to Mystere Man's answer** How would the exception be swallowed? I have a Trace.WriteLine right above the .Connect method and a Trace.WriteLine right under it (not shown in the code sample for readability). I know that both traces are running. I also have a try catch around the whole thing which also does a Trace.Writeline and I don't see that in the log files anywhere. I have also enabled the internal socket tracing as you suggested. I don't see any exceptions. I see what appears to be successful connections. I am trying to identify differences between the windows service app and the diagnostic console app I made. I am running out of ideas though **End edit** Thanks
I have never observed this again. It seems to me that something was corrupt somewhere. Either the OS on which the app was installed or the .NET framework.
Are you sure the exception isn't being caught and swallowed in the service, but not in the console app? My first step would be to isolate the differences between the two implementations. You mention tracing, but you don't say whether this is Network tracing (part of the BCL) or your own tracing. If you're not using network tracing, then enable that.
TCP Socket.Connect is generating false positives
[ "", "c#", ".net", "sockets", "tcp", "" ]
I'm using the BrowserLauncher2 library for opening the user's default web browser from my Swing app, but it's throwing a very confusing exception: ``` public static void openURL(String url) { try{ BrowserLauncher launcher = new BrowserLauncher(); launcher.openURLinBrowser(url); }catch(Exception e){ e.printStackTrace(); } } Exception: edu.stanford.ejalbert.exception.BrowserLaunchingExecutionException: java.lang.reflect.InvocationTargetException at edu.stanford.ejalbert.launching.macos.MacOs3_1BrowserLaunching.openUrl(MacOs3_1BrowserLaunching.java:61) at edu.stanford.ejalbert.BrowserLauncherRunner.run(BrowserLauncherRunner.java:136) at java.lang.Thread.run(Thread.java:613) Caused by: java.lang.reflect.InvocationTargetException at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:585) at edu.stanford.ejalbert.launching.macos.MacOs3_1BrowserLaunching.openUrl(MacOs3_1BrowserLaunching.java:58) ... 2 more Caused by: java.security.AccessControlException: access denied (java.lang.RuntimePermission canOpenURLs) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264) at java.security.AccessController.checkPermission(AccessController.java:427) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at com.apple.eio.FileManager.openURL(FileManager.java:229) at com.apple.mrj.MRJPriv.openURL(MRJPriv.java:255) at com.apple.mrj.MRJFileUtils.openURL(MRJFileUtils.java:206) ... 7 more ```
You are running your application with a `SecurityManager` set. Some code in the `AccessControlContext` (a.k.a. acc) does not have the required permission. Probably that code is your application code.
An `InvocationTargetException` always wraps another exception which was caused while invoking a method or constructor via reflection. To solve your problem, you need to look at the exception under it, the `IllegalAccessException` which as Tom Hawtin points out, is being thrown because of the `SecurityManager`.
Java BrowserLauncher throwing InvocationTargetException
[ "", "java", "exception", "" ]
How do I best gather messages that have not been read by a given user? Existing tables ``` Message table ---------------------------------- id title body sentAt User table ---------------------------------- id username Read Messages table ---------------------------------- user_id message_id ``` I'm thinking something like ``` select m.id, m.title, m.sentAt, u.username from message m, [user] u where u.id = 1 and -- @userId parameter m.id not in (select r.message_id from read_messages r where r.user_id = u.id) ``` Unfortunately for me I dont understand much looking at the execution plan. /Adam
*Suggesting an alternative approach:* I was faced with the exact same problem at work earlier. I wasted a good week in trying to figure the best way to do this. I ended up with creating a join table, as you have done, but the table contains only *unread* messages, instead of keeping track of *read* messages. # Because 1. The status quo is "everyone has read all their messages". 2. Getting the unread messages (or their count) should be as fast as possible. 3. The status quo should be the least straining status on the system. Now, if I would've kept track of all the messages everyone has read, the clutter in the database grows pretty rapidly (*users*\**messages* rows), easily leading to thousands of rows of 'dead weight' in even smaller applications. This problem is exaggerated if the lifetime of messages are indefinite - you could be keeping track of message statuses that are many years old. If keeping track of the inverse, your "unread messages" table contains only a handful of rows, and they diminish for each message that a user reads. Also, getting the amount of unread messages is as simple as "`SELECT COUNT(*) FROM unread WHERE user = foo`". # But As everything, this is a trade-off. While reading is pretty much as fast as computationally possible, writing is a chore. For each written message, you need to insert an entry to this join table. Additionally, if multiple people can read the same message, you need to insert one row for each recipient. If the recipients are implicit (e.g. only a user group's name is given, or even with the criteria such as "anyone who has access to this thing"), creating new messages becomes even more complicated. But I feel this is a fair compromise. YMMV, HTH.
NOT IN is very expensive. Instead, you could do something like: ``` SELECT m.id, m.title, m.sentAt FROM message m LEFT JOIN [Read Messages] rm ON m.message_id = rm.message_id AND rm.user_id = @userID WHERE rm.user_id IS NULL ``` Provided you have the right indexes, this should be much faster. You're fetching all messages and LEFT JOINing read messages for that user. Then, in the WHERE clause you're asking for that user\_id to be NULL for that message, meaning the user has not read it yet.
SQL query - how to fetch non-read messages efficiently
[ "", "sql", "" ]
My problem here is that I would like to pass an object to a derived class, but it must be done before the base class constructor, since the base class will immediately call the derived class's `Start()` method that uses the object. Here's an excerpt from the base class, (renamed from [BarcodeScanner](http://msdn.microsoft.com/en-us/library/aa446489.aspx#barcode_scanners_netcf_topic6) for convenience). ``` public abstract class MyBase { public MyBase() { if (Initialize()) this.Start(); } public abstract bool Initialize(); public abstract void Start(); } ``` Here's the derived class that I'm creating. ``` class MyDerived : MyBase { private string sampleObject; public MyDerived (string initObject) { sampleObject = initObject; } public override bool Initialize() { return GetDevice(); } public override void Start() { Console.WriteLine("Processing " + sampleObject.ToString()); } } ``` I doubt you can make C# execute a derived constructor before the base constructor; so I'm really just looking for a solution to pass an object to the derived class before the object is used. I've gotten around this by putting the Initialize/Start if block inside the `MyDerived` constructor. However, there are other classes deriving from the base class; so I ended up having to repeat this block of Initialize/Start code in every derived class. I'd like to see an alternative to modifying the base class.
What you are trying to do is impossible in C#. A constructor in a base class must be run before the constructor of any derived class otherwise there would be potential for corrupt object state. A child object must be able to assume that its base is fully constructed and available.
IMHO your design is wrong. You shouldn't start the process from within the constructor. Your consuming code should explicitly call the Start() method when required.
Execute a derived constructor before the base constructor in C#
[ "", "c#", "constructor", "abstract-class", "derived-class", "" ]
Is there an Oracle SQL tool that builds insert statements from a result set? We are currently only allowed to use a tool called SQL Station. I'd like to either suggest a tool, like Rapid SQL or CrazySQuirrell, or build my own re-usable chunk of sql.
I found this solution, which is what I'm using now. Thanks for all of the help. It turns out we can use SQL+ too. For some reason I can't run it in SQL Station. COPY FROM userid/password@from\_DB TO userid/password>@to\_DB INSERT toDB\_tablename USING SELECT \* FROM fromDB\_tablename where ....; commit;
Where is this result set coming from? If you mean that you want to execute a SELECT, then insert the resulting data into another table, you can do that in a single SQL statement: ``` INSERT INTO table2 (columnA, columnB) SELECT columnA, columnB FROM table1; ```
Is there an Oracle SQL tool that builds insert statements from a result set?
[ "", "sql", "oracle", "insert", "resultset", "" ]
I wrote the following method. ``` public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable<T>(); return table.ToList().SingleOrDefault(e => Convert.ToInt16(e.GetType().GetProperties().First().GetValue(e, null)) == id); } ``` Basically it's a method in a Generic class where `T` is a class in a DataContext. The method gets the table from the type of T (`GetTable`) and checks for the first property (always being the ID) to the inputted parameter. The problem with this is I had to convert the table of elements to a list first to execute a `GetType` on the property, but this is not very convenient because all the elements of the table have to be enumerated and converted to a `List`. How can I refactor this method to avoid a `ToList` on the whole table? **[Update]** The reason I can't execute the `Where` directly on the table is because I receive this exception: > Method 'System.Reflection.PropertyInfo[] GetProperties()' has no supported translation to SQL. Because `GetProperties` can't be translated to SQL. **[Update]** Some people have suggested using an interface for *T*, but the problem is that the `T` parameter will be a class that is auto generated in *[DataContextName].designer.cs*, and thus I cannot make it implement an interface (and it's not feasible implementing the interfaces for all these "database classes" of LINQ; and also, the file will be regenerated once I add new tables to the DataContext, thus loosing all the written data). So, there has to be a better way to do this... **[Update]** I have now implemented my code like [Neil Williams](https://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method/735209#735209)' suggestion, but I'm still having problems. Here are excerpts of the code: *Interface:* ``` public interface IHasID { int ID { get; set; } } ``` *DataContext [View Code]:* ``` namespace MusicRepo_DataContext { partial class Artist : IHasID { public int ID { get { return ArtistID; } set { throw new System.NotImplementedException(); } } } } ``` *Generic Method:* ``` public class DBAccess<T> where T : class, IHasID,new() { public T GetByID(int id) { var dbcontext = DB; var table = dbcontext.GetTable<T>(); return table.SingleOrDefault(e => e.ID.Equals(id)); } } ``` The exception is being thrown on this line: `return table.SingleOrDefault(e => e.ID.Equals(id));` and the exception is: > `System.NotSupportedException: The > member > 'MusicRepo_DataContext.IHasID.ID' has > no supported translation to SQL.` **[Update] Solution:** With the help of [Denis Troller](https://stackoverflow.com/questions/735140/c-linq-to-sql-refectoring-this-generic-getbyid-method/735888#735888)'s posted answer and the link to the post at the [Code Rant blog](http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html), I finally managed to find a solution: ``` public static PropertyInfo GetPrimaryKey(this Type entityType) { foreach (PropertyInfo property in entityType.GetProperties()) { ColumnAttribute[] attributes = (ColumnAttribute[])property.GetCustomAttributes(typeof(ColumnAttribute), true); if (attributes.Length == 1) { ColumnAttribute columnAttribute = attributes[0]; if (columnAttribute.IsPrimaryKey) { if (property.PropertyType != typeof(int)) { throw new ApplicationException(string.Format("Primary key, '{0}', of type '{1}' is not int", property.Name, entityType)); } return property; } } } throw new ApplicationException(string.Format("No primary key defined for type {0}", entityType.Name)); } public T GetByID(int id) { var dbcontext = DB; var itemParameter = Expression.Parameter(typeof (T), "item"); var whereExpression = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property( itemParameter, typeof (T).GetPrimaryKey().Name ), Expression.Constant(id) ), new[] {itemParameter} ); return dbcontext.GetTable<T>().Where(whereExpression).Single(); } ```
What you need is to build an expression tree that [LINQ to SQL](http://en.wikipedia.org/wiki/Language_Integrated_Query#LINQ_to_SQL) can understand. Assuming your "id" property is always named "id": ``` public virtual T GetById<T>(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property( itemParameter, "id" ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable<T>(); return table.Where(whereExpression).Single(); } ``` This should do the trick. It was shamelessly borrowed from [this blog](http://mikehadlow.blogspot.com/2008/03/using-irepository-pattern-with-linq-to.html). This is basically what LINQ to SQL does when you write a query like ``` var Q = from t in Context.GetTable<T)() where t.id == id select t; ``` You just do the work for LTS because the compiler cannot create that for you, since nothing can enforce that T has an "id" property, and you cannot map an arbitrary "id" property from an interface to the database. ==== UPDATE ==== OK, here's a simple implementation for finding the primary key name, assuming there is only one (not a composite primary key), and assuming all is well type-wise (that is, your primary key is compatible with the "short" type you use in the GetById function): ``` public virtual T GetById<T>(short id) { var itemParameter = Expression.Parameter(typeof(T), "item"); var whereExpression = Expression.Lambda<Func<T, bool>> ( Expression.Equal( Expression.Property( itemParameter, GetPrimaryKeyName<T>() ), Expression.Constant(id) ), new[] { itemParameter } ); var table = DB.GetTable<T>(); return table.Where(whereExpression).Single(); } public string GetPrimaryKeyName<T>() { var type = Mapping.GetMetaType(typeof(T)); var PK = (from m in type.DataMembers where m.IsPrimaryKey select m).Single(); return PK.Name; } ```
What if you rework this to use GetTable().Where(...), and put your filtering there? That would be more efficient, since the Where extension method should take care of your filtering better than fetching the entire table into a list.
C# LINQ to SQL: Refactoring this Generic GetByID method
[ "", "c#", "linq-to-sql", "generics", "expression-trees", "" ]
One of the things I'm working on right now has some similarities to a game. For purposes of illustration, I'm going to explain my problem using an example drawn from a fictitious, hypothetical game. Let's call it *DeathBlaster 4: The Deathening*. In DB4, you have a number of `Ship` objects which periodically and randomly encounter `Phenomena` as they travel. A given `Phenomenon` may have zero, one, or more `Effects` on a `Ship` that encounters it. For example, we might have four kinds of `Ships` and three kinds of `Phenomena`. ``` Phenomena ========================================== Ships GravityWell BlackHole NebulaField ------------ ------------------------------------------ RedShip +20% speed -50% power -50% shield BlueShip  no effect invulnerable death Effects of Various GreenShip -20% speed death +50% shield Phenomena on Ships YellowShip death +50% power no effect ``` Additionally, `Effects` may interact with each other. For example, a `GreenShip` that is in both a `GravityWell` and a `NebulaField` may derive some kind of synergy between the generated `SpeedEffect` and `ShieldEffect`. In such cases, the synergistic effect is itself an `Effect` -- for example, there might be a `PowerLevelSynergyEffect` that results from this interaction. No information other than the set of `Effects` acting on a `Ship` is needed to resolve what the final result should be. You may begin to see a problem emerging here. As a naive first approach, **either every `Ship` will have to know how to handle every `Phenomenon`, or every `Phenomenon` will have to know about every `Ship`**. This is obviously unacceptable, so we would like to move these responsibilities elsewhere. Clearly there's at least one external class here, perhaps a `Mediator` or `Visitor` of some sort. But what's the best way to do that? The ideal solution will probably have these properties: * It's just as easy to add a new `Ship` as it is to add a new `Phenomenon`. * Interactions that produce no effect are the default and don't require additional code to represent. Convention over configuration. * Understands how `Effects` interact with each other and is capable of managing these interactions to decide what the final result will be. I've already decided what my approach will be, I think, but I'm interested to hear what the best-design consensus is. Where would you start? What avenues would you explore? --- --- **Follow-up update:** Thanks for your responses, everybody. Here's what I wound up doing. My main observation was that the number of different `Effects` seems to be small relative to the number of possible `Phenomena` × `Ships` interactions. That is, although there are many possible *combinations* of interactions, the number of *kinds of results* of those interactions is a smaller number. You can see that, for example, although there are 12 interaction combinations in the table, there are only five *kinds* of effects: modifications to speed, modifications to power, modifications to shield, invulnerability, death. I introduced a third class, the `InteractionResolver`, to determine the result of interactions. It contains a dictionary that maps `Ship-Phenomenon` pairs to `Effects` (which are basically a delegate that performs the effect and some metadata). Each `Ship` is handed an `EffectStack` corresponding to the `Effects` it's experiencing when the result of computing the interaction is complete. `Ships` then use the `EffectStack` to determine the actual result of the `Effects` on them, by adding modifiers to their existing attributes and properties. I like this because: * `Ship`s never need to know about `Phenomena`. * The complexity of the `Ship`-`Phenomena` relationship is abstracted into the `InteractionResolver`. * The details of how to resolve multiple and possibly complex effects is abstracted away by the `InteractionResolver`. Ships only have to apply the effects as necessary. * This enables additional useful refactorings. For example, the *way* in which a ship processes effects could be differentiated by making an `EffectProcessorStrategy`. The default might be to process all effects, but, say, a `BossShip` might ignore minor effects by having a different `EffectProcessorStrategy`.
An interesting potential option would be to use a variant of the [Visitor Pattern](http://en.wikipedia.org/wiki/Visitor_pattern). Judith Bishop and R. Nigel Horspool wrote a paper about [design pattern efficiency](http://webhome.cs.uvic.ca/~nigelh/Publications/Tools08.pdf) in which they explained various variants on the classic visitor pattern using C# 3 features. In particular, I would take a look at how they work with delegates to handle the visitor pattern. Using a list or stack of delegates could potentally give you an interesting way to handle multiple effects from multiple objects, and be much easier to extend either side of the class hierarchy (add ships or add effects) without huge breaking code changes.
I think the answer of a problem is depend on how good the question ask. I think the way to design is depend on what the question is(or the question will goes in the future) you give a table, then I think the solution is maintain a table and query it. python code here:(not tested and just shows for a example) ``` class Ship(): def __init__(self,type): self.type=type def encounterPhenomena(self,type): # let Phenomena to process ship p = Phenomena(type) p.process(self) class Phenomena(): processTable = {} def __init__(self,type): self.type=type def process(self,ship): try: self.processTable[self.type](ship.type) #query the internal table to process ship except: pass #if Phenomena don't know this ship type then no process.. def addType(type,processMethod): processTable[type]=processMethod #add new Phenomena, and add processMethod def run(): A = Ship(type = 'RedShip') A.encounterPhenomena(type='GravityWell'); ``` If process method changed, simply modify the process method in the Phenomena class. If you think ship need to know how to process Phenomena, then change process method into the ship class. or you think there are other things not only Phenomena need to change status of ship(like other ships, shoal rock), you need to maintain a process table in ship class and make Phenomena one of it, speak again, how to design is depend on the question its self.
What's the best way to resolve a combinatorial explosion of interactions?
[ "", "c#", "design-patterns", "software-design", "" ]
I know that you can use java.util.Properties to read Java properties files. See: [Java equivalent to app.config?](https://stackoverflow.com/questions/212539/java-equivalent-to-app-config) Is there a standard place to put this file? In .NET we put application.exe.config in the same directory as application.exe. The application looks for it here by default. Java can be made to look for a properties file in the class path but I am struggling to understand the filename/path structure to use and how to use either a standard .properties format or XML format file. Assuming I have an API packaged in org\_example\_api.jar (the root package is org.example.api). I don't want to put the properties file inside the jar as it should be editable by the user. I want the user to be able to put the required configuration properties in either a .properties or .xml file somewhere relative to the classpath so I can find it without needing to know anything about the ir file system structure. Will this work on all systems: ``` /classpath/org_example_api.jar /classpath/org/example/api/config.properties OR /classpath/org/example/api/config.xml ``` Code: ``` java.util.Properties = ? //NEED SOME HELP HERE ```
This purely depends on the type of application you are developing. 1) If it is a web application the best place is inside the WEB-INF/classes/ folder. 2) If you are developing a standalone application there are many approaches. From your example I think the following structure will work. ``` /<dist>/org_example_api.jar /<dist>/config.xml /<dist>/run.sh ``` In the run.sh you can start the java application providing the current directory also in the classpath. Something like this. java -cp .:org\_example\_api.jar ClassToExecute 3) If it is an API distribution it is up to the end user. You can tell the user that they can provide the config.xml in the classpath which should follow some predefined structure. You can look at Log4J as an example in this case.
The world is wide open to you here. The only best practice is what works best for you: 1. Whatever program the user is running can require the path to the properties file as an argument 2. Your application can be configured to look in the current directory for `config.properties`. 3. If the file can't be found, you could maybe fall back to the `user.home` directory, or fall back to wherever your application is installed. Personally I usually have my applications attempt to read properties files from the classpath - but I'm not in a world where I have end-users update/change the file. Whatever option you choose, just make sure you clearly document it for your users so they know which file to edit and where it needs to be!
Simulate app.config for Java?
[ "", "java", "configuration", "properties", "" ]
This is in python 2.4. Here is my situation. I pull a string from a database, and it contains an umlauted 'o' (\xf6). At this point if I run type(value) it returns str. I then attempt to run .decode('utf-8'), and I get an error ('utf8' codec can't decode bytes in position 1-4). Really my goal here is just to successfully make type(value) return unicode. I found an [earlier question](https://stackoverflow.com/questions/447107/whats-the-difference-between-encode-decode-python-2-x) that had some useful information, but the example from the picked answer doesn't seem to run for me. Is there something I am doing wrong here? Here is some code to reproduce: ``` Name = 'w\xc3\xb6rner'.decode('utf-8') file.write('Name: %s - %s\n' %(Name, type(Name))) ``` I never actually get to the write statement, because it fails on the first statement. Thank you for your help. **Edit:** I verified that the DB's charset is utf8. So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs. Is there a difference between 'utf-8' and 'utf8'? The tip on using codecs to write to a file is handy (I'll definitely use it), but in this scenario I am only writing to a log file for debugging purposes.
> So in my code to reproduce I changed '\xf6' to '\xc3\xb6', and the failure still occurs Not in the first line it doesn't: ``` >>> 'w\xc3\xb6rner'.decode('utf-8') u'w\xf6rner' ``` The second line will error out though: ``` >>> file.write('Name: %s - %s\n' %(Name, type(Name))) UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position 7: ordinal not in range(128) ``` Which is entirely what you'd expect, trying to write non-ASCII Unicode characters to a byte stream. If you use Jiri's suggestion of a codecs-wrapped stream you can write Unicode directly, otherwise you will have to re-encode the Unicode string into bytes manually. Better, for logging purposes, would be simply to spit out a repr() of the variable. Then you don't have to worry about Unicode characters being in there, or newlines or other unwanted characters: ``` name= 'w\xc3\xb6rner'.decode('utf-8') file.write('Name: %r\n' % name) Name: u'w\xf6rner' ```
Your string **is not** in UTF8 encoding. If you want to 'decode' string to unicode, your string must be in encoding you specified by parameter. I tried this and it works perfectly: ``` print 'w\xf6rner'.decode('cp1250') ``` **EDIT** For writing unicode strings to the file you can use codecs module: ``` import codecs f = codecs.open("yourfile.txt", "w", "utf8") f.write( ... ) ``` It is handy to specify encoding of the input/output and using 'unicode' string throughout your code without bothering of different encodings.
Unable to decode unicode string in Python 2.4
[ "", "python", "unicode", "decode", "" ]
I'm interested in knowing the actual average page loadtime for my webapplication. Simplistically, how log does my average visitor wait before they can start using a page on my site. From when they click the link to my site until the site is finished rendering & ready to accept input. The standard solution seems to be to use Javascript to compare the time from a script in the until a script in the window.onload() event. (See: <http://www.dreamincode.net/code/snippet1908.htm>) This doesn't seem like a very acturate measure to me, as it ignores the time taken to resolve my domain & receive enough HTML content to begin Javascript parsig. It also looks like Safari fires window.onload before the page has actually finished loading (<http://www.howtocreate.co.uk/safaribenchmarks.html>). Any ideas? Is it possible to get the time a the current request was initiated via Javascript? What event fires after everything is ready reliably across all browsers?
<http://www.webpagetest.org/> is an excellent resource for measuring load time Also google chorme dev tools has a Timeline panel where you can record events, Here is a 2.5minute video showing you how Timeline in google chrome works <http://www.youtube.com/watch?v=RhaWYQ44WEc>
[FireBug](https://addons.mozilla.org/de/firefox/addon/1843) has a "network timing mode" where you can see how long it took to download each resource which makes up your web page. Plus you should measure the time your server needs to prepare the request. Since you can't influence the browser and the network, rendering time on your server should be as small as possible.
What is a reliable way to calculate actual (web) page loadtime
[ "", "javascript", "performance", "pageload", "" ]
I have a list of objects. Object has 3 string attributes. I want to make a list containing only a specific attribute from class. Is there any built-in functions to do that?
A list comprehension would work just fine: ``` [o.my_attr for o in my_list] ``` But there is a combination of built-in functions, since you ask :-) ``` from operator import attrgetter map(attrgetter('my_attr'), my_list) ```
are you looking for something like this? ``` [o.specific_attr for o in objects] ```
How to extract from a list of objects a list of specific attribute?
[ "", "python", "" ]
If I have a `SomeDisposableObject` class which implements `IDisposable`: ``` class SomeDisposableObject : IDisposable { public void Dispose() { // Do some important disposal work. } } ``` And I have another class called `AContainer`, which has an instance of `SomeDisposableObject` as a public property: ``` class AContainer { SomeDisposableObject m_someObject = new SomeDisposableObject(); public SomeDisposableObject SomeObject { get { return m_someObject; } set { m_someObject = value; } } } ``` Then FxCop will insist that `AContainer` is also made `IDisposable`. Which is fine, but I can't see how I can safely call `m_someObject.Dispose()` from `AContainer.Dispose()`, as another class may still have a reference to the `m_someObject` instance. What is the best way to avoid this scenario? (Assume that other code relies on `AContainer.SomeObject` always having a non-null value, so simply moving the creation of the instance outside of the `AContainer` is not an option) **Edit**: I'll expand with some example as I think some commenters are missing the issue. If I just implement a `Dispose()` method on `AContainer` which calls m\_someObject.Dispose() then I am left with these situations: ``` // Example One AContainer container1 = new AContainer(); SomeDisposableObject obj1 = container1.SomeObject; container1.Dispose(); obj1.DoSomething(); // BAD because obj1 has been disposed by container1. // Example Two AContainer container2 = new AContainer(); SomeObject obj2 = new SomeObject(); container2.SomeObject = obj2; // BAD because the previous value of SomeObject not disposed. container2.Dispose(); obj2.DoSomething(); // BAD because obj2 has been disposed by container2, which doesn't really "own" it anyway. ``` Does that help?
There is no single answer, it depends on your scenario, and the key point is ownership of the disposable resource represented by the property, as [Jon Skeet points out](https://stackoverflow.com/questions/674879/who-disposes-of-an-idisposable-public-property/674896#674896). It's sometimes helpful to look at examples from the .NET Framework. Here are three examples that behave differently: * **Container always disposes**. System.IO.StreamReader exposes a disposable property BaseStream. It is considered to own the underlying stream, and disposing the StreamReader always disposes the underlying stream. * **Container never disposes**. System.DirectoryServices.DirectoryEntry exposes a Parent property. It is not considered to own its parent, so disposing the DirectoryEntry never disposes its parent. In this case a new DirectoryEntry instance is returned each time the Parent property is dereferenced, and the caller is presumably expected to dispose it. Arguably this breaks the guidelines for properties, and perhaps there should be a GetParent() method instead. * **Container sometimes disposes**. System.Data.SqlClient.SqlDataReader exposes a disposable Connection property, but the caller decides if the reader owns (and therefore disposes) the underlying connection using the CommandBehavior argument of SqlCommand.ExecuteReader. Another interesting example is System.DirectoryServices.DirectorySearcher, which has a read/write disposable property SearchRoot. If this property is set from outside, then the underlying resource is assumed not to be owned, so isn't disposed by the container. If it's not set from outside, a reference is generated internally, and a flag is set to ensure it will be disposed. You can see this with Lutz Reflector. You need to decide whether or not your container owns the resource, and make sure you document its behavior accurately. If you do decide you own the resource, and the property is read/write, you need to make sure your setter disposes any reference it's replacing, e.g.: ``` public SomeDisposableObject SomeObject { get { return m_someObject; } set { if ((m_someObject != null) && (!object.ReferenceEquals(m_someObject, value)) { m_someObject.Dispose(); } m_someObject = value; } } private SomeDisposableObject m_someObject; ``` **UPDATE**: GrahamS rightly points out in comments that it's better to test for m\_someObject != value in the setter before disposing: I've updated the above example to take account of this (using ReferenceEquals rather than != to be explicit). Although in many real-world scenarios the existence of a setter might imply that the object is not owned by the container, and therefore won't be disposed.
It really depends on who notionally "owns" the disposable object. In some cases, you may want to be able to pass in the object, for instance in the constructor, without your class taking responsibility for cleaning it up. Other times you may want to clean it up yourself. If you're creating the object (as in your sample code) then it should almost certainly be your responsibility to clean it up. As for the property - I don't think having a property should really transfer ownership or anything like that. If your type is responsible for disposing of the object, it should keep that responsibility.
Who Disposes of an IDisposable public property?
[ "", "c#", ".net", "dispose", "idisposable", "" ]
I'm creating a contextual menu in JavaScript for a web app. The menu can appear in numerous contexts, and have different choices. I could have a different function for each context/choice: ``` grid1_delete() grid1_duplicate() grid2_delete() grid2_add() grid2_duplicate() ``` and hard code those in as the menu is being built. The thing I don't like about that is there will probably be a lot of repeated code. So I was thinking about using a dispatcher function, but it's resulting in potentially long, nested switch statement thus: ``` function contextMenuClick(context, menuItem) { var action = menuItem.innerHTML; switch (context) { case 'grid1': switch(action) { case('delete'): // do delete for grid1 break; case('duplicate'): // do duplicate for grid1 break; default: console.log('undefined action in contextMenuClick/grid1: ' + context); } break; case 'grid2': switch(action) { case('add'): // do add for grid2 break; case('delete'): // do delete for grid2 break; case('duplicate'): // do duplicate for grid2 break; default: console.log('undefined action in contextMenuClick/grid2: ' + context); } break; default: console.log('undefined context in contextMenuClick: ' + context); } ``` Yuck. There's got to be a better way. Maybe the dispatcher is more trouble than it's worth. I've looked at some of [the](https://stackoverflow.com/questions/496189/what-is-the-best-easiest-way-to-use-nested-switch-case-statements) [related](https://stackoverflow.com/questions/494506/dealing-with-nested-if-then-else-nested-switch-statements) [posts](http://www.codinghorror.com/blog/archives/000486.html), but I'm not quite getting how to apply them to this exact situation.
Switch statements are very rarely necessary in Javascript. In general, you can just use objects like dictionaries/maps and do the lookup directly: `foo.bar` is equivalent to `foo['bar']`. Also, for "global" variables, `some_global_func()` is equivalent to `window.some_global_func()`, which can also be written as `var f = 'some_global_func'; window[f]()`: you don't *ever* need `eval` in order to select a variable or call a function dynamically based on its name. In general, when doing that, though, you should prefer to store the function in an object rather than at global scope (i.e. in the `window` object). So, assuming that `grid1_delete` and `grid2_delete` are fundamentally different and can't be combined into a generic function, you could do something like the following without changing your code much: ``` var grid_actions = { 'grid1': { 'delete': function() { /* ... */ }, 'duplicate': function() { /* ... */ } }, 'grid2': { 'delete': function() { /* ... */ }, 'add': function() { /* ... */ }, 'duplicate': function() { /* ... */ } } } function contextMenuClick(context, menuItem) { var action = menuItem.innerHtml; if (context in grid_actions) { if (action in grid_actions[context]) { grid_actions[context][action](); } else { console.log('undefined action in contextMenuClick/' + context + ': ' + action); } } else { console.log('undefined context in contextMenuClick: ' + context); } } ``` A better solution, though, is to refactor things to have have these functions be methods of objects for each context, like @[le dorfier](https://stackoverflow.com/users/31641/le-dorfier) suggests.
How about passing an actual object reference in for "context" instead of just a string? That way, you have just one switch statement: ``` function contextMenuClick(grid, menuItem) { var action = menuItem.innerHTML; switch(action) { case('delete'): grid.delete(); break; case('duplicate'): grid.duplicate(); break; } } ``` Better yet, simply bind the handler directly to the correct object/method.
how to avoid nested switch?
[ "", "javascript", "nested", "switch-statement", "" ]
I am using Hudson as a continuous integration server to test C/C++ code. Unfortunatly, I have a bug somewhere that causes memory corruption, so on some Windows machines I will sometimes get a "Application Error" dialog box explaining that an instruction referenced memory that could not be read. This dialog box pops up and basically hangs the test run, as it requires manual intervention. Is there a way to prevent this dialog box from appearing, so that the test run simply fails and is reported as such in Hudson? Is it possible to automatically generate a minidump instead of showing the dialog?
1. Use "Disable error reporting", as Mr. Gently suggests. See also [this PC World article](http://www.pcworld.com/article/108734/window_tips_xp_error_messagesyou_decide_what_to_report.html). 2. If you happen to have MS Visual Studio on your build machine, it will catch Application Errors and pop up a dialog box. To disable these dialogs (and also the Just-In-Time Debugging feature of Visual Studio), run the command `drwtsn32.exe -i` to set Dr. Watson as the default system debugger. Dr. Watson will generate a core dump and silently exit. (See this Microsoft Knowledge Base article: <http://support.microsoft.com/kb/q121434/>.)
You can also do something like this programaticaly using *SetErrorMode*. See [this](http://msdn.microsoft.com/en-us/library/ms680621(VS.85).aspx) article for more details. A simple example of how to use it is to do the following: ``` SetErrorMode(GetErrorMode () | SEM_NOGPFAULTERRORBOX); ``` The above 'ORs' the current mode with our desired addition.
Can the "Application Error" dialog box be disabled?
[ "", "c++", "windows", "debugging", "memory", "build-automation", "" ]
does anyone know of a Java library to fetch webpages through https?
Take a look at [HttpClient](http://hc.apache.org/httpcomponents-client-ga/)
As of 1.4, you can use boring old URL.openConnection()...
Fetching webpages through https
[ "", "java", "https", "" ]
I have a table with a column I would like to update its values. Here is an example of TSQL codes: ``` WITH Pieces(id, newdesc) AS ( SELECT itemid, REPLACE(REPLACE(description, 'DESC_A', 'DESC_B'), 'NEW_1', 'NEW_2') FROM myTable WHERE description like '%DESC_A%DESC_B%' ) -- SELECT * FROM Pieces UPDATE myTable SET description = newdesc // not working, how? ``` This update is NOT working. By commenting out SELECT, I can see the result is what I need. How I can do this change in a batch way for a group of rows? Not sure is it possible by WITH statement? Here are some example data: ``` .... xxxDESC_AyyyDESC_Bwwww aaaDESC_AxxDESC_Beee .... ``` the udpated ones will be: ``` .... xxxNEW_1yyyNEW_2wwww aaaNEW_1xxNEW_2eee .... ```
maybe ``` UPDATE myTable SET description = newdesc FROM Pieces WHERE Pieces.id = myTable.itemid ```
By the way, if you really want to use a CTE for the Update (although I prefer more straightforward updates), you can. But, you have to include the updated column in the CTE and the table you're updating is the CTE name, not the original tablename. Like this: ``` ;WITH Pieces(id, description, newdesc) AS( SELECT itemid, description, REPLACE(REPLACE(description, 'DESC_A', 'DESC_B'), 'NEW_1', 'NEW_2') FROM myTable WHERE description like '%DESC_A%DESC_B%' ) UPDATE Pieces SET description = newdesc ```
TSQL: Update values by using With statement?
[ "", "sql", "sql-server-2005", "t-sql", "" ]
I have object called Foo. Right now it implements IFoo which has a lot of properties on it. I have one class that only depends on a few of those properties so i create IMeasurableFoo (which just has a few properties) to avoid duplicate code, i now have IFoo : IMeasurableFoo as i moved the properties into IMeasurableFoo but this feels wrong from an inheritance point of view as you have a more generic interface inheriting from a specific interface any thoughts on the best way to organize these abstractions For example, if these were concretions: Bird would not inherit from FlyingBird (it would be the other way around)
No, it's not "more generic interface inheriting from a specific interface". `IMeasurableFoo`, having only several properties, is *the* generic interface, whereas `IFoo` is more specific, since it refines the knowledge about the `IMeasurableFoo`. Think `IList` inheriting from `IEnumerable`.
Maybe change the names? IMeasurableFoo sounds like a more specific interface indeed, but couldn't you just call it IFoo and rename the original IFoo interface? Or rename both? Is the IMeasurableFoo really an IFoo or (perhaps) an IMeasurable?
interface question
[ "", "c#", "interface", "" ]
I had a previous question [can jquery ajax call external webservice?](https://stackoverflow.com/questions/727183/can-jquery-ajax-call-external-webservice) and some good developers answered me to use jsonp, but i don't know how to use it, i am trying to call my service using this code: ``` $.ajax({ type: "POST", url: "http://localhost:1096/MySite/WebService.asmx?callback=?", data: "{}", contentType: "application/json; charset=utf-8", dataType: "jsonp", success: function(msg) {alert(msg);} }); ``` and this is my service code: ``` [WebMethod] public string HelloWorld() { return "Hello World " ; } ``` anyone have examples or can explain this issue for me? **UPDATE**: I wrote the code again to be like this: ``` $.getJSON("http://localhost:1096/YourShoppingTest1/WebService.asmx/HelloWorld?jsonp=?",{name:"test"}, function(data){ alert(data.x); }); ``` and the service like this: ``` [WebMethod] public string HelloWorld(string name) { return "( {\"x\":10 , \"y\":100} )"; } ``` But it always give me this error when back: "missing ; before statement [Break on this error] ( {"x":10 , "y":100} )" and never call the success function, can anyone help with that?
I've had a similiar problem, unfortunately I don't have the code at hand. From memory: * Add [ScriptService] as an attribute to your Web Method * Also change your url to call the HelloWorld procedure. Something like <http://localhost:1096/MySite/WebService.asmx/HelloWorld?callback> See: [What are some good examples of JQuery using JSONP talking to .net?](https://stackoverflow.com/questions/448879/what-are-some-good-examples-of-jquery-using-jsonp-talking-to-net) & [What is the best way to call a .net webservice using jquery?](https://stackoverflow.com/questions/426420/what-is-the-best-way-to-call-a-net-webservice-using-jquery)
The point with JSONP is the P! P as in padding. You are padding the JSON object literal with a function call - invoking a function on the calling page taking the data object as an argument. I.e. if you request the webservice, send the desired callback function name in the query string ``` ...service/?callback=hello ``` Then the service should answer (using appropriate mime type): ``` hello({a: 17, b: 4117}); ``` For a more in-depth explanation, see: <http://www.stpe.se/2008/10/cross-site-data-retrieval-using-jsonp/>
How to call external webservice using jquery "jsonp"?
[ "", "asp.net", "javascript", "jquery", "web-services", "" ]
Refactored from [bug\_report\_view.cc](http://src.chromium.org/viewvc/chrome/trunk/src/chrome/browser/views/bug_report_view.cc) and [bug\_report\_view.h](http://src.chromium.org/viewvc/chrome/trunk/src/chrome/browser/views/bug_report_view.h), I extracted `send_report()`, `report_phishing()`, a few other smaller functions and `BugReport::Cleanup` into [bug\_report.cc](http://codepad.org/pRBblPQQ) and [bug\_report.h](http://codepad.org/5mHJXwaf) (my versions). Compiling now, I get: > `[...]bug_report.cc:196: error: no matching function for call to ‘URLFetcher::URLFetcher(std::wstring&, URLFetcher::RequestType, BugReport::PostCleanup*)’ > ../chrome/browser/net/url_fetcher.h:136:` > > `note: candidates are: URLFetcher::URLFetcher(const URLFetcher&) > ../chrome/browser/net/url_fetcher.h:82:` > > `note: URLFetcher::URLFetcher(const GURL&, URLFetcher::RequestType, URLFetcher::Delegate*)` For some reason, `BugReport::PostCleanup` (in my version) isn't recognized as a subclass of URLFetcher::Delegate, but `BugReportView::PostCleanup` (in the first links) is. So where did I mess up? Thanks.
The problem is not the type of the PostCleanup class. The problem is the type of the first parameter to the URLFetcher class constructor. The constructor expects a GURL &, you are passing a `std::wstring` called `post_url`. You will need to perform some kind of conversion between the two. Possibly something like this would be appropriate: ``` GURL post_url(l10n_util::GetString(IDS_BUGREPORT_POST_URL)); URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST, new BugReport::PostCleanup); ``` In the code you have modified, the class has a GURL member which is initialised in the constructor, you have changed it to a variable referenced only in that one function, but changed the type.
At: ``` URLFetcher* fetcher = new URLFetcher(post_url, URLFetcher::POST, new BugReport::PostCleanup); ``` it can't find an URLFetcher constructor thzat takes the parameters youn give it - the problem is presumably in url\_fetcher.h, which you haven't shown. BTW, there are a lot of other problems and bad practices exhibited in your code - it would be a good idea to instigate a full code review ASAP.
How did I break inheritance?
[ "", "c++", "inheritance", "oop", "" ]
Is there a way to share a project across multiple solutions in SVN? I already have a class library in a solution that I want to import in another one. Can I just import the project in the new solution or will there be a problem with paths (since the project is not in the same repository)? Is there a better way to do this?
I'll add another `externals` link: [How to get started with svn:externals?](https://stackoverflow.com/questions/663155/how-to-get-started-with-svnexternals)
Sounds like you want [svn:externals](http://tortoisesvn.net/docs/release/TortoiseSVN_en/tsvn-dug-externals.html).
SVN - Project in multiple solutions
[ "", "c#", "svn", "project", "solution", "" ]
Let's say I have a byte-stream in which I know the location of a 64-bit value (a 64-bit nonce). The byte-order is Little-Endian. As PHP's integer data-type is limited to 32-bit (at least on 32-bit operating systems) how would I convert the byte-sequence into a PHP numeric representation (float would be sufficient I think)? ``` $serverChallenge = substr($bytes, 24, 8); // $serverChallenge now contains the byte-sequence // of which I know that it's a 64-bit value ```
Just looked up the code for `Zend_Crypt_Math_BigInteger_Bcmath` and `Zend_Crypt_Math_BigInteger_Gmp` which deals with this problem: ## Using BCmath (Big-Endian) This is essentially the solution posted by [Chad Birch](https://stackoverflow.com/questions/726092/converting-byte-stream-into-numeric-data-type/726323#726323). ``` public static function bc_binaryToInteger($operand) { $result = '0'; while (strlen($operand)) { $ord = ord(substr($operand, 0, 1)); $result = bcadd(bcmul($result, 256), $ord); $operand = substr($operand, 1); } return $result; } ``` ## Using GMP (Big-Endian) Same algorithem - just different function names. ``` public static function gmp_binaryToInteger($operand) { $result = '0'; while (strlen($operand)) { $ord = ord(substr($operand, 0, 1)); $result = gmp_add(gmp_mul($result, 256), $ord); $operand = substr($operand, 1); } return gmp_strval($result); } ``` Changing the algorithem to use Litte-Endian byte-order is quite simple: just read the binary data from end to start: ## Using BCmath (Litte-Endian) ``` public static function bc_binaryToInteger($operand) { // Just reverse the binray data $operand = strrev($operand); $result = '0'; while (strlen($operand)) { $ord = ord(substr($operand, 0, 1)); $result = bcadd(bcmul($result, 256), $ord); $operand = substr($operand, 1); } return $result; } ``` ## Using GMP (Litte-Endian) ``` public static function gmp_binaryToInteger($operand) { // Just reverse the binray data $operand = strrev($operand); $result = '0'; while (strlen($operand)) { $ord = ord(substr($operand, 0, 1)); $result = gmp_add(gmp_mul($result, 256), $ord); $operand = substr($operand, 1); } return gmp_strval($result); } ```
This seems like a total hack, but it should do the job, assuming you have the BC Math functions that daemonmoi recommended: ``` $result = "0"; for ($i = strlen($serverChallenge) - 1; $i >= 0; $i--) { $result = bcmul($result, 256); // shift result $nextByte = (string)(ord($serverChallenge[$i])); $result = bcadd($result, $nextByte); } ```
Converting byte-stream into numeric data-type
[ "", "php", "floating-point", "64-bit", "integer", "32-bit", "" ]
Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct? I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical. EDIT: Had to edit this further... I am pretty sure the class wouldn't be modified, so it's ok to that extent... my only concern is, if the person who coded that class gets to know of this, it might not go down well with him :(.
"Never say never". I'm sure somewhere in the universe, there's a situation that will force you to have to do this... But I certainly would cringe if I had to do it. You truly need get lots of opinions on your situation before pulling the trigger. Can you describe your specific situation and maybe we could see if it makes sense or what better alternatives might exist? In response to comment/question-- Define "permissions" -- institutional permission? That sounds like not a programming problem, but something to talk to whoever is asserting said permission. Maybe this is more of a political issue than a technical one? Again, I think we need more specifics--even if it was somewhat about the politics of the situation. That may or may not be deemed out of scope for the website, however.
Let's not consider ethics for a moment. Let's consider the standard. What you are proposing to do is nonstandard. See section 9.2, clause 12 of the standard. "The order of allocation of nonstatic members separated by an access-specifier is unspecified." Therefore, if you have a class with private members, and a struct with no private members, the standard does not guarantee that the members will be in the same order. Therefore, if your hack works, it works only by accident, that the compiler writers happened to do it that way. There is no guarantee that it will work on another compiler, a later version of the same compiler, or with different class layouts. Not to mention that, if you don't have authority to modify the class (say, to provide a simple accessor function), you probably don't have authority to object if any implementation detail in the class changes. (One of the ideas behind public and private is to distinguish what is promised from what is freely changeable.) Therefore, the layout may change, or the member might come to mean something different, or be removed altogether. Herb Sutter wrote [a Guru of the Week](http://www.gotw.ca/gotw/076.htm) column on this issue. Oh, as far as the ethics go? If you really, really have to do something like this, and you can't get out of it, document it very carefully. If your coding standards have some sort of procedure to flag nonstandard behavior, use them. If not, be very careful to note it in a way it won't be overlooked when something goes wrong.
Accessing private members
[ "", "c++", "private-members", "" ]
I have a sharepoint site that has an excel spreadsheet that I need to download on a schedulad basis Is this possible?
Why not just use `wget.exe <url>`. You can put that line in a batch file and run that through windows scheduler.
Yes it is possible to download the file from sharepoint. Once you have the url for the document, it can be downloaded using HttpWebRequest and HttpWebResponse. attaching a sample code ``` DownLoadDocument(string strURL, string strFileName) { HttpWebRequest request; HttpWebResponse response = null; request = (HttpWebRequest)WebRequest.Create(strURL); request.Credentials = System.Net.CredentialCache.DefaultCredentials; request.Timeout = 10000; request.AllowWriteStreamBuffering = false; response = (HttpWebResponse)request.GetResponse(); Stream s = response.GetResponseStream(); // Write to disk if (!Directory.Exists(myDownLoads)) { Directory.CreateDirectory(myDownLoads); } string aFilePath = myDownLoads + "\\" + strFileName; FileStream fs = new FileStream(aFilePath, FileMode.Create); byte[] read = new byte[256]; int count = s.Read(read, 0, read.Length); while (count > 0) { fs.Write(read, 0, count); count = s.Read(read, 0, read.Length); } // Close everything fs.Close(); s.Close(); response.Close(); } ``` You can also use the GetItem API of Copy service to download a file. ``` string aFileUrl = mySiteUrl + strFileName; Copy aCopyService = new Copy(); aCopyService.UseDefaultCredentials = true; byte[] aFileContents = null; FieldInformation[] aFieldInfo; aCopyService.GetItem(aFileUrl, out aFieldInfo, out aFileContents); ``` The file can be retrieved as a byte array.
How do I programatically download a file from a sharepoint site?
[ "", "c#", "file", "download", "" ]
I would like to send data over internet through a desktop application. I know a little bit about sockets. I have transferred the data within the LAN, but now I want to transfer the data over the internet. What is the best way to transfer both large and small quantities of data? My system is connected to the server which has the access to the internet. My system's IP address is dynamic. I don't know how to send the data to another system which is connected to the internet. Do I need to find the router address? (My IP address is generated as 192.168.1.15). Is using a socket enough, or is HTTP required?
Socket is enough if no firewalls/proxies are involved. But, as Internet is involved (not the fastest connection), I suggest for the sake of convenience you should better opt for remoting over http. That way, even if in the future the setup changes, and firewalls/proxies get involved in the equation, you should not worry.
If all you want to do is transfer raw data from one machine to another it's very easy to do using a TCP socket. Here's a quick example. Server: ``` ThreadPool.QueueUserWorkItem(StartTCPServer); private static void StartTCPServer(object state) { TcpListener tcpServer = new TcpListener(IPAddress.Parse("192.168.1.15"), 5442); tcpServer.Start(); TcpClient client = tcpServer.AcceptTcpClient(); Console.WriteLine("Client connection accepted from " + client.Client.RemoteEndPoint + "."); StreamWriter sw = new StreamWriter("destination.txt"); byte[] buffer = new byte[1500]; int bytesRead = 1; while (bytesRead > 0) { bytesRead = client.GetStream().Read(buffer, 0, 1500); if (bytesRead == 0) { break; } sw.BaseStream.Write(buffer, 0, bytesRead); Console.WriteLine(bytesRead + " written."); } sw.Close(); } ``` Client: ``` StreamReader sr = new StreamReader("source.txt"); TcpClient tcpClient = new TcpClient(); tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.15"), 5442)); byte[] buffer = new byte[1500]; long bytesSent = 0; while (bytesSent < sr.BaseStream.Length) { int bytesRead = sr.BaseStream.Read(buffer, 0, 1500); tcpClient.GetStream().Write(buffer, 0, bytesRead); Console.WriteLine(bytesRead + " bytes sent."); bytesSent += bytesRead; } tcpClient.Close(); Console.WriteLine("finished"); Console.ReadLine(); ```
How can I send data over the internet using a socket?
[ "", "c#", "sockets", "networking", "" ]
I have a common User / Role setup, with a user\_role join table. I'm trying to use Spring's HibernateTemplate to mass delete all locked users like this: ``` getHibernateTemplate().bulkUpdate("delete from User where locked=?", true); ``` If the user being deleted does not have any roles (no record in the user\_role table), then everything goes fine; however if the user does have a role record, I'm getting the following error: > integrity constraint violated - child > record found Roles are defined in User.java like this: ``` @ManyToMany(fetch = FetchType.EAGER) @JoinTable(name = "user_role", joinColumns = { @JoinColumn(name = "user_id") }, inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<Role>(); ``` So how can I batch delete users even if a user has child records? Thanks!
Bulk delete operations are not cascaded to **related entities** as per the JPA specification: > ### 4.10 Bulk Update and Delete Operations > > Bulk update and delete operations > apply to entities of a single entity > class (together with its subclasses, > if any). Only one entity abstract > schema type may be specified in the > FROM or UPDATE clause. > > ... > > A delete operation only applies to > entities of the specified class and > its subclasses. **It does not cascade > to related entities**. However, I'd expect the JPA provider to deal with join tables. Sadly, Hibernate doesn't and this is logged in [HHH-1917](http://opensource.atlassian.com/projects/hibernate/browse/HHH-1917). I'm afraid you'll have to fall back on native SQL to clean up the join table yourself or to use cascading foreign keys in the schema.
Application-level cascading (cascading through hibernate annotations or JPA annotations) only work if the actual entity is actually loaded from the db. When you use the hibernate template with HQL, you'll notice that the entities are not loaded, and the HQL is directly converted to SQL to be executed. If you want to batch delete you have to use an HQL query to delete all relevant tables (ie roles) before deleting the parent table data.
How to batch delete using bulkUpdate
[ "", "java", "hibernate", "spring", "orm", "" ]
How could one convert a string to upper case. The examples I have found from googling only have to deal with chars.
[Boost string algorithms](https://www.boost.org/doc/libs/1_73_0/boost/algorithm/string/case_conv.hpp): ``` #include <boost/algorithm/string.hpp> #include <string> std::string str = "Hello World"; boost::to_upper(str); std::string newstr = boost::to_upper_copy<std::string>("Hello World"); ```
``` #include <algorithm> #include <string> std::string str = "Hello World"; std::transform(str.begin(), str.end(), str.begin(), ::toupper); ```
Convert a String In C++ To Upper Case
[ "", "c++", "string", "" ]
I'm creating a calendar that displays a timetable of events for a month. Each day has several parameters that determine if more events can be scheduled for this day (how many staff are available, how many times are available etc). My database is set up using three tables: 1. Regular Schedule - this is used to create an array for each day of the week that outlines how many staff are available, what hours they are available etc 2. Schedule Variations - If there are variations for a date, this overrides the information from the regular schedule array. 3. Events - Existing events, referenced by the date. At this stage, the code loops through the days in the month and checks two to three things for each day. 1. Are there any variations in the schedule (public holiday, shorter hours etc)? 2. What hours/number of staff are available for this day? 3. (If staff are available) How many events have already been scheduled for this day? Step 1 and step 3 require a database query - assuming 30 days a month, that's 60 queries per page view. I'm worried about how this could scale, for a few users I don't imagine that it would be much of a problem, but if 20 people try and load the page at the same time, then it jumps to 1200 queries... Any ideas or suggestions on how to do this more efficiently would be greatly appreciated! Thanks!
I can't think of a good reason you'd need to limit each query to one day. Surely you can just select all the values between a pair of dates. Similarly, you could use a join to get the number of events scheduled events for a given day. Then do the loop (for each day) on the array returned by the database query.
Create a table: ``` t_month (day INT) INSERT INTO t_month VALUES (1), (2), ... (31) ``` Then query: ``` SELECT * FROM t_month, t_schedule WHERE schedule_date = '2009-03-01' + INTERVAL t_month.day DAY AND schedule_date < '2009-03-01' + INTERVAL 1 MONTH AND ... ``` Instead of `30` queries you get just one with a `JOIN`. Other `RDBMS`'s allow you to generate rowsets on the fly, but [**MySQL doesn't**](https://stackoverflow.com/questions/701444/how-do-i-make-a-row-generator-in-mysql). You, though, can replace `t_month` with ugly ``` SELECT 1 AS month_day UNION ALL SELECT 2 UNION ALL ... SELECT 31 ```
Best way to query calendar events?
[ "", "php", "mysql", "database", "" ]
If a thread is doing something like this: ``` const DWORD interval = 20000; DWORD ticks = GetTickCount(); while(true) { DoTasksThatTakeVariableTime(); if( GetTickCount() - ticks > interval ) { DoIntervalTasks(); ticks = GetTickCount(); } } ``` Eventually, ticks is going to wrap when the value doesn't fit in a DWORD. I've been discussing this with a colleague. One of us believes the code will still behave 'nicely' when the wrap occurs, because the subtraction operation will also wrap. The other of us, believes it won't always work, especially if the interval is large. Who's right, and why? Thanks.
From [the docs](http://msdn.microsoft.com/en-us/library/ms724408.aspx): > The elapsed time is stored as a DWORD > value. Therefore, the time will wrap > around to zero if the system is run > continuously for 49.7 days. To avoid > this problem, use GetTickCount64. > Otherwise, check for an overflow > condition when comparing times. However, DWORD is unsigned - so you should be okay. 0 - "very big number" = "small number" (assuming you don't have any overflow checking active, of course). I had a previous edit which suggested you'd get a negative number, but that was before I took into account that DWORD is unsigned. You'll still have a problem if the operation takes *just under* 49.7 days though. That may not be an issue for you ;) One way to test would be to stub out the `GetTickCount()` method so you could write unit tests where you explicitly make it wrap. Then again, if you're really only doubting the arithmetic part, you can easily write unit tests for that :) Really, the fact that the number is coming from a system clock is pretty much irrelevant so long as you know the behaviour when it wraps - and that's specified in the documentation.
Nothing bad happens, as long as: * You subtract `DWORD`s, rather than converting to some other type first. * Nothing you're trying to time takes longer than 49.7 days. This is because unsigned arithmetic overflow is well-defined in C, and wrapping behavior does exactly what we want. ``` DWORD t1, t2; DWORD difference; t1 = GetTickCount(); DoSomethingTimeConsuming(); t2 = GetTickCount(); ``` `t2 - t1` will produce the correct the value, even if `GetTickCount` wraps around. Just don't convert `t2` and `t1` to some other type (e.g. `int` or `double`) before doing the subtraction. This won't work if the programming language treats overflow as an error. It also won't work if `DoSomethingTimeConsuming()` takes longer than 49.7 days. You can't tell just by looking at `t2` and `t1` how many times `GetTickCount` wrapped around, unfortunately. --- Let's start with the the usual case, where no wraparound comes into play: ``` t1 = 13487231 t2 = 13492843 ``` Here, `t2 - t1 = 5612`, which means the operation took about five seconds. Now consider an operation that takes a short amount of time, but where `GetTickCount` did wrap around: ``` t1 = 4294967173 t2 = 1111 ``` The operation took 1234ms, but the timer wrapped around, and `1111 - 4294967173` is the bogus value of `-4294966062`. What ever will we do? Well, modulo 232, the result of subtraction wraps around, too: ``` (DWORD)-4294966062 == (DWORD)1234 ``` Finally, consider the edge case where an operation takes *nearly* 232 milliseconds, but not quite: ``` t1 = 2339189280 t2 = 2339167207 ``` Here, `GetTickCount` wrapped around, and came right back around where it was. Now `t2 - t1` yields the bogus-looking value of `4294945223`. That's because that's the amount of time the operation actually took! In general: ``` (base + offset) - base ≡ offset mod 2^32 ```
What happens when GetTickCount() wraps?
[ "", "c++", "c", "windows", "winapi", "" ]
I don't have much experience with tcsh, but I am interested in learning. I've been having issues getting Python to see `PYTHONPATH`. I can echo `$PYTHONPATH`, and it is correct, but when I start up Python, my paths do not show up in `sys.path`. Any ideas? EDIT: ``` [dmcdonal@tg-steele ~]$ echo $PYTHONPATH /home/ba01/u116/dmcdonal/PyCogent-v1.1 >>> from sys import path >>> from os import environ >>> path ['', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/setuptools-0.6c8-py2.5.egg', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/FiPy-2.0-py2.5.egg', '/apps/steele/Python-2.5.2', '/apps/steele/Python-2.5.2/lib/python25.zip', '/apps/steele/Python-2.5.2/lib/python2.5', '/apps/steele/Python-2.5.2/lib/python2.5/plat-linux2', '/apps/steele/Python-2.5.2/lib/python2.5/lib-tk', '/apps/steele/Python-2.5.2/lib/python2.5/lib-dynload', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages', '/apps/steele/Python-2.5.2/lib/python2.5/site-packages/Numeric'] >>> environ['PYTHONPATH'] '/apps/steele/Python-2.5.2' ```
How are you setting PYTHONPATH? You might be confusing tcsh's set vs. setenv. Use "set" to set what tcsh calls *shell variables* and use "setenv" to set *environment variables*. So, you need to use setenv in order for Python to see it. For example: ``` $ set FOO='bar' $ echo $FOO bar $ python -c 'import os; print os.getenv("FOO")' None $ setenv BAR 'wiz' $ echo $BAR wiz $ python -c 'import os; print os.getenv("BAR")' wiz ``` There is some more information available in [the variables section of the tcsh documentation](http://wings.buffalo.edu/computing/Documentation/unix/tcsh.html).
Make sure that you're not starting python with the `-E` option (which is: ignore environment variables). If you start python via a shell script or some other app, just double check it doesn't add anything. Since the list of sys.path is long, it can be hard to miss your paths. PYTHONPATH stuff normally gets added to about the middle of the list, after all the library paths. Any chance your paths are there, just buried in the middle?
No path in sys.path with Python and tcsh
[ "", "python", "tcsh", "" ]
How would I write the following query using Linq to SQL? ``` UPDATE [TB_EXAMPLE] SET [COLUMN1] = 1 ``` (My actual goal is more complex than this)
The DataContext class has two query methods, ExecuteCommand, and ExecuteQuery. The ExecuteQuery method returns LINQ to SQL Entities, so you need to pass a type to it: ``` [VB.Net] MyDataContext.ExecuteQuery(Of Product)("SELECT * FROM PRODUCTS") [C#] MyDataContext.ExecuteQuery<Product>("SELECT * FROM PRODUCTS"); ``` However, the ExecuteCommand doesn't need a type, you'd use this method for your UPDATE query Because you only need a String to write the query, you can use reflection to make a really generic UPDATE method for your DAL. ``` MyDataContext.ExecuteCommand("UPDATE Products WHERE ProductID = {0}",1) ``` or ``` MyDataContext.ExecuteCommand("UPDATE Products WHERE ProductID = 1") ```
Yes. The [DataContext](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx) has an [ExecuteCommand](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executecommand.aspx) method that will allow you to execute arbitrary (hopefully, parameterized) SQL. Quoting from the remarks on the DataContext link above: > This method is a pass-through > mechanism for cases where LINQ to SQL > does not adequately provide for a > particular scenario. > > The syntax for the command is almost > the same as the syntax used to create > an ADO.NET DataCommand. The only > difference is in how the parameters > are specified. Specifically, you > specify parameters by enclosing them > in braces ({…}) and enumerate them > starting from 0. The parameter is > associated with the equally numbered > object in the parameters array.
Is it possible to run arbitrary queries with Linq to SQL? (C#)
[ "", "c#", ".net", "linq-to-sql", "" ]
I have a PDF template file. It has a bunch of fields I need to write to using PHP. How can I easily determine the xy coordinates of a field in the file? Right now I am using xy locations but trial and error is very time consuming. Is there a better way to do this? Or even an easy way to get the xy coordinates of a point in a pdf file?
The form-filling part of your question seems related to [this question](https://stackoverflow.com/questions/77873/filling-pdf-forms-with-php/112712#112712). As for coords, I can't help with PHP but I have a good Perl solution for this. Here are [two](https://stackoverflow.com/questions/620470/how-can-i-get-the-width-and-height-of-a-text-string-with-campdf) [questions](https://stackoverflow.com/questions/196788/how-do-i-get-character-offset-information-from-a-pdf-document/203553#203553) about computing X,Y coords of text. CAM::PDF has a [fillformfields.pl](http://search.cpan.org/dist/CAM-PDF/bin/fillpdffields.pl) utility that can help.
In order of my preference: **Mac**: *Skim* - Select a Text Box. Look on the bottom right for X,Y, plus the box height & width. *Preview* (included in OSX), Select a Text Box: Tools -> Show Inspector -> pick 4th tab that has a little ruler icon. This gives coordinates, but with an upper-left origin (web standard origin, but not the pdf convention) **Linux and Unix**: don't know, but try... *GSView* *xpdf* *evince* *gnome-gv* **Windows**: *GSView* is now my favorite: fast, convenient alway-on coordinate display, free *Foxit Reader*, free for reading coordinates (see 'Properties' box), $100 if you want to save file revisions. *Foxit Phantom* ($130) does not display coordinates. *PDF-Xchange* will also do it for free, but the Y origin is upper-left, not lower-left, so you have to subtract every Y from your page height. And the coordinates have to be interpreted by reading an edge scale, which is hard to do accurately. *Adobe Acrobat* - A sales and a tech support ticket I filed say that the $700 reader will do it. I haven't checked.
How to get the X,Y coordinates of a point in a PDF
[ "", "php", "pdf", "" ]
Has anybody here ever used ngen? Where? why? Was there any performance improvement? when and where does it make sense to use it?
Yes, I've seen performance improvements. My measurements indicated that it did improve startup performance if I also put my assemblies into the GAC since my assemblies are all strong named. If your assemblies are strong named, NGen won't make any difference without using the GAC. The reason for this is that if you have strong named assemblies that are not in the GAC, then the .NET runtime validates that your strong named assembly hasn't been tampered with by loading the whole managed assembly from disk so it can validate it circumventing one of the major benefits of NGen. This wasn't a very good option for my application since we rely on common assemblies from our company (that are also strong named). The common assemblies are used by many products that use many different versions, putting them in the GAC meant that if one of our applications didn't say "use specific version" of one of the common assemblies it would load the GAC version regardless of what version was in its executing directory. We decided that the benefits of NGen weren't worth the risks.
I don't use it day-to-day, but it is used by tools that want to boost performance; for example, Paint.NET uses NGEN during the installer (or maybe first use). It is possible (although I don't know for sure) that some of the MS tools do, too. Basically, NGEN performs much of the JIT for an assembly up front, so that there is very little delay on a cold start. Of course, in most typical usage, not 100% of the code is ever reached, so in some ways this does a lot of *unnecessary* work - but it can't tell that ahead of time. The downside, IMO, is that you need to use the GAC to use NGEN; I try to avoid the GAC as much as possible, so that I can use robocopy-deployment (to servers) and ClickOnce (to clients).
Have you ever used ngen.exe?
[ "", "c#", ".net", "optimization", "clr", "ngen", "" ]
I need to get the last element of a split array with multiple separators. The separators are commas and space. If there are no separators it should return the original string. If the string is "how,are you doing, today?" it should return "today?" If the input were "hello" the output should be "hello". How can I do this in JavaScript?
``` const str = "hello,how,are,you,today?" const pieces = str.split(/[\s,]+/) const last = pieces[pieces.length - 1] console.log({last}) ``` At this point, `pieces` is an array and `pieces.length` contains the size of the array so to get the last element of the array, you check `pieces[pieces.length-1]`. If there are no commas or spaces it will simply output the string as it was given. ``` alert(pieces[pieces.length-1]); // alerts "today?" ```
There's a one-liner for everything. :) ``` var output = input.split(/[, ]+/).pop(); ```
Getting the last element of a split string array
[ "", "javascript", "split", "" ]
If I run the two statements in batch will they return one table to two to my sqlcommand object with the data merged. What I am trying to do is optimize a search by searching twice, the first time on one set of data and then a second on another. They have the same fields and I’d like to have all the records from both tables show and be added to each other. I need this so that I can sort the data between both sets of data but short of writing a stored procedure I can’t think of a way of doing this. Eg. Table 1 has columns A and B, Table 2 has these same columns but different data source. I then wan to merge them so that if a only exists in one column it is added to the result set and if both exist it eh tables the column B will be summed between the two. Please note that this is not the same as a full outer join operation as that does not merge the data. **[EDIT]** Here's what the code looks like: ``` Select * From (Select ID,COUNT(*) AS Count From [Table1]) as T1 full outer join (Select ID,COUNT(*) AS Count From [Table2]) as T2 on t1.ID = T2.ID ```
Possibly: ``` select table1.a, table1.b from table1 where table1.a not in (select a from table2) union all select table1.a, table1.b+table2.b as b from table1 inner join table2 on table1.a = table2.a ``` edit: perhaps you would benefit from unioning the tables *before* counting. e.g. ``` select id, count() as count from (select id from table1 union all select id from table2) ```
Perhaps you're looking for UNION? IE: ``` SELECT A, B FROM Table1 UNION SELECT A, B FROM Table2 ```
How do I merge data from two tables in a single database call into the same columns?
[ "", "sql", "merge", "" ]
How can I access an inherited protected field from an object by reflection?
Two issues you may be having issues with - the field might not be accessible normally (private), and it's not in the class you are looking at, but somewhere up the hierarchy. Something like this would work even with those issues: ``` public class SomeExample { public static void main(String[] args) throws Exception{ Object myObj = new SomeDerivedClass(1234); Class myClass = myObj.getClass(); Field myField = getField(myClass, "value"); myField.setAccessible(true); //required if field is not normally accessible System.out.println("value: " + myField.get(myObj)); } private static Field getField(Class clazz, String fieldName) throws NoSuchFieldException { try { return clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e) { Class superClass = clazz.getSuperclass(); if (superClass == null) { throw e; } else { return getField(superClass, fieldName); } } } } class SomeBaseClass { private Integer value; SomeBaseClass(Integer value) { this.value = value; } } class SomeDerivedClass extends SomeBaseClass { SomeDerivedClass(Integer value) { super(value); } } ```
Use `FieldUtils.writeField(object, "fieldname", value, true)` or `readField(object, "fieldname", true)` from [Apache Commons lang3](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/reflect/FieldUtils.html).
Java reflection - access protected field
[ "", "java", "reflection", "field", "protected", "" ]
I am trying to view SQL generated by Linq to SQL in the SQL Server Profiler (2005). I can see the sql sent to the server from anything except for linq to sql. I'm betting that I need to change event selections for the trace, but not sure what else to select. I am currently only selecting this: SQL:StmtCompleted - TextData & SPID I don't want to use data context logging nor the SQL Debug Visualizer. I need to use the profiler. Why can I not see the LINQ to SQL queries? Thanks. ### EDIT I added SQL:BatchCompleted and that hasn't helped. ### EDIT 2 I added the event RPC:Completed which is found under the Stored Procedures category in event selection. This worked!
You need RPC call - the queries are executed as exec\_sql.
Are you including enough of the options in the SQL Profiler to see the BatchCompleted events, too? Marc
SQL server profiler not showing LINQ To Sql queries
[ "", "sql", "sql-server", "sql-server-2005", "linq-to-sql", "sql-server-profiler", "" ]
I have a set of functions I want to be available to my web pages and user controls in my c# .net 3.5 web project. My standard approach for pages is to create a "base page" that extends the System.Web.UI.Page class and then have my pages inherit from this, rather than directly from the Page class. I now want to expose some of these functions to my web controls (ascx) and web services. I can think of a number of ways to do this, but they seem a little clumsy and I think I'm missing a trick. Is there an easy way to provide some common functions to both my pages, web services and controls using inheritance, or do I need to wrap these functions in a class that all of them can access? An example to clarify: * I have a singleton that handles most functionality for my web application. * At the start of each request I want to check that the class exists in the web cache and initialise it if not. Initially this was handled in a page base that the pages all used. Now I need to be able to access my singleton safely from services and controls, with the same checks. I have therefore extracted the checking and initialisation logic into another class, that then each of my base page, control and web service, all instantiate. Even with this model I have the same code repeated in 3 places (each of my base classes for controls, ws and pages), albeit not much code, this seems wrong too! It works, but it seems clumsy...I look forward to you guys humbling me with your wisdom!
Sounds to mee like a case of aspect-oriented programming. .NET is ill equipped for this. I'm afraid that your solution is one of the best. Alternatively perhaps you can move all or some of those functions to a static class/singleton and then use that class from your aspx/ascx/asmx? Not much in the way of inheritance, but at least less code duplication.
In your Singleton you could provide a Strategy interface to allow variations of the code depending on the configured environment. This would allow you to switch between web/windows/wcf...and so on.
Common inheritance for pages, web services and web controls
[ "", "c#", ".net", "asp.net", "" ]
We have an application which imports objects from an XML. The XML is around 15 GB. The application invariably starts running out of memory. We tried to free memory in between operations but this has lead to degrading performance. i.e it takes more time to complete the import operation. The CPU utilization reaches 100% The application is written in C++. Does the frequent call to `free()` will lead to performance issues? --- Promoted from a comment by the OP: the parser being used in expat, which is a SAX parser with a very small footprint, and customisable memory management.
Have you tried resuing the memory and your classes as opposed to freeing and reallocating it? Constant allocation/deallocation cycles, especially if they are coupled with small (less than 4096 bytes) data fragments can lead to serious performance problems and memory address space fragmentation.
Use [SAX](http://en.wikipedia.org/wiki/Simple_API_for_XML) parser instead of [DOM](http://en.wikipedia.org/wiki/Document_Object_Model) parser.
Memory management while loading huge XML files
[ "", "c++", "xml", "memory", "memory-management", "" ]
Using LINQ what is the best way to select a single item from a list if the item may not exists in the list? I have come up with two solutions, neither of which I like. I use a where clause to select the list of items (which I know will only be one), I can then check the count and make a Single call on this list if count is one, the other choice is to use a foreach and just break after getting the item. Neither of these seem like a good approach, is there a better way?
You can use `IEnumerable.First()` or `IEnumerable.FirstOrDefault()`. The difference is that `First()` will throw if no element is found (or if no element matches the conditions, if you use the conditions). `FirstOrDefault()` will return `default(T)` (`null` if it's a reference type).
Use the FirstOrDefault selector. ``` var list = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var firstEven = list.FirstOrDefault(n => n % 2 == 0); if (firstEven == 0) Console.WriteLine("no even number"); else Console.WriteLine("first even number is {0}", firstEven); ``` **Just pass in a predicate to the [First](http://msdn.microsoft.com/en-us/library/bb291976.aspx) or [FirstOrDefault](http://msdn.microsoft.com/en-us/library/bb340482.aspx) method** and it'll happily go round' the list and picks the first match for you. If there isn't a match, FirstOrDefault will returns the default value of whatever datatype the list items is. Hope this helps :-)
Select single item from a list
[ "", "c#", "linq", "" ]
One of my projects on Linux uses blocking sockets. Things happen very serially so non-blocking would just make things more complicated. Anyway, I am finding that often a `recv()` call is returning `-1` with `errno` set to `EAGAIN`. The `man` page only really mentions this happening for non-blocking sockets, which makes sense. With non-blocking, the socket may or may not be available so you might need to try again. **What would cause it to happen for a blocking socket? Can I do anything to avoid it?** At the moment, my code to deal with it looks something like this (I have it throw an exception on error, but beyond that it is a very simple wrapper around `recv()`): ``` int ret; do { ret = ::recv(socket, buf, len, flags | MSG_NOSIGNAL); } while(ret == -1 && errno == EAGAIN); if(ret == -1) { throw socket_error(strerror(errno)); } return ret; ``` **Is this even correct?** The `EAGAIN` condition gets hit pretty often. **EDIT:** some things which I've noticed which may be relevant. 1. I do set a read timeout on the socket using `setsockopts()`, but it is set to 30 seconds. the `EAGAIN`'s happen way more often than once every 30 secs. **CORRECTION** my debugging was flawed, `EAGAIN`'s don't happen as often as I thought they did. Perhaps it is the timeout triggering. 2. For connecting, I want to be able to have connect timeout, so I temporarily set the socket to non-blocking. That code looks like this: ``` int error = 0; fd_set rset; fd_set wset; int n; const SOCKET sock = m_Socket; // set the socket as nonblocking IO const int flags = fcntl (sock, F_GETFL, 0); fcntl(sock, F_SETFL, flags | O_NONBLOCK); errno = 0; // we connect, but it will return soon n = ::connect(sock, addr, size_addr); if(n < 0) { if (errno != EINPROGRESS) { return -1; } } else if (n == 0) { goto done; } FD_ZERO(&rset); FD_ZERO(&wset); FD_SET(sock, &rset); FD_SET(sock, &wset); struct timeval tval; tval.tv_sec = timeout; tval.tv_usec = 0; // We "select()" until connect() returns its result or timeout n = select(sock + 1, &rset, &wset, 0, timeout ? &tval : 0); if(n == 0) { errno = ETIMEDOUT; return -1; } if (FD_ISSET(sock, &rset) || FD_ISSET(sock, &wset)) { socklen_t len = sizeof(error); if (getsockopt(SOL_SOCKET, SO_ERROR, &error, &len) < 0) { return -1; } } else { return -1; } done: // We change the socket options back to blocking IO if (fcntl(sock, F_SETFL, flags) == -1) { return -1; } return 0; ``` The idea is that I set it to non-blocking, attempt a connect and select on the socket so I can enforce a timeout. Both the set and restore `fcntl()` calls return successfully, so the socket should end up in blocking mode again when this function completes.
It's possible that you have a nonzero receive timeout set on the socket (via `setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,...)`) as that would also cause recv to return `EAGAIN`
Is it possible that you're using `MSG_DONTWAIT` is being specified as part of your flags? The `man` page says `EAGAIN` will occur if no data is available and this flag is specified. If you really want to force a block until the `recv()` is somewhat successful, you may wish to use the `MSG_WAITALL` flag.
Blocking socket returns EAGAIN
[ "", "c++", "c", "linux", "sockets", "" ]
I have yet to find a good reference on this topic. For this example we will take some C++ code that I'm trying to port over to C#. In C++ land we have the following prototype for an external library function: ``` extern "C" DWORD EXPORT FILES_GetMemoryMapping( PSTR pPathFile, PWORD Size, PSTR MapName, PWORD PacketSize, PMAPPING pMapping, PBYTE PagesPerSector); ``` and in it is used like such: ``` FILES_GetMemoryMapping((LPSTR)(LPCTSTR)MapFile, &Size, (LPSTR)MapName, &PacketSize, pMapping, &PagePerSector); ``` Now I'm trying to port the first line over to C# and here is where I'm presented with no clear path. This is what I've got so far: ``` [DllImport("Files.DLL")] public static extern uint FILES_GetMemoryMapping( [MarshalAs(UnmanagedType.LPStr)] string pPathFile, out ushort Size, [MarshalAs(UnmanagedType.LPStr)] string MapName, out ushort PacketSize, IntPtr pMapping, out byte PagesPerSector); ``` Now the question is: Is there any good guide out there that tells me a "PSTR pPathFile" should be "[MarshalAs(UnmanagedType.LPStr)] string pPathFile" ... Assuming that is correct? Or, a that a pointer to a "PMAPPING" struct becomes a "out IntPtr pMapping" ... assuming that is correct? Any help on this one guys?
> I have yet to find a good reference on this topic [Here you go.](http://www.pinvoke.net/) Oddly, the site is down at the moment, but it's a very good resource for marshalling problems. In the mean time, you can use Archive.net's archive of pinvoke.net at <http://web.archive.org/web/20080202041852/http://www.pinvoke.net>
In addition to the [P/Invoke](http://www.pinvoke.net/) site, [Adam Nathan](http://blogs.msdn.com/adam_nathan/)'s *[.NET and COM: The Complete Interoperability Guide](https://rads.stackoverflow.com/amzn/click/com/067232170X)* is something worthwhile adding to your bookshelf if you've more than a passing interest in .NET interop. Kev
C# formatting external Dll function parameters
[ "", "c#", "marshalling", "dllimport", "" ]
I need a way of sorting a string I have in PHP, the string is formatted like the one below, but is much bigger. ``` { 1, 3, 1, 2, }, { 2, 3, 2, 1, }, { 3, 3, 2, 2, }, { 1, 2, 3, 1, }, ``` What I would need it to do is turn each set of numbers that is in the brackets into an array. So in this case there would be four arrays with four values in each array. The first array would look like the following: ``` array1[0] == 1 array1[1] == 3 array1[2] == 1 array1[3] == 2 ``` How would I manage to do this?
``` $inbound = "{ 1, 3, 1, 2, }, { 2, 3, 2, 1, }, { 3, 3, 2, 2, }, { 1, 2, 3, 1, }"; $inbound = trim(preg_replace("/,\\s*}/i", "}", $inbound), " ,"); $inbound = str_replace("{", "[", $inbound); $inbound = str_replace("}", "]", $inbound); $array_of_arrays = json_decode('[' . $inbound . ']'); ```
I can't comment (<50) but for Sean Bright, the problem with blank echo is that the json\_decode doesn't like the trailing "," inside the [ ].. edit : $inbound = str\_replace( array( '{', ', }' ), array( '[', ']' ), $inbound ); fixes.
Processing a string in PHP
[ "", "php", "arrays", "" ]
I have the following issue: when a stored proc is called from my application, every now and then (like 1 time out of 1000 calls), it takes 10-30 seconds to finish. Typically, the sproc runs in under a second. It's a fairly simply proc with a single select that ties together a couple of tables. All the table names are set with a (NOLOCK) hint, so it probably isn't locking. The indexes are all in place too, otherwise it would be slow all the time. The problem is that I can't replicate this issue in SSMS (as it always runs subsecond) no matter how many times it runs the sproc, yet I see the problem when I point the profiler to the user who's running my app. The query plan in SSMS seems correct, yet the problem persists. Where do I go from here? How do I debug this issue?
* Autogrows on the database? Check for messages in the SQL error logs. * Page splits due to inserted records? Check table fragmentation with DBCC SHOWCONTIG * Antivirus scans? Don't. * Out of date statistics? Don't rely on auto-update statistics on tables that change a lot. * Don't rule out a problem on the client end, or the networking between them. * Run profiler with a filter on duration, only capturing events with duration > 10 seconds, look for patterns in parameters, clients, time of day.
Some options: * What does profiler or `SET STATISTICS xx ON` say? Is there simply resource starvation, say CPU * The engine decides statistics are out of date. Are the tables changing by 10% row count change (rule of thumb). To test: ``` SELECT name AS stats_name, STATS_DATE(object_id, stats_id) AS statistics_update_date FROM sys.stats WHERE object_id IN (OBJECT_ID('relevanttable1'), OBJECT_ID('relevanttable2')) ``` * What else is happening on the server? example: Index rebuild: not blocking, just resource intensive. Usually I'd suggest parameter sniffing but you say the parameters are the same for every call. I'd also expect it to happen more often.
SQL Server 2005 stored procedure performance problem
[ "", "sql", "sql-server", "sql-server-2005", "performance", "stored-procedures", "" ]
How to print the bit representation of a string ``` std::string = "\x80"; void print (std::string &s) { //How to implement this } ```
I'd vote for `bitset`: ``` void pbits(std::string const& s) { for(std::size_t i=0; i<s.size(); i++) std::cout << std::bitset<CHAR_BIT>(s[i]) << " "; } int main() { pbits("\x80\x70"); } ```
Little-endian or big-endian? ``` for (int i = 0; i < s.length(); i++) for (char c = 1; c; c <<= 1) // little bits first std::cout << (s[i] & c ? "1" : "0"); for (int i = 0; i < s.length(); i++) for (unsigned char c = 0x80; c; c >>= 1) // big bits first std::cout << (s[i] & c ? "1" : "0"); ``` Since I hear some grumbling about portability of assuming that a `char` is a 8-bit byte in the comments of the other answers... ``` for (int i = 0; i < s.length(); i++) for (unsigned char c = ~((unsigned char)~0 >> 1); c; c >>= 1) std::cout << (s[i] & c ? "1" : "0"); ``` This is written from a very `C`-ish standpoint... if you're already using C++ with STL, you might as well go the whole way and take advantage of the STL bitset functionality instead of playing with strings.
Print bit representation of a string
[ "", "c++", "printing", "bit", "" ]
Using the standard English letters and underscore only, how many characters can be used at a maximum without causing a potential collision in a hashtable/dictionary. So strings like: ``` blur Blur b Blur_The_Shades_Slightly_With_A_Tint_Of_Blue ``` ...
There's no guarantee that you won't get a collision between single letters. You *probably* won't, but the algorithm used in `string.GetHashCode` isn't specified, and could change. (In particular it changed between .NET 1.1 and .NET 2.0, which burned people who assumed it wouldn't change.) Note that hash code collisions won't stop well-designed hashtables from working - you should still be able to get the right values out, it'll just potentially need to check more than one key using equality if they've got the same hash code. Any dictionary which relies on hash codes being unique is missing important information about hash codes, IMO :) (Unless it's operating under *very* specific conditions where it absolutely *knows* they'll be unique, i.e. it's using a [perfect hash function](http://en.wikipedia.org/wiki/Perfect_hash_function).)
Given a [perfect hashing function](http://en.wikipedia.org/wiki/Perfect_hash_function) (which you're not typically going to have, as others have mentioned), you can find the *maximum possible* number of characters that guarantees no two strings will produce a collision, as follows: --- No. of unique hash codes avilable = 2 ^ 32 = 4294967296 (assuming an 32-bit integer is used for hash codes) Size of character set = 2 \* 26 + 1 = 53 (26 lower as upper case letters in the Latin alphabet, plus underscore) Then you must consider that a string of length `l` (or less) has a total of `54 ^ l` representations. Note that the base is 54 rather than 53 because the string can terminate after any character, adding an extra possibility per char - not that it greatly effects the result. Taking the no. of unique hash codes as your maximum number of string representations, you get the following simple equation: `54 ^ l = 2 ^ 32` And solving it: ``` log2 (54 ^ l) = 32 l * log2 54 = 32 l = 32 / log2 54 = 5.56 ``` (Where log2 is the logarithm function of base 2.) Since string lengths clearly can't be fractional, you take the integral part to give a maximum length of just **5**. Very short indeed, but observe that this restriction would prevent even the remotest chance of a collision given a perfect hash function. --- This is largely theoretical however, as I've mentioned, and I'm not sure of how much use it might be in the design consideration of anything. Saying that, hopefully it should help you understand the matter from a theoretical viewpoint, on top of which you can add the practical considersations (e.g. non-perfect hash functions, non-uniformity of distribution).
Hashtable/Dictionary collisions
[ "", "c#", "string", "math", "dictionary", "hashtable", "" ]
i have a tcp server that, when a client connects, it makes a new thread and adds them to it but everytime i try to access information about the connection or anything about it, say even keeping a count of how many clients are connected, i get a cross-thread illegal exception or something like that. ive read several tutorials on things called delegates, invoking and reflection but all the examples or tutorials simply confuse me as doing one invoke a certain way fails in another. is there an elegant or simplistic way of doing this? do i need to learn how to do something else first? or am i just making things way more complex than they are? any suggestions, links or tips are most appreciated and accepted.
I guess you get this cross thread exception since you are trying to update screen elements from your threaded code. If you need to do that you can get a simple solution using anonymous method. Say that you want to add an item to a listbox called ListBoxLog. This code would do the trick from any thread: ``` ListBoxLog.Invoke((MethodInvoker)delegate { ListBoxLog.Items.Add("Done"); }); ``` There's also a property to check .InvokeRequired you can check to see if invocation is nessecary. You would typically check that property in a function that could be called by both the main UI thread and any background thread. You can also use BeginInvoke like I did with Invoke. BeginInvoke is totaly asynchronous and does not wait for the code in the delegate to finish.
I suppose you go directly to the UI from your client connection thread. This is not good. Instead, consider using some variation of MVP pattern to decouple presentation logic from views. Thus, your "connection threads" will talk to some intermediary, presenters will talk to the same intermediary and just hand off some data for view to display. As far as cross-thread operations are concerned, particulary UI thread operations, I find `SynchronizationContext` to be very useful in cicrumstances when you want to marshal a call from a non-UI thread to the UI thread. See [this article](http://www.codeproject.com/KB/threads/SynchronizationContext.aspx) for more in-depth discussion.
C#: How can i elegantly and or simplistically make cross threaded calls?
[ "", "c#", "visual-studio-2008", "" ]
when i am going through my project in IE only its showing errors A runtime error has occurred Do you wish to debug? Line 768 Error:Expected')' Is this is regarding any script error
Yes, it looks like you have a javascript syntax error. Check unclosed paranthesis and unclosed string literals in your client script blocks.
[This](http://www.jonathanboutelle.com/mt/archives/2006/01/howto_debug_jav.html) might be helpful for javascript debugging in Internet Explorer.
Internet Explorer problem - runtime error
[ "", "c#", "asp.net", "internet-explorer", "scripting", "" ]
I'm trying to use fixed width fonts in Java. I can use Courier or Lucida Console, but when I apply a "bold" style, it makes the characters larger in width and that's not acceptible in my application. Is there anyway I can force the bold characters to have the same width as non-bold characters?
`Monospaced` should work on any platform. On Windows, I like `Consolas`. `Courier New` should also work.
The only solution I can think of is to find a font face that renders with exactly the same width regardless of the bold property. I am yet to find such font.
bold fixed fonts in Java Swing
[ "", "java", "swing", "fonts", "" ]
I'm trying to format various numbers on my page. These numbers either represent a price, a change in price, or a percentage. I know Javascript has functions to limit the number of decimal places, but is there any support for other types of formatting, such as grouping numbers with commas, controlling whether or not the +/- is shown, etc? Here's what I have so far: ``` var FORMATTER = { price : function(value) { return '$' + value.toFixed(2); }, pricePer : function(value) { return (value * 100).toFixed(2) + '%'; }, priceChg : function(value) { return (value >= 0 ? '+' : '-') + '$' + Math.abs(value).toFixed(2); } }; ``` It works OK, but it'd like to add commas to the 'price' formatter, and you can see that there's a hack in the 'priceChg' formatter where I try to move the +/- sign in front of the '$' sign. Basically, I'm hoping there is some library out there (jQuery is OK) that emulates Java's DecimalFormat class.
There's the NUMBERFORMATTER jQuery plugin, details below: <https://code.google.com/p/jquery-numberformatter/> From the above link: > This plugin is a NumberFormatter > plugin. Number formatting is likely > familiar to anyone who's worked with > server-side code like Java or PHP and > who has worked with > internationalization. EDIT: Replaced the link with a more direct one.
No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you. EDIT: I missed the last sentence of your post. Try <http://code.google.com/p/jquery-utils/wiki/StringFormat> for a jQuery solution.
Javascript: Easier way to format numbers?
[ "", "javascript", "jquery", "formatting", "" ]
Let's suppose I have a struct like this: ``` struct my_struct { int a; int b; } ``` I have a function which should set a new value for either "a" or "b". This function also requires to specify which variable to set. A typical example would be like this: ``` void f(int which, my_struct* s, int new_value) { if(which == 0) s->a = new_value; else s->b = new_value; } ``` For reasons I won't write here I cannot pass the pointer to a/b to f. So I cannot call f with address of my\_struct::a or my\_struct::b. Another thing I cannot do is to declare a vector (int vars[2]) within my\_struct and pass an integer as index to f. Basically in f I need to access the variables by name. Problem with previous example is that in the future I plan to add more variables to struct and in that case I shall remember to add more if statements to f, which is bad for portability. A thing I could do is write f as a macro, like this: ``` #define FUNC(which) void f(my_struct* s, int new_value) \ { \ s->which = new_value; \ } ``` and then I could call FUNC(a) or FUNC(b). This would work but I don't like using macros. So my question is: Is there a way to achieve the same goal using templates instead of macros? **EDIT**: I'll try to explain why I cannot use pointers and I need access to variable by name. Basically the structure contains the state of a system. This systems needs to "undo" its state when requested. Undo is handled using an interface called undo\_token like this: ``` class undo_token { public: void undo(my_struct* s) = 0; }; ``` So I cannot pass pointers to the undo method because of polymorphism (mystruct contains variables of other types as well). When I add a new variable to the structure I generally also add a new class, like this: ``` class undo_a : public undo_token { int new_value; public: undo_a(int new_value) { this->new_value = new_value; } void undo(my_struct *s) { s->a = new_value} }; ``` Problem is I don't know pointer to s when I create the token, so I cannot save a pointer to s::a in the constructor (which would have solved the problem). The class for "b" is the same, just I have to write "s->b" instead of s->a Maybe this is a design problem: I need an undo token per variable type, not one per variable...
``` #include <iostream> #include <ostream> #include <string> struct my_struct { int a; std::string b; }; template <typename TObject, typename TMember, typename TValue> void set( TObject* object, TMember member, TValue value ) { ( *object ).*member = value; } class undo_token {}; template <class TValue> class undo_member : public undo_token { TValue new_value_; typedef TValue my_struct::* TMember; TMember member_; public: undo_member(TMember member, TValue new_value): new_value_( new_value ), member_( member ) {} void undo(my_struct *s) { set( s, member_, new_value_ ); } }; int main() { my_struct s; set( &s, &my_struct::a, 2 ); set( &s, &my_struct::b, "hello" ); std::cout << "s.a = " << s.a << std::endl; std::cout << "s.b = " << s.b << std::endl; undo_member<int> um1( &my_struct::a, 4 ); um1.undo( &s ); std::cout << "s.a = " << s.a << std::endl; undo_member<std::string> um2( &my_struct::b, "goodbye" ); um2.undo( &s ); std::cout << "s.b = " << s.b << std::endl; return 0; } ```
To answer the exact question, there is, but it's pretty complicated, and it will purely be a compile-time thing. (If you need runtime lookup, use a pointer-to-member - and based on your updated question, you may have misunderstood how they work.) First, you need something you can use to represent the "name of a member" at compile time. In compile-time metaprogramming, everything apart from integers has to be represented by types. So you'll use a type to represent a member. For example, a member of type integer that stores a person's age, and another for storing their last name: ``` struct age { typedef int value_type; }; struct last_name { typedef std::string value_type; }; ``` Then you need something like a `map` that does lookup at compile time. Let's called it `ctmap`. Let's give it support for up to 8 members. Firstly we need a placeholder to represent the absence of a field: ``` struct none { struct value_type {}; }; ``` Then we can forward-declare the shape of `ctmap`: ``` template < class T0 = none, class T1 = none, class T2 = none, class T3 = none, class T4 = none, class T5 = none, class T6 = none, class T7 = none > struct ctmap; ``` We then specialise this for the case where there are no fields: ``` template <> struct ctmap< none, none, none, none, none, none, none, none > { void operator[](const int &) {}; }; ``` The reason for this will be come clear (possibly) in a moment. Finally, the definition for all other cases: ``` template < class T0, class T1, class T2, class T3, class T4, class T5, class T6, class T7 > struct ctmap : public ctmap<T1, T2, T3, T4, T5, T6, T7, none> { typedef ctmap<T1, T2, T3, T4, T5, T6, T7, none> base_type; using base_type::operator[]; typename T0::value_type storage; typename T0::value_type &operator[](const T0 &c) { return storage; } }; ``` What the hell's going on here? If you put: ``` ctmap<last_name, age> person; ``` C++ will build a type for `person` by recursively expanding the templates, because `ctmap` *inherits from itself*, and we provide storage for the first field and then discard it when we inherit. This all comes to a sudden stop when there are no more fields, because the specialization for all-`none` kicks in. So we can say: ``` person[last_name()] = "Smith"; person[age()] = 104; ``` It's like looking up in a `map`, but at compile time, using a field-naming class as the key. This means we can also do this: ``` template <class TMember> void print_member(ctmap<last_name, age> &person) { std::cout << person[TMember()] << std::endl; } ``` That's a function that prints one member's value, where the member to be printed is a type parameter. So we can call it like this: ``` print_member<age>(person); ``` So yes, you can write a thing that is a little like a `struct`, a little like a compile-time `map`.
Can templates be used to access struct variables by name?
[ "", "c++", "templates", "" ]
We have `Request.UserHostAddress` to get the IP address in ASP.NET, but this is usually the user's ISP's IP address, not exactly the user's machine IP address who for example clicked a link. How can I get the real IP Address? For example, in a Stack Overflow user profile it is: **"Last account activity: 4 hours ago from 86.123.127.8"**, but my machine IP address is a bit different. How does Stack Overflow get this address? In some web systems there is an IP address check for some purposes. For example, with a certain IP address, for every 24 hours can the user just have only 5 clicks on download links? This IP address should be unique, not for an ISP that has a huge range of clients or Internet users. Did I understand well?
As others have said you can't do what you are asking. If you describe the problem you are trying to solve maybe someone can help? E.g. * are you trying to uniquely identify your users? * Could you use a cookie, or the session ID perhaps instead of the IP address? **Edit** The address you see on the server shouldn't be the ISP's address, as you say that would be a huge range. The address for a home user on broadband will be the address at their router, so every device inside the house will appear on the outside to be the same, but the router uses NAT to ensure that traffic is routed to each device correctly. For users accessing from an office environment the address may well be the same for all users. Sites that use IP address for ID run the risk of getting it very wrong - the examples you give are good ones and they often fail. For example my office is in the UK, the breakout point (where I "appear" to be on the internet) is in another country where our main IT facility is, so from my office my IP address appears to be not in the UK. For this reason I can't access UK only web content, such as the BBC iPlayer). At any given time there would be hundreds, or even thousands, of people at my company who appear to be accessing the web from the same IP address. When you are writing server code you can never be sure what the IP address you see is referring to. Some users like it this way. Some people deliberately use a proxy or VPN to further confound you. When you say your machine address is different to the IP address shown on StackOverflow, how are you finding out your machine address? If you are just looking locally using `ipconfig` or something like that I would expect it to be different for the reasons I outlined above. If you want to double check what the outside world thinks have a look at [whatismyipaddress.com/](http://whatismyipaddress.com/). This [Wikipedia link on NAT](http://en.wikipedia.org/wiki/Network_address_translation) will provide you some background on this.
Often you will want to know the IP address of someone visiting your website. While ASP.NET has several ways to do this one of the best ways we've seen is by using the "HTTP\_X\_FORWARDED\_FOR" of the ServerVariables collection. Here's why... Sometimes your visitors are behind either a proxy server or a router and the standard `Request.UserHostAddress` only captures the IP address of the proxy server or router. When this is the case the user's IP address is then stored in the server variable ("HTTP\_X\_FORWARDED\_FOR"). So what we want to do is first check "HTTP\_X\_FORWARDED\_FOR" and if that is empty we then simply return `ServerVariables("REMOTE_ADDR")`. While this method is not foolproof, it can lead to better results. Below is the ASP.NET code in VB.NET, taken from [James Crowley's blog post "Gotcha: HTTP\_X\_FORWARDED\_FOR returns multiple IP addresses"](http://www.jamescrowley.co.uk/2007/06/19/gotcha-http-x-forwarded-for-returns-multiple-ip-addresses/) **C#** ``` protected string GetIPAddress() { System.Web.HttpContext context = System.Web.HttpContext.Current; string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; if (!string.IsNullOrEmpty(ipAddress)) { string[] addresses = ipAddress.Split(','); if (addresses.Length != 0) { return addresses[0]; } } return context.Request.ServerVariables["REMOTE_ADDR"]; } ``` **VB.NET** ``` Public Shared Function GetIPAddress() As String Dim context As System.Web.HttpContext = System.Web.HttpContext.Current Dim sIPAddress As String = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR") If String.IsNullOrEmpty(sIPAddress) Then Return context.Request.ServerVariables("REMOTE_ADDR") Else Dim ipArray As String() = sIPAddress.Split(New [Char]() {","c}) Return ipArray(0) End If End Function ```
How to get a user's client IP address in ASP.NET?
[ "", "c#", "asp.net", "client", "ip-address", "" ]
I have a base class Foo that is concrete and contains 30 methods which are relevant to its subclasses. Now I've come across a situation that is specific only to the base class,and I want to create a method that cannot be inherited, is this possible? ``` Class Foo { /* ... inheritable methods ... */ /* non-inheritable method */ public bool FooSpecificMethod() { return true; } } Class Bar : Foo { /* Bar specific methods */ } var bar = new Bar(); bar.FooSpecificMethod(); /* is there any way to get this to throw compiler error */ ``` **EDIT** I'm not sure if I was clear originally. I do understand the principles of inheritance, and I understand the Liskov substitution principle. In this case there is a single exception that ONLY deals with the 'un-inherited' case, and so I did not want to create an 'uninheritedFoo' subclass. I was asking if it is technically possible to create a situation where foo.FooSpecificMethod() is a valid and publicly accessible method, but subclassoffoo.FooSpecificMethod() throws a compiler error. Essentially I want a sealed method on an unsealed class.
I would rethink the need for this. If you are using inheritance, you are suggesting that "Bar" IS A "Foo". If "Bar" is always a "Foo", methods that work on "Foo" should also work on "Bar". If this isn't the case, I would rework this as a private method. Publically, Bar should always be a Foo. --- Just to take this one step further - If you could do this, things would get very complicated. You could have situations where: ``` Foo myBar = new Bar(); // This is legal myBar.FooSpecificMethod(); // What should this do? // It's declared a Foo, but is acutally a Bar ``` You can actually force this behavior using reflection, though. I think it's a bad idea, but FooSpecificMethod() could check the type of this, and if it isn't typeof(Foo), throw an exception. This would be very confusing, and have a very bad smell. --- Edit in response to question's edit: There is no way for the compiler to enforce what you are asking. If you really want to force the compiler to check this, and prevent this, you really should consider making Foo a sealed class. You could use other extension methods than subclassing in this case. For example, you might want to consider using events or delegates to extend the behavior instead of allowing the object to be subclasses. Trying to do what you are accomplishing is basically trying to prevent the main goals of inheritance.
Brian's right about Liskov Substitution (upmodded). And Reed's right about "is-a" (also upmodded); in fact they're both telling you the same thing. Your public methods are a *contract* with users of your class Foo, saying that, "you can always" call those methods on Foo. Subclassing Foo means that you're saying that a Subclass, e.g. Bar, is always acceptable to use where a Foo could be used. In particular, it means you inherit not (necessarily) Foo's implementation (you can override that, or Foo may be abstract and give no particular implementation for a method). Inheritance of implementation (if any) is a detail; what you're *really inheriting* is the public interface, the contract, the *promise* to users that a Bar can be used like a Foo. Indeed, they may never even know they have a Bar, not a Foo: if I make a FooFactory, and I write its Foo\* getAFoo() to return a pointer to a Bar, they may never know, *and sholdn't have to*. When you break that contract, you break Object Orientation. (And the Java Collection classes, by throwing NotSupported exceptions, entirely break OO -- users can no longer use so-called subclasses polymorphically. That's poor, poor design, which has caused major headaches for many many Java users, *not* something to emulate.) If there's a public method that Foo subclasses can't use, then that method shouldn't be in Foo, it should be in a Foo subclass, and the other subclasses should derive from Foo. Now, that does NOT mean that all methods in Foo should be callable on subclasses. No, I'm not contradicting myself. *Non-public* methods are not part of a class's public interface. If you want a method in Foo that can't be called on Bar, *and* shouldn't be publicly callable in Foo, then make that method private or protected.
Preventing methods from being inherited
[ "", "c#", "inheritance-prevention", "" ]
I have a mock up of a sql query that will represent a real sql query. ``` Create table #tmp ( Atype varchar(10), Btype varchar(10) ) insert into #tmp values ('a','x') insert into #tmp values ('b','x') insert into #tmp values ('a','y') insert into #tmp values ('a','y') insert into #tmp values ('b','z') insert into #tmp values ('b','y') select atype, btype,count(*) as count from #tmp group by atype, btype order by atype drop table #tmp ``` This will give me the result of: ``` atype btype count ----------------- a x 1 a y 2 b x 1 b y 1 b z 1 ``` What i am looking for after this is to be able to create a report that basically looks like: ``` atype|x| y| z ------------- a |1| 2| 0 b |1| 1| 1 ``` I am sure you can do this using come crazy t-sql code but i am struggeling to get it right. EDIT: I agree that you can use the TSQL PIVOT command but what happens when Btype is variable. Meaning that i dont know how many types there will be?
``` SELECT atype, SUM(CASE btype WHEN 'x' THEN 1 ELSE 0 END) AS x, SUM(CASE btype WHEN 'y' THEN 1 ELSE 0 END) AS y, SUM(CASE btype WHEN 'z' THEN 1 ELSE 0 END) AS z FROM #tmp group by atype order by atype ```
`@Tomalak`'s answer is nice, but there's nothing crazy about it, just plain old `SQL`. Here's the really crazy `T-SQL` code you asked for, in case you were interested: ``` SELECT atype, [x], [y], [z] FROM ( SELECT atype, btype FROM #tmp ) t PIVOT ( COUNT(btype) FOR btype IN ([x], [y], [z]) ) AS PivotTable ```
SQL Query - Along the lines of a pivot table
[ "", "sql", "pivot-table", "" ]
* linux: `$HOME/.config` * windows: `%APPDATA%` * mac os: `$HOME/.config` It can be set using <http://qt-project.org/doc/qt-4.8/qsettings.html#setPath>, but it seems as I am not able to retrieve it. <http://qt-project.org/doc/qt-4.8/qlibraryinfo.html#location> `QLibraryInfo::LibrariesPath` returns the system wide settings dir, which is not what I want. Any ideas, or do I have to code it separately for each platform? €: I want to create a sub directory, and store files into it. (You may punish me if this is a bad idea)
This might not answer your question directly: if you want to store per-user persistent data, shouldn't you use [QDesktopServices::storageLocation(QDesktopServices::DataLocation)](http://qt-project.org/doc/qt-4.8/qdesktopservices.html#storageLocation) instead?
This is a nasty workaround. First you create `QSettings`, then get its location. ``` QSettings cfg(QSettings::IniFormat, QSettings::UserScope, "organization", "application"); QString config_dir = QFileInfo(cfg.fileName()).absolutePath() + "/"; ``` Credits go to the Qt Centre forum. `QSettings` stores the default config in the user AppData directory. See documentation for [`QSettings`](http://qt-project.org/doc/qt-4.8/qsettings.html). Also this code instructs to store the config in the Ini file format.
Qt4.4 how to get the user settings path
[ "", "c++", "qt", "" ]