Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm trying to figure out how to properly serialize my XmlDocument and send it via a HTTPWebRequest object.
Here's what I have thus far:
```
Stream requestStream;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wwwcie.ups.com/ups.app/xml/Track");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
requestStream = request.GetRequestStream();
XmlSerializerNamespaces xsm = new XmlSerializerNamespaces();
xsm.Add("", ""); // remove namespace
XmlSerializer ser = new XmlSerializer(xmlRequest.GetType());
ser.Serialize(requestStream, xmlRequest);
requestStream.Write(postData, 0, postData.Length);
requestStream.Close();
```
A few things I'm uncertain about. I have 2 XmlDocuments I need to send in the same HTTPWebRequest. I've tried before to convert the XmlDocuments to strings and just concatenate them (to send the string) but when I used the StringBuilder / Writer it adds:
```
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://myNameSpace/">
```
I already have the declaration in my XmlDocument objects so now its in there twice, and I cannot have the `<string...` part in there. Is it easier to convert the XmlDocuments to strings then concatenate them and send that or is there a easy way to send the XmlDocuments as they are?
**Edit:**
See [C# XmlDocument Nodes](https://stackoverflow.com/questions/1104549/c-xmldocument-nodes)
When I try to convert one of my XmlDocuments to a string it shows up as
```
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://myNamespace/">
<TrackRequest>
<Request>
<TransactionReference>
<CustomerContext>whatever</CustomerContext>
</TransactionReference>
</Request>
<TrackingNumber>123</TrackingNumber>
</TrackRequest>
</string>
```
I want my root to be `<TrackRequest>` | I'm guessing this question is related to the previous one about 2 xml documents not being able to be combined into one document without wrapping them both in a root node first ([C# XmlDocument Nodes](https://stackoverflow.com/questions/1104549/c-xmldocument-nodes/1104586#1104586)).
If that is the case then you don't want to be serialising the XmlDocuments and sending them to the WebService. Serializing the objects is for transporting/storing the actual object, not the data. You want to just send the webservice the data not the object so just concatenate the two xml documents and send that.
```
use XmlDocument.OuterXml to get the XmlDocument as a string. ie:
XmlDocument doc1 = new XmlDocument();
doc.LoadXml("Some XML");
XmlDocument doc2 = new XmlDocument();
doc2.LoadXml("Some other XML");
StringBuilder sb = new StringBuilder();
sb.Append(doc1.OuterXml);
sb.Append(doc2.OuterXml);
```
The just send sb.ToString() to the WebService.
Hope I haven't got completely the wrong end of the stick. | Works (somewhat)! Thanks, heres the code:
```
Stream requestStream;
Stream responseStream;
WebResponse response;
StreamReader sr;
byte[] postData;
string postString;
postString = xmlAccess.OuterXml + xmlRequest.OuterXml;
postData = Encoding.UTF8.GetBytes(postString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://wwwcie.ups.com/ups.app/xml/Track");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
requestStream = request.GetRequestStream();
requestStream.Write(postData, 0, postData.Length);
requestStream.Close();
response = request.GetResponse();
responseStream = response.GetResponseStream();
sr = new StreamReader(responseStream);
return sr.ReadToEnd();
```
It still doesnt return proper XML though:
```
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://namespace/"><?xml version="1.0" ?> <TrackResponse><Response><...
```
Not sure why there's 2x `<?xml version...` | Serialize XmlDocument & send via HTTPWebRequest | [
"",
"c#",
".net",
"httpwebrequest",
"xmldocument",
""
] |
What is the code required to redirect the browser to a new page with an ASPX page?
I have tried this on my page default.aspx :
```
<% Response.Redirect("new.aspx", true); %>
```
or
```
<%@ Response.Redirect("new.aspx", true); %>
```
And these resulted in a server error that is undetermined. I cannot see the error code; because the server is not in my control and the errors are not public.
Please provide all necessary code from line 1 of the page to the end, and I would really appreciate it. | ```
<%@ Page Language="C#" %>
<script runat="server">
protected override void OnLoad(EventArgs e)
{
Response.Redirect("new.aspx");
}
</script>
``` | You could also do this is plain in html with a [meta tag](http://en.wikipedia.org/wiki/Meta_refresh):
```
<html>
<head>
<meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>
``` | aspx page to redirect to a new page | [
"",
"c#",
"asp.net",
"redirect",
""
] |
Galileo came out the other day, and even though plugins under Eclipse are, IMO, just a little bit easier to deal with than [Netbeans](https://stackoverflow.com/questions/1059725/a-new-version-of-netbeans-just-came-out-is-there-anything-i-can-do-to-avoid-hav), it would still be really awesome if there was a simple way for me to upgrade to the new version (and take my plugins with me).
Any tips? | Not directly, AFAIK.
Here is the closest thing I came up with, under the assumption that my old Eclipse is recent enough so that it uses a similar form of update manager (P2).
In the old Eclipse, go to preferences->Install/Update->Available Software Sites.
Pick the ones that are not built in (you will see a name for them, or at least a non-eclipse URL). You can select the ones you want and then export them to XML.
Now go to the new Eclipse, go to the same preference window, and import the update sites from the XML. Now, when you install new software, you should see your update sites although you will probably still have to manually pick options for plugins that offer multiple downloads.
Important caveat: Some plugin vendors actually offer different update sites for different Eclipse versions, so you would still be pointing at the old plugin. This would typically happen if you never updated your existing plugin to a new version. One common example of this is with Subsclipse, so you may want to manually upgrade that one. | Take a look into this blog entry: [How to make your Eclipse plugin list survive an Eclipse upgrade](http://rachaelandtom.info/content/how-make-your-eclipse-plugin-list-survive-eclipse-upgrade)
I also used the [Yoxos](http://ondemand.yoxos.com/geteclipse/start) service to build my "own" Eclipse distribution. I guess it should be easy possible to just upgrade the core elements in such a profile, keeping the plugins. It has included dependency checking, so it's very nice to get a distribution running. | A new version of Eclipse just came out. Is there anything I can do to avoid having to manually hunt down my plugins again? | [
"",
"java",
"eclipse",
"eclipse-3.4",
"eclipse-3.5",
""
] |
How do u backup SQL Server db with C# 3.0 ? | You don't - C# is a programming language and as such is unsuitable for database maintenance. The *.NET Framework* has an API that will allow you to work with a SQL Server database but even this is not the best way to do database maintenance.
SQL Server has a rich array of tools that can be used for backing up a database. Please see these links for more information:
* [Backup Overview (SQL Server)](http://msdn.microsoft.com/en-us/library/ms175477.aspx)
* [How to: Back Up a Database (SQL Server Management Studio)](http://msdn.microsoft.com/en-us/library/ms187510.aspx) | You can use SQL SMO to backup the database and perform other SQL functions through c#.
<http://msdn.microsoft.com/en-us/library/ms162169.aspx> | Backup SQL DATABASE with C# 3.0 | [
"",
"c#",
"sql-server",
""
] |
I'm looking for a tool that that I can use to clean up (formatting, tabs, etc.) my stored procedures and views. Is there anything like [HTML Tidy](https://en.wikipedia.org/wiki/HTML_Tidy), but for SQL which is free/open source? | Two options that seem to be missing, and I think are both more appropriate than most options listed so far:
* [Poor Man's T-SQL Formatter](http://www.architectshack.com/PoorMansTSqlFormatter.ashx) / [poorsql.com](http://poorsql.com/) (free, open-source, SSMS add-in, command line formatter, full [DDL](https://en.wikipedia.org/wiki/Data_definition_language)/[DML](https://en.wikipedia.org/wiki/Data_manipulation_language) script formatting, and I'm the author/maintainer, so I get to put it first :))
* [T-SQL Tidy](http://tsqltidy.com.serv6.temphostspace.com/downloads.aspx) (free, SSMS Add-In, full DDL/DML script formatting, apparently an [SQL Server 2008 R2](https://en.wikipedia.org/wiki/History_of_Microsoft_SQL_Server#SQL_Server_2008_R2) add-in can do offline formatting also now - but not open-source?)
I believe either of these makes more sense than any of the previous answers because the other options provided are:
* Online-only (instant SQL formatter)
* Trialware / commercial software (SQL pretty printer)
* Don't format (SSMS tools pack, the accepted answer)
* Don't handle full T-SQL properly ([CPAN](https://en.wikipedia.org/wiki/CPAN) module, SQL-talk prettifier)
* Incomplete, only handle some statements (SqlFormat project) | [ssmstools](http://www.ssmstoolspack.com/) is useful | Is there a Tidy for SQL? | [
"",
"sql",
"sql-server",
"formatting",
"ssms",
""
] |
I know how to do it in code, but can this be done in XAML ?
Window1.xaml:
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<ComboBox Name="ComboBox1" HorizontalAlignment="Left" VerticalAlignment="Top">
<ComboBoxItem>ComboBoxItem1</ComboBoxItem>
<ComboBoxItem>ComboBoxItem2</ComboBoxItem>
</ComboBox>
</Grid>
</Window>
```
Window1.xaml.cs:
```
using System.Windows;
using System.Windows.Controls;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
double width = 0;
foreach (ComboBoxItem item in ComboBox1.Items)
{
item.Measure(new Size(
double.PositiveInfinity, double.PositiveInfinity));
if (item.DesiredSize.Width > width)
width = item.DesiredSize.Width;
}
ComboBox1.Measure(new Size(
double.PositiveInfinity, double.PositiveInfinity));
ComboBox1.Width = ComboBox1.DesiredSize.Width + width;
}
}
}
``` | This can't be in XAML without either:
* Creating a hidden control (Alan Hunford's answer)
* Changing the ControlTemplate drastically. Even in this case, a hidden version of an ItemsPresenter may need to be created.
The reason for this is that the default ComboBox ControlTemplates that I've come across (Aero, Luna, etc.) all nest the ItemsPresenter in a Popup. This means that the layout of these items is deferred until they are actually made visible.
An easy way to test this is to modify the default ControlTemplate to bind the MinWidth of the outermost container (it's a Grid for both Aero and Luna) to the ActualWidth of PART\_Popup. You'll be able to have the ComboBox automatically synchronize it's width when you click the drop button, but not before.
So unless you can force a Measure operation in the layout system (which you **can** do by adding a second control), I don't think it can be done.
As always, I'm open to an short, elegant solution -- but in this case a code-behind or dual-control/ControlTemplate hacks are the only solutions I have seen. | You can't do it directly in Xaml but you can use this Attached Behavior. (The Width will be visible in the Designer)
```
<ComboBox behaviors:ComboBoxWidthFromItemsBehavior.ComboBoxWidthFromItems="True">
<ComboBoxItem Content="Short"/>
<ComboBoxItem Content="Medium Long"/>
<ComboBoxItem Content="Min"/>
</ComboBox>
```
The Attached Behavior ComboBoxWidthFromItemsProperty
```
public static class ComboBoxWidthFromItemsBehavior
{
public static readonly DependencyProperty ComboBoxWidthFromItemsProperty =
DependencyProperty.RegisterAttached
(
"ComboBoxWidthFromItems",
typeof(bool),
typeof(ComboBoxWidthFromItemsBehavior),
new UIPropertyMetadata(false, OnComboBoxWidthFromItemsPropertyChanged)
);
public static bool GetComboBoxWidthFromItems(DependencyObject obj)
{
return (bool)obj.GetValue(ComboBoxWidthFromItemsProperty);
}
public static void SetComboBoxWidthFromItems(DependencyObject obj, bool value)
{
obj.SetValue(ComboBoxWidthFromItemsProperty, value);
}
private static void OnComboBoxWidthFromItemsPropertyChanged(DependencyObject dpo,
DependencyPropertyChangedEventArgs e)
{
ComboBox comboBox = dpo as ComboBox;
if (comboBox != null)
{
if ((bool)e.NewValue == true)
{
comboBox.Loaded += OnComboBoxLoaded;
}
else
{
comboBox.Loaded -= OnComboBoxLoaded;
}
}
}
private static void OnComboBoxLoaded(object sender, RoutedEventArgs e)
{
ComboBox comboBox = sender as ComboBox;
Action action = () => { comboBox.SetWidthFromItems(); };
comboBox.Dispatcher.BeginInvoke(action, DispatcherPriority.ContextIdle);
}
}
```
What it does is that it calls an extension method for ComboBox called SetWidthFromItems which (invisibly) expands and collapses itself and then calculates the Width based on the generated ComboBoxItems. (IExpandCollapseProvider requires a reference to UIAutomationProvider.dll)
Then extension method SetWidthFromItems
```
public static class ComboBoxExtensionMethods
{
public static void SetWidthFromItems(this ComboBox comboBox)
{
double comboBoxWidth = 19;// comboBox.DesiredSize.Width;
// Create the peer and provider to expand the comboBox in code behind.
ComboBoxAutomationPeer peer = new ComboBoxAutomationPeer(comboBox);
IExpandCollapseProvider provider = (IExpandCollapseProvider)peer.GetPattern(PatternInterface.ExpandCollapse);
EventHandler eventHandler = null;
eventHandler = new EventHandler(delegate
{
if (comboBox.IsDropDownOpen &&
comboBox.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
double width = 0;
foreach (var item in comboBox.Items)
{
ComboBoxItem comboBoxItem = comboBox.ItemContainerGenerator.ContainerFromItem(item) as ComboBoxItem;
comboBoxItem.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (comboBoxItem.DesiredSize.Width > width)
{
width = comboBoxItem.DesiredSize.Width;
}
}
comboBox.Width = comboBoxWidth + width;
// Remove the event handler.
comboBox.ItemContainerGenerator.StatusChanged -= eventHandler;
comboBox.DropDownOpened -= eventHandler;
provider.Collapse();
}
});
comboBox.ItemContainerGenerator.StatusChanged += eventHandler;
comboBox.DropDownOpened += eventHandler;
// Expand the comboBox to generate all its ComboBoxItem's.
provider.Expand();
}
}
```
This extension method also provides to ability to call
```
comboBox.SetWidthFromItems();
```
in code behind (e.g in the ComboBox.Loaded event) | How can I make a WPF combo box have the width of its widest element in XAML? | [
"",
"c#",
"wpf",
"combobox",
""
] |
I have the following code for creating tabs. It works at the end of the html body section but not if I place it at the beginning - before all of the divs are defined. Why might that be?
```
<script type="text/javascript">
$("ul.tabs li.label").hide();
$("#tab-set > div").hide();
$("#tab-set > div").eq(0).show();
$("ul.tabs a").click(
function() {
$("ul.tabs a.selected").removeClass('selected');
$("#tab-set > div").hide();
$(""+$(this).attr("href")).show();
$(this).addClass('selected');
return false;
}
);
$("#toggle-label").click( function() {
$(".tabs li.label").toggle();
return false;
});
</script>
``` | you need to wrap it with a document ready block. this prevents the code firing until the page is fully loaded.
```
<script type="text/javascript">
$(function() {
// do something on document ready
$("ul.tabs li.label").hide();
$("#tab-set > div").hide();
$("#tab-set > div").eq(0).show();
$("ul.tabs a").click(
function() {
$("ul.tabs a.selected").removeClass('selected');
$("#tab-set > div").hide();
$(""+$(this).attr("href")).show();
$(this).addClass('selected');
return false;
}
);
$("#toggle-label").click( function() {
$(".tabs li.label").toggle();
return false;
});
});
</script>
``` | It is most likely because the DOM is not ready yet, and therefore they don't exist.
Therefore you need to do the following:
```
$(function() {
// Any code in here will only be executed when the DOM is ready.
});
``` | Why does some jquery code only work if it's at the end of my html-body section? | [
"",
"javascript",
"jquery",
"document",
"position",
""
] |
The code below has a repeating background image "thinline.png". On top of that are 4 layered transparent PNGs: cardshadow.png, steel.png, startjobapplicationshadow.png and startapplication.png
My goal is to make this code look good in IE6 without messing up other browsers. This feature of IE is widely documented but I have not been able to get it working. Please give me some ideas or examples to help me solve this.
Thanks.
Mike
The Code:
```
<div style="height: 333px; width: 100%; position: absolute; top: 68px; background-image:url(Resources/thinline.png); background-repeat:repeat-x; ">
<div style="position: absolute; height: 300px; width: 215px; top: 15px; right: 50%; margin-right: -390px; z-index: 2; ">
<img src="Resources/steel.png" style="position: absolute; top: 0px; z-index: 3;"/>
<img src="Resources/cardshadow.png" style="position: absolute; top: 0px; margin-top: -8px; margin-left: -10px; z-index: 2">
<img src="Resources/startjobapplication.png" style="margin-left: -65px; position: relative; top: 258px; left: 50%; z-index: 5; display: block;"/>
<img src="Resources/startjobapplicationshadow.png" style="margin-left: -67px; margin-top: -20px; position: relative; top: 258px; left: 50%; z-index: 4; display: block;"/>
``` | Use [DD\_belatedPNG](http://www.dillerdesign.com/experiment/DD_belatedPNG/). | Take a look at [IE7](http://dean.edwards.name/IE7/) by Dean Edwards. It's a javascript library for Internet Explorer 6 that makes transparent pngs work correctly, as well as fixing css bugs and adding support for additional css features. I've used this library in the past with some success (It's easier than adding IE-specific css hacks.). However, the page may briefly look incorrect while loading. | How should I use transparent pngs in IE 6 over a background-repeat? | [
"",
"javascript",
"html",
"css",
"internet-explorer",
"png",
""
] |
I saw a java function that looked something like this-
```
public static<T> foo() {...}
```
I know what generics are but can someone explain the in this context? Who decides what T is equal to? Whats going on here?
EDIT: Can someone please show me an example of a function like this. | You've missed the return type out, but apart from that it's a generic method. As with generic types, `T` stands in for any reference type (within bounds if given).
For methods, generic parameters are typically inferred by the compiler. In certain situations you might want to specify the generic arguments yourself, using a slightly peculiar syntax:
```
List<String> strings = Collections.<String>emptyList();
```
In this case, the compiler could have inferred the type, but it's not always obvious whether the compiler can or can't. Note, the `<>` is after the dot. For syntactical reasons the type name or target object must always be specified.
It's possible to have generic constructors, but I've never seen one in the wild and the syntax gets worse.
I believe C++ and C# syntaxes place the generic types after the method/function name. | The context is a generic method as opposed to a class. The variable `<T>` applies only to the call of the method.. The Collections class has a number of these; the class itself is not generic, but many of the methods are.
The compiler decides what T is equal to -- it equals whatever gets the types to work. Sometimes this is easier then others.
For example, the method `static <T> Set<T> Collections.singleton(T o)` the type is defined in the parameter:
```
Collections.singleton(String T)
```
will return a `Set<String>`.
Sometimes the type is hard to define. For example sometimes there is not easily enough information to type `Collection.emptyList()`. In that case you can specify the type directly: `Collection.<String>emptyList()`. | Java : What is - public static<T> foo() {...}? | [
"",
"java",
"generics",
"static-methods",
""
] |
I want to union the result of two sub-queries (say SUB1 and SUB2). The sub-queries have multiple columns including an ID column.
If an ID=1 exists in SUB1, I want the union result to include only the row of ID=1 from SUB1 and not include the ID=1 row from SUB2.
eg. if SUB1 had the following columns and rows
```
ID | Date
1 | 7/1
2 | 7/3
```
And SUB2 had the following:
```
ID | Date
1 | 7/4
3 | 7/8
```
I would like the union result to be
```
ID | Date
1 | 7/1
2 | 7/3
3 | 7/8
```
The only way I can think of is to do something like
```
SELECT * FROM (SUB1)
UNION
SELECT * FROM (SUB2)
WHERE ID NOT IN
(SELECT ID FROM (SUB1) )
```
My only concern is that SUB1 and SUB2 are long queries. I would like to avoid pasting SUB1 twice in my query.
Is there a more concise way? Thanks | ```
SELECT COALESCE(sub1.id, sub2.id), COALESCE(sub1.date, sub2.date)
FROM sub1
FULL OUTER JOIN
sub2
ON sub1.id = sub2.id
``` | If using SQL Server 2005 or greater, a Common Table Expression will help with not typing the code twice:
```
; with CTE_Sub1 as (select * from (Sub1))
select * from CTE_Sub1
union
select * from (sub2)
where ID not in (select id from CTE_Sub1)
``` | SQL combining Union and Except | [
"",
"sql",
"sql-server",
""
] |
Is it possible to somehow do this without taking out the @? It does not like @
```
cJavaScript.AppendFormat(@"
function GetNextProductIDs(state)
{
var productIDs = new Array();
var {0}lastProductFoundIndex = $.inArray({0}lastProductID, {0}allProductIDs);
return productIDs.join();
}; ", ClientID);
``` | The problem is not with the @, but with the curly brace. Using two curly braces will escape them propertly.
```
cJavaScript.AppendFormat(@"
function GetNextProductIDs(state)
{{
var productIDs = new Array();
var {0}lastProductFoundIndex = $.inArray({0}lastProductID, {0}allProductIDs);
return productIDs.join();
}}; ", ClientID);
``` | I like to use use string.Concat or StringBuilder to append multi-line strings like this together. Usually I don't really care if the cr/lf's are in there, but you can adjust if you do:
```
string fmt = string.Concat(
"function GetNextProductIDs(state) ",
"{",
"var productIDs = new Array();"
...
);
cJavaScript.AppendFormat(fmt, ClientID);
``` | StringBuilder AppendFormat with @ | [
"",
"c#",
""
] |
I'm writing a jQuery function where I'd like to access both the native size of an image, and the size specified for it on the page. I'd like to set a variable for each.
How is that done? | # Modern browsers
When I wrote this answer back in 2009 the browser landscape was much different. Nowadays any reasonably modern browser supports [Pim Jager's suggestion](https://stackoverflow.com/a/1093414) using `img.naturalWidth` and `img.naturalHeight`. Have a look at his answer.
# Legacy answer compatible with super old browsers
```
// find the element
var img = $('#imageid');
/*
* create an offscreen image that isn't scaled
* but contains the same image.
* Because it's cached it should be instantly here.
*/
var theImage = new Image();
theImage.src = img.attr("src");
// you should check here if the image has finished loading
// this can be done with theImage.complete
alert("Width: " + theImage.width);
alert("Height: " + theImage.height);
``` | This should work:
```
var img = $('#imageid')[0]; //same as document.getElementById('imageid');
var width = img.naturalWidth;
var height = img.naturalHeight;
```
The naturalWidth and naturalHeight return the size of the image response, not the display size.
According to Josh' comment this is not supported cross browser, this might be correct, I tested this in FF3 | Can Javascript access native image size? | [
"",
"javascript",
"jquery",
"image",
"size",
""
] |
Given the below setup and code snippets, what reasons can you come up with for using one over the other? I have a couple arguments using either of them, but I am curious about what others think.
Setup
```
public class Foo
{
public void Bar()
{
}
}
```
Snippet One
```
var foo = new Foo();
foo.Bar();
```
Snippet Two
```
new Foo().Bar();
``` | The first version means you can examine `foo` in a debugger more easily before calling `Bar()`.
The first version also means you associate a name with the object (it's actually the name of variable of course, but there's clearly a mental association) which can be useful at times:
```
var customersWithBadDebt = (some big long expression)
customersWithBadDebt.HitWithBaseballBat();
```
is clearer than
```
(some big long expression).HitWithBaseballBat();
```
If neither of those reasons apply, feel free to go for the single line version of course. It's personal taste which is then applied to each specific context. | If you are not going to use the Foo instance for more than simply doing that call I would probably go for the second one, but I can't see that there should be any practical difference, unless the call happens extremely often (but that does not strike me as very likely with that construct). | Holding onto object references | [
"",
"c#",
"coding-style",
""
] |
I have a layered application with namespaces:
* `App.Core` - business layer logic services
* `App.Data` - data access layer store classes and data access objects
* `App.Web` - user interface layer
I also have business objects/DTOs. They reside in `App.Objects` namespace, but I dont like this naming convention. Why? Because this namespace will also have subnamespaces suffixed *Objects* like `App.Objects.KeywordObjects`. These subnamespaces can't be without the *Objects* suffix, because some of them will also contain classes with the same name (`App.Objects.KeywordObjects` will contain `Keyword` and `Keywords` classes).
I was thinking of changing `App.Objects` to something else. So I don't have duplicate "Objects" word. But I can't seem to find any usable word. And I don't want to use acronyms like DTO or BO.
How do you normally name your namespaces and what would you suggest I should use in this case. | Namespace depth should correlate to frequency of usage. Why not put them in `App`? If your application revolves around the business objects, it makes sense to keep them at or near the root.
For a practical comparison, for many business applications the business objects are analogous to keeping common types in System. They are pervasive. | I'm a fan of the guidelines in "Framework Design Guidelines" by Brad Abrams et Al, which would give you:
`YourCompany.BusinessArea` for your business objects and `YourCompany.BusinessArea.Web` for your web layer. I seem to remember there was also a guideline that an object shouldn't rely on a nested namespace (but you could rely on a parent namespace) | Common namespace naming suggestion | [
"",
"c#",
"naming-conventions",
"namespaces",
""
] |
I have a class called SynonymMapping which has a collection of values mapped as a CollectionOfElements
```
@Entity(name = "synonymmapping")
public class SynonymMapping {
@Id private String keyId;
//@CollectionOfElements(fetch = FetchType.EAGER)
@CollectionOfElements
@JoinTable(name="synonymmappingvalues", joinColumns={@JoinColumn(name="keyId")})
@Column(name="value", nullable=false)
@Sort(type=SortType.NATURAL)
private SortedSet<String> values;
public SynonymMapping() {
values = new TreeSet<String>();
}
public SynonymMapping(String key, SortedSet<String> values) {
this();
this.keyId = key;
this.values = values;
}
public String getKeyId() {
return keyId;
}
public Set<String> getValues() {
return values;
}
}
```
I have a test where I store two SynonymMapping objects to the database and then ask the database to return all saved SynonymMapping objects, expecting to receive the two objects I stored.
When I change the mapping of values to be eager (as shown in in the code by the commented out line) and run the test again, I receive four matches.
I have cleared out the database between runs and I can duplicate this problem swapping between eager and lazy.
I think it has to do with the joins that hibernate creates underneath but I can't find a definite answer online.
Can anyone tell me why an eager fetch is duplicating the objects?
Thanks. | It's generally not a good idea to enforce eager fetching in the mapping - it's better to specify eager joins in appropriate queries (unless you're 100% sure that under any and all circumstances your object won't make sense / be valid without that collection being populated).
The reason you're getting duplicates is because Hibernate internally joins your root and collection tables. Note that they really are duplicates, e.g. for 2 SynonymMappings with 3 collection elements each you would get 6 results (2x3), 3 copies of each SynonymMapping entity. So the easiest workaround is to wrap results in a Set thereby ensuring they're unique. | I stepped into the same problem - when you set the FetchType.EAGER for a @CollectionOfElements, the Hibernate tries to get everything in one shot, i.e. using one single query for each entry of element linked to a "master" object. This problem can be successfully solved at a cost of N+1 query, if you add the @Fetch (FetchMode.SELECT) annotation to your collection.
In my case I wanted to have a MediaObject entity with a collection of its metadata items (video codec, audio codec, sizes, etc.). The mapping for a metadataItems collection looks as follows:
```
@CollectionOfElements (targetElement = String.class, fetch = FetchType.EAGER)
@JoinTable(name = "mo_metadata_item", joinColumns = @JoinColumn(name = "media_object_id"))
@MapKey(columns = @Column(name = "name"))
@Column (name = "value")
@Fetch (FetchMode.SELECT)
private Map<String, String> metadataItems = new HashMap<String, String>();
``` | Hibernate CollectionOfElements EAGER fetch duplicates elements | [
"",
"java",
"hibernate",
"annotations",
""
] |
Having the following classes, in two different assemblies:
```
class Member
{
public string Label {get;set;}
// Lots of other fields...
public double Thickness {get;set;}
public double Width {get;set;}
public double Length {get;set;}
public double GetVolume ()
{
return Thickness * Width * Length;
}
// Other methods
}
class OtherMember
{
public string CompositeLabel {get;set;}
// Lots of other fields (not related to other class: Member)
public double Thickness {get;set;}
public double Width {get;set;}
public double Length {get;set;}
public double GetVolume ()
{
return Thickness * Width * Length;
}
// Other methods
}
```
I want to refactor the Thickness, Width, Length properties and the GetVolume method to another class (Dimensions?) as to DRY...
I could then have a field/property in those classes to give access to a Dimensions instance.
Is this a good way to go?
I've read succinctly about having interfaces instead of concrete classes, should I inherit from an interface?
Also, what about immutability?
I feel I'm often lost about getting my domain classes right. Does anyone have some advice on this? | I would agree that you should create a `Dimensions` class that has the `Thickness`, `Length`, `Width` properties, along with the `GetVolume()` method. You probably do NOT want to create a base class with these members and have `Member` and `OtherMember` inherit from it because `Member` and `OtherMember` have dimensions, they are not super classes of dimensions. I'll try to lay out some guidelines so you can make the best decision for your case below.
For the interface, it is possibly a good idea since there are multiple ways volume can be calculated.
```
public interface ISolid{
double Volume { get; }
}
public class Cylinder: ISolid{
public double Height { get; set; }
public double Radius { get; set; }
public double Volume {
get
{
return (2 * Math.Pi * Radius ^ 2) * Height;
}
}
}
public class Cube: ISolid{
public double Width { get; set; }
public double Height { get; set; }
public double Depth { get; set; }
public double Volume {
get
{
return Width * Height * Depth;
}
}
}
```
It isn't clear what Member and OtherMember are, they have labels and other things that may not be represented well by inheriting straight from these types defined above. Also, multiple inheritance can make things complicated. So you need to look at your own domain objects and ask yourself, is this class a superclass (inheritance) or does it just need to use the other class to define some characteristic of itself (composition)
```
public class SodaCan: Cylinder
{
public SodaCan(string brand)
{
Brand = brand;
IsFull = true;
Height = 5D;
Radius = 1.5D;
}
public string Brand { get; private set; }
public bool IsFull { get; set; }
}
```
or
```
public class SodaCan: BeverageHolder
{
public SodaCan(string brand)
{
Brand = brand;
IsFull = true;
Dimensions = new Cylinder { Height = 5D, Radius = 1.5D };
}
private ISolid Dimensions { get; set; }
public double Volume {
get {
return Dimensions.Volume;
}
}
}
```
If all of your objects volumes can be found by using the Lenth \* Height \* Thickness, then you probably don't need the interface. Interfaces are good when you might have a bunch of objects with the same behavior, but the behavior is performed different. For example the volume of a cylinder vs. the volume of a cube. It doesn't hurt to create an interface anyway, but in this case you might not need it. In terms of should you create a base class, or a class to encapsulate the common behavior and use composition, that depends on your Domain. The soda can could be a cylinder, or it could be a BeverageHolder. A box of wine could also be a beverage holder, and those are not both Cylinders, so you have to look at what else you might want to inherit from in your domain. | Since you have a lot of state and behavior in common I would recommend a base class. Try something like this:
```
class Member
{
public string Label { get; set; }
public double Thickness { get; set; }
public double Width { get; set; }
public double Length { get; set; }
public double GetVolume()
{
return Thickness * Width * Length;
}
}
class OtherMember : Member
{
public string CompositeLabel { get; set; }
}
```
And depending on what the `Label` property is for you have the option of making it virtual and override the implementation in the derived class:
```
class Member
{
public virtual string Label { get; set; }
public double Thickness { get; set; }
public double Width { get; set; }
public double Length { get; set; }
public double GetVolume()
{
return Thickness * Width * Length;
}
}
class OtherMember : Member
{
string label;
public override string Label
{
get { return this.label; }
set { this.label = value; }
}
}
``` | C#: How would you suggest to refactor these classes? (Interfaces, Aggregation or anything else) | [
"",
"c#",
"refactoring",
"interface",
"model",
""
] |
Is there any way to differentiate IE7 versus IE6 using PHP's get\_browser() function? | You can do so as such:
```
$browser = get_browser();
if($browser->browser == 'IE' && $browser->majorver == 6) {
echo "IE6";
} elseif($browser->browser == 'IE' && $browser->majorver == 7) {
echo "IE7";
}
```
A quick look to the official [`get_browser()`](http://www.php.net/manual/en/function.get-browser.php) documentation would of answered your question. **Always read the documentation before.** | I read that get\_browser() is a relatively slow function, so I was looking for something speedier. This code checks for MSIE 7.0, outputting "Otay!" if true. It's basically the same answer as the previous post, just more concise. Fairly straightforward if statement:
```
<?php
if(strpos($_SERVER['HTTP_USER_AGENT'],'MSIE 7.0'))
echo 'Otay!';
?>
``` | PHP get_browser: how to identify ie7 versus ie6? | [
"",
"php",
"internet-explorer",
"internet-explorer-6",
"internet-explorer-7",
"browser-detection",
""
] |
I have a process that interfaces with a library that launches another process. Occasionally this process gets stuck and my program blocks in a call to the library. I would like to detect when this has happened (which I am doing currently), and send a kill signal to all these hung processes that are a child of me.
I know the commands to kill the processes, but I am having trouble getting the pids of my children. Does anyone know of a way to do this? | ```
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp = popen("ps -C *YOUR PROGRAM NAME HERE* --format '%P %p'" , "r");
if (fp == NULL)
{
printf("ERROR!\n");
}
char parentID[256];
char processID[256];
while (fscanf(fp, "%s %s", parentID, processID) != EOF)
{
printf("PID: %s Parent: %s\n", processID, parentID);
// Check the parentID to see if it that of your process
}
pclose(fp);
return 1;
}
``` | This question is very similar to one asked the other day. I would suggest taking a look [here](https://stackoverflow.com/questions/1009552/how-to-find-all-child-processes) to see if the answers are satisfactory in your case. Basically you will probably have to read through /proc. | Getting the pid of my children using linux system calls in C++ | [
"",
"c++",
"linux",
""
] |
I have a web page that displays a list of documents stored on the web site. I need to add a link next to each document that can e-mail it. By that I mean **attach the entire document** to the e-mail.
When clicking the e-mail link, a 'New Message' window needs to display with:
* Subject line filled in with the title of the document (displayed on the web page)
* Contents of the document downloaded from the web site and added as an attachment
The mail client is Outlook. The server is SharePoint (ASP.NET) which contains web services that are able to download files. JavaScript and any JS library is available for use. I'm not able to deploy additional software to the client.
What are my options and are there any references that achieve this type of functionality? | An alternative might be to put a link in the body of the message to a place where the file can be downloaded. You could even make it a web page that deletes the file after a set time or number of downloads. To be safe you would need to use "mailto:someone@somewhere.com&subject=somesubject&body="+System.Web.HttpUtility.UrlEncode(bodyStringToEncode) to generate an html safe llink
Even with the above answer about launching an email using office automation, you'd still need to first have the file sent to the client, saved in a name and location known to the server, in order to attach the file. | I can't think of a way to attach the document but you can have a link to fill in the subject and body of an email in which you could add a link to the online document.
```
<a href="mailto:test@test.com?subject=
[your_subject]&body=[url_encoded_content_string]">New Message</a>
```
You can use this function to urlencode your body text <http://phpjs.org/functions/urlencode>
Hope that helps,
Josh | Send a file from a web page in Outlook | [
"",
"asp.net",
"javascript",
"windows",
"outlook",
""
] |
I need to find 2 elegant complete implementations of
```
public static DateTime AddBusinessDays(this DateTime date, int days)
{
// code here
}
and
public static int GetBusinessDays(this DateTime start, DateTime end)
{
// code here
}
```
O(1) preferable (no loops).
EDIT:
By business days i mean working days (Monday, Tuesday, Wednesday, Thursday, Friday). No holidays, just weekends excluded.
I already have some ugly solutions that seem to work but i wonder if there are elegant ways to do this. Thanks
---
This is what i've written so far. It works in all cases and does negatives too.
Still need a GetBusinessDays implementation
```
public static DateTime AddBusinessDays(this DateTime startDate,
int businessDays)
{
int direction = Math.Sign(businessDays);
if(direction == 1)
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(2);
businessDays = businessDays - 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
businessDays = businessDays - 1;
}
}
else
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(-1);
businessDays = businessDays + 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(-2);
businessDays = businessDays + 1;
}
}
int initialDayOfWeek = (int)startDate.DayOfWeek;
int weeksBase = Math.Abs(businessDays / 5);
int addDays = Math.Abs(businessDays % 5);
if((direction == 1 && addDays + initialDayOfWeek > 5) ||
(direction == -1 && addDays >= initialDayOfWeek))
{
addDays += 2;
}
int totalDays = (weeksBase * 7) + addDays;
return startDate.AddDays(totalDays * direction);
}
``` | Latest attempt for your first function:
```
public static DateTime AddBusinessDays(DateTime date, int days)
{
if (days < 0)
{
throw new ArgumentException("days cannot be negative", "days");
}
if (days == 0) return date;
if (date.DayOfWeek == DayOfWeek.Saturday)
{
date = date.AddDays(2);
days -= 1;
}
else if (date.DayOfWeek == DayOfWeek.Sunday)
{
date = date.AddDays(1);
days -= 1;
}
date = date.AddDays(days / 5 * 7);
int extraDays = days % 5;
if ((int)date.DayOfWeek + extraDays > 5)
{
extraDays += 2;
}
return date.AddDays(extraDays);
}
```
The second function, GetBusinessDays, can be implemented as follows:
```
public static int GetBusinessDays(DateTime start, DateTime end)
{
if (start.DayOfWeek == DayOfWeek.Saturday)
{
start = start.AddDays(2);
}
else if (start.DayOfWeek == DayOfWeek.Sunday)
{
start = start.AddDays(1);
}
if (end.DayOfWeek == DayOfWeek.Saturday)
{
end = end.AddDays(-1);
}
else if (end.DayOfWeek == DayOfWeek.Sunday)
{
end = end.AddDays(-2);
}
int diff = (int)end.Subtract(start).TotalDays;
int result = diff / 7 * 5 + diff % 7;
if (end.DayOfWeek < start.DayOfWeek)
{
return result - 2;
}
else{
return result;
}
}
``` | using [Fluent DateTime](https://github.com/FluentDateTime/FluentDateTime):
```
var now = DateTime.Now;
var dateTime1 = now.AddBusinessDays(3);
var dateTime2 = now.SubtractBusinessDays(5);
```
internal code is as follows
```
/// <summary>
/// Adds the given number of business days to the <see cref="DateTime"/>.
/// </summary>
/// <param name="current">The date to be changed.</param>
/// <param name="days">Number of business days to be added.</param>
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
public static DateTime AddBusinessDays(this DateTime current, int days)
{
var sign = Math.Sign(days);
var unsignedDays = Math.Abs(days);
for (var i = 0; i < unsignedDays; i++)
{
do
{
current = current.AddDays(sign);
}
while (current.DayOfWeek == DayOfWeek.Saturday ||
current.DayOfWeek == DayOfWeek.Sunday);
}
return current;
}
/// <summary>
/// Subtracts the given number of business days to the <see cref="DateTime"/>.
/// </summary>
/// <param name="current">The date to be changed.</param>
/// <param name="days">Number of business days to be subtracted.</param>
/// <returns>A <see cref="DateTime"/> increased by a given number of business days.</returns>
public static DateTime SubtractBusinessDays(this DateTime current, int days)
{
return AddBusinessDays(current, -days);
}
``` | AddBusinessDays and GetBusinessDays | [
"",
"c#",
".net",
""
] |
I have a textbox that I would like for only numbers. But if I hit the wrong number, I cant backspace to correct it. How can I allow backspaces to work. Thanks
```
private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsNumber(e.KeyChar) != true)
{
e.Handled = true;
}
}
``` | You could add a check to allow control characters as well:
```
if (Char.IsControl(e.KeyChar) != true && Char.IsNumber(e.KeyChar) != true)
{
e.Handled = true;
}
```
Update: in response to person-b's comment on the code s/he suggests the following style (which is also how I would personally write this):
```
if (!Char.IsControl(e.KeyChar) && !Char.IsNumber(e.KeyChar))
{
e.Handled = true;
}
``` | Correct answer is:
```
private void amount_PaidTextBox_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = !сhar.IsNumber(e.KeyChar) && (e.KeyChar != '\b');
}
``` | Masking a textbox for Numbers only but wont accept BackSpace | [
"",
"c#",
"winforms",
"masking",
""
] |
```
SELECT
(SELECT
IIF(IsNull(sum(b.AmountCharged) - sum(b.AmountPaid)),
a.Balance,
(sum(b.AmountCharged) - sum(b.AmountPaid)))
FROM tblCurrentTransaction AS b
WHERE b.TenantTransactionID <= a.TenantTransactionID
AND b.Tenant = a.Tenant
GROUP BY b.Tenant
) AS TrueBalance, a.TenantTransactionID
FROM tblCurrentTransaction AS a
ORDER BY a.Tenant, a.TenantTransactionID;
UNION
UPDATE tblCurrentTransaction SET tblCurrentTransaction.Balance = TrueBalance
WHERE tblCurrentTransaction.TenantTransactionID = a.TenantTransactionID;
```
Basically what happens is I get a result set from the first query, then I match it's TenantTransactionID with the update query. However Access complains: *"An action query cannot be used as a row source"*
How can I fix this?
This is the query without the UNION
```
UPDATE tblCurrentTransaction SET tblCurrentTransaction.Balance = (SELECT
(SELECT
IIF(IsNull(sum(b.AmountCharged) - sum(b.AmountPaid)),
a.Balance,
(sum(b.AmountCharged) - sum(b.AmountPaid)))
FROM tblCurrentTransaction AS b
WHERE b.TenantTransactionID <= a.TenantTransactionID
AND b.Tenant = a.Tenant
GROUP BY b.Tenant
) AS TrueBalance
FROM tblCurrentTransaction AS a
WHERE a.TenantTransactionID = tblCurrentTransaction.TenantTransactionID
ORDER BY a.Tenant, a.TenantTransactionID;
);
```
But it doesn't do anything, and Access complains *"Operation must use an updateable query"*
**This is the query that gathers the data**
This query returns the true balance, and the transaction ID it belongs to. This is what I need to insert into the table.
```
SELECT (SELECT IIF(IsNull(sum(b.AmountCharged) - sum(b.AmountPaid)),a.Balance, (sum(b.AmountCharged) - sum(b.AmountPaid)))
FROM tblCurrentTransaction AS b
WHERE b.TenantTransactionID <= a.TenantTransactionID AND b.Tenant = a.Tenant
GROUP BY b.Tenant
) AS TrueBalance, a.TenantTransactionID
FROM tblCurrentTransaction AS a
ORDER BY a.Tenant, a.TenantTransactionID;
``` | `SELECT UNION UPDATE`. Wow. Never seen anybody try that one before.
If this really has to be done in SQL, I'd say rewrite the whole thing as an `UPDATE` with subqueries.
If it doesn't really have to be done in SQL, I'd say rewrite the whole process so the logic is in your application language and the SQL queries are simple `UPDATE`s.
Edit: OP and I went through quite some adventures, as you can see in the comments. The final resolution was to use a scratch table to do the calculations in and push the results from there back into tblCurrentTransaction. I blame Access. | Try this:
```
UPDATE tblCurrentTransaction SET tblCurrentTransaction.Balance = i.TrueBalance
FROM ((SELECT
IIF(IsNull(sum(b.AmountCharged) - sum(b.AmountPaid)), a.Balance, (sum(b.AmountCharged) - sum(b.AmountPaid)))
FROM tblCurrentTransaction AS b
WHERE b.TenantTransactionID <= a.TenantTransactionID AND b.Tenant = a.Tenant
GROUP BY b.Tenant
) AS TrueBalance, a.TenantTransactionID
FROM tblCurrentTransaction AS a
)AS i
WHERE tblCurrentTransaction.TenantTransactionID = i.TenantTransactionID;
``` | How can I make this complex update query work? | [
"",
"sql",
"ms-access",
""
] |
I'm using an SQLite database from python (with [SQLAlchemy](http://www.sqlalchemy.org/)). For performance reasons, I'd like to populate an in-memory database in the application, and then back up that database to disk.
SQLite has a [backup API](http://www.sqlite.org/backup.html), which seems would do this transparently.
The [APSW](http://code.google.com/p/apsw/) documentation says that it [wraps the backup API](http://apsw.googlecode.com/svn/publish/backup.html), but I'd like to access this functionality from Python's standard sqlite3 module, or in the best case from SQLAlchemy. Is this possible? | The [python-sqlite3-backup](https://github.com/husio/python-sqlite3-backup) module claims to solve this problem. | the APSW dialect can be added to SQLAlchemy pretty easily as well. It would be very easy to achieve in 0.6, which allows multiple kinds of DBAPI adapters to make use of a common dialect for the database in use. | Use SQLite's backup API from Python/SQLAlchemy | [
"",
"python",
"sqlite",
"sqlalchemy",
"apsw",
""
] |
I've modified my run.sh file and added `JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=1044,server=y,suspend=n"` but when I start JBoss I get `FATAL ERROR in native method: No transports initialized`.
Looking around the internet it seems like it may having something to do with missing jars or my version of Java? I'm on J2SDK JRE 1.4.2.
Thoughts anyone? | This error can mean many things but for me, this error meant there was already a process listening on port 1044. All I had to do was change my port address to 1045 and problem was solved.
```
JAVA_OPTS="$JAVA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=1045,server=y,suspend=n"
``` | I had this error, I fixed it by changing my `JAVA_OPTS` from this:
```
set JAVA_OPTS=-Xdebug -Xrunjdwp:transport=dt_socket,address=8787,server=n,suspend=n %JAVA_OPTS%
```
To this:
```
set JAVA_OPTS=-agentlib:jdwp=transport=dt_socket,address=8787,server=y,suspend=n %JAVA_OPTS%
``` | Why do I get "No transports initialized" error when starting JBoss with remote debugging? | [
"",
"java",
"debugging",
"jboss",
"remote-debugging",
""
] |
I'm currently in the process of setting my website, largely with php. Though this is my first time using it so I'm running into some problems.
I've got the basics of the site down. Registering, login-in, profile page e.t.c. However this is where I seem to have to make a decision about the site layout.
For instance. Currently a user's profile page has the URL of
> mysite.com/profile.php
Ideally what I would like is for it to be is something along the lines of
> mysite.com/user/ChrisSalij
From reading [this](https://stackoverflow.com/questions/115629/simplest-php-routing-framework) among other things I believe I need a Front Controller style site, though I'm not sure of this, nor where to start with implementing one.
Bearing in mind that I'm pretty new to php and the like, I would appreciate any helpful comments, and links, and constructive critiques.
I'm defiantly will to learn so links to articles and explanations would be excellent. I usually do a fair amount of research on stuff like this. But I'm so new to it that I don't know where to start.
EDIT: I should also add that I'm planning on scaling this website up to the large scale. It's small to start with but there should be quite a few pages if my goals work out. So I'm willing to put the effort in now to get it set up right for the long term.
Thanks | Well, welcome to the world of PHP :)
First of all, a front controller is typically only 1 part of a larger framework known as a MVC (Model-View-Controller). Simply put, a front controller can be though of as the "index" page that all people go to when they come to your site. It handles initiating needed site things and then pulling and running what resouces are needed to handle the user request (typically through the URL, as you have given of mysite.com/user/...). This is an overly simple explanation.
While not necessarily a hard thing to learn, I would recommend looking at a tutorial like [this](http://www.phpro.org/tutorials/Model-View-Controller-MVC.html) that explains the whole idea and basic implementation of a MVC. They call the front controller a "router" (that's another thing, there are more than 1 way to implement a MVC or it's variants and more than 1 name for the different parts). I don't think it is particularity hard to understand or grasp. Most modern MVC frameworks do implement Object Oriented Programming practices. For a good set of video screencast on PHP (including some basic OOP skills), take a look [here](http://net.tutsplus.com/videos/screencasts/diving-into-php-video-series/).
Lastly, if this is your first big use of PHP and want to implement something like MVC, you might check out something like [CakePHP](http://cakephp.org/) or [CodeIgniter](http://codeigniter.com/). Great frameworks that have good documentation and has done alot of hard work for you. Good luck | Assuming you're on apache, you can create a file called [.htaccess](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html) at the root of your site, and add these lines
```
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* /index.php?url=$0 [L,QSA]
```
This will pass all page requests to index.php. In index.php, you'd want to to parse `$_GET['url']` and load up the proper page with `include`. You'll have to sanitize the input and make sure people aren't including anything they shouldn't. You can get the pieces with something like:
```
list($controller, $username) = explode('/', $_GET['url']);
```
The typical MVC structure would use `controller/action/id`. If "action" is omitted though, as in your example, I'd make it default to "view". As in "view" user's profile. The ID would be the username. Typically, each controller is a class, and each action is a function in that class, any parameters after that are passed into the function. There's also an associated view file with each action.
It's a lot of code to give you a full example (I just coded up an MVC framework!) but that should give you the basics to get started.
Definately check out some other frameworks like CakePHP, Kohana/CodeIgniter if you need more details and code examples. | Php site structure | [
"",
"php",
"front-controller",
""
] |
If I'm working with, say, a BookID of type int in my code that corresponds to an int primary key field in a database table (I'm using C# and SQL Server)... is it best practice, when I'm passing around IDs in my code, to use a nullable int and check for null to see if the BookID exists:
```
if (BookID != null) {
```
or, is it a better practice to assign an integer value (such as 0 or -1) that cannot correspond to an actual value in the db:
```
if (BookID > 0) {
```
---
EDIT:
For further clarification, suppose I only want to return the ID of the book, instead of the whole book object. In the db, the primary key is non-nullable, *but* if I were to perform a query for the BookID of 'my book title' that didn't exist, then I would get no results. Should this be reflected as null?
Example:
```
BookID = GetBookID("my book title");
``` | If you have a value that allows null in the database, you should use `Nullable<T>` and avoid introducing [Magic Numbers](http://en.wikipedia.org/wiki/Magic_number_(programming)). But if `BookId` is a (primary) key, it should probably not be nullable (besides it is used as a foreign key).
**UPDATE**
For the point of querying the database and not finding a matching record, there are several solutions. I prefer to throw an exception because it is usually an indication of an error if the application tries to get a record that does not exist.
```
Book book = Book.GetById(id);
```
What would you do in this case with a null return value? Probably the code after this line wants to do something with the book and in the case of null the method could usually do nothing more then
1. throwing an exception that could be better done in `GetById()` (besides the caller might have more context information on the exception)
2. returning immidiatly with null or an error code that requires handling by the caller, but that is effectivly reinventing an exception handling system
If it is absolutly valid, not to find a matching record, I suggest to use the TryGet pattern.
```
Book book;
if (Book.TryGetById(out book))
{
DoStuffWith(book);
}
else
{
DoStuffWithoutBook();
}
```
I believe this is better then returning null, because null is a kind of a magic value and I don't like to see implementation details (that a reference type or a nullable value type can take the special value named null) in the business logic. The drawback is that you lose composability - you can no longer write `Book.GetById(id).Order(100, supplier)`.
The following gives you the composability back, but has a very big problem - the book could become deleted between the call to `Exists()` and `GetById()`, hence I strongly recommend not to use this pattern.
```
if (Book.Exists(id))
{
Book book = Book.GetById(id).Order(100, supplier);
}
else
{
DoStuffWithoutBook();
}
``` | I prefer to use a nullable int - this maps more directly to what will actually be in the database.
Also, there are many times when there are no appropriate values to use for null. Using -1 to signify null is bad practice, IMO, since -1 is often a valid value in a DB. | Should I use a nullable int when working with int object IDs? | [
"",
"c#",
"primary-key",
"nullable",
""
] |
I have a program that creates a `JFrame` and makes it visible. Is there anyway to know when the `JFrame` is fully drawn and visible? Right now a hacky "wait and pray" method is being used. | You could [add](http://java.sun.com/javase/6/docs/api/java/awt/Window.html#addWindowListener(java.awt.event.WindowListener)) a [`WindowListener`](http://java.sun.com/javase/6/docs/api/java/awt/event/WindowListener.html) to the `JFrame`; then when [`windowOpened`](http://java.sun.com/javase/6/docs/api/java/awt/event/WindowListener.html#windowOpened(java.awt.event.WindowEvent)) is fired, the window should be visible. | to answer the "How can yield and specifically wait for the Swing thread to execute" question:
you can use a [SwingWorker](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html).
**edit**
reading your comment once more i see a potentially problematic statement:
> I'm creating a JFrame in a thread, then I want that thread to wait for the JFrame to appear.
are you calling your `frame.setVisible(true)` in this thread as well? If so, you should probably be reminded that Swing painting should all be handled on the AWT EventQueue. This is where the `SwingWorker` comes in.
However, what you may need for the 'yield and wait' is a wait/notify operation. In your calling thread you can wait on a shared Object:
```
synchronized (frameShowingLock) {
frameShowingLock.wait()'
}
```
then in your SwingWorker, or wherever you call frame.setVisible(true) you can finish the process by using the `notifyAll()` method to wake up your waiting thread:
```
synchronized (frameShowingLock) {
frameShowingLock.notifyAll()'
}
``` | Knowing when a JFrame is fully drawn | [
"",
"java",
"multithreading",
"swing",
""
] |
I am running a thread in C#.
I have web form. I declared public string attribute in my web form. (e.g. string myVal)
Then I called thread and assign value into myVal.
It assign values in it.
But when I exit from thread code, myVal become null.
Is there anyway to keep myVal value.
```
public string myVal;
protected void Page_Load(object sender, EventArgs e)
{
System.Threading.Thread myThread = new System.Threading.Thread(this.getVal);
myThread.SetApartmentState(System.Threading.ApartmentState.STA);
myThread.Start();
myThread.Join();
//I am not able to get myVal string over here.
}
private void getVal()
{
myVal = "I can easily get myVal over here.";
}
``` | Test Case failure: I copy-pasted your code in a new ASP.NET Project and added, after the myThread.Join() :
```
Label1.Text = myVal;
```
And the label does show your string. | Do you reference myVal further in your code or are you just inspecting it with the debugger and checking the value after you are done with it? If so maybe the garbage collector has already gotten to it. | how to get string value from thread | [
"",
"c#",
"multithreading",
"string",
""
] |
Is there some way I can catch when a method generates a write to STDERR?
I'm trying to pre-pend some information with each STDERR write.
let's say our method is:
```
parser.thatGeneratesSTDERR();
```
it'll generate something like
**line 37:29 no viable alternative at character 'a'**
can I just wrap it with something that catches the stderr to be written and pre-pend some
info so it'll look like this instead:
**File: mybadfile.txt -- line 37:29 no viable alternative at character 'a'**
I know I could probably dig through the actual code that does the STDERR writing but I really don't want to do that -- I'd rather just wrap some code around this method instead.
I should note that this method doesn't always generate STDERR -- the reason I'm trying to catch them is that it SHOULDN'T be generating any STDERR -- but since this is called on quite a few files (over 40) I never know which file is generating the error message -- it takes forever to find.
**UPDATE**
so yeh, we can change our STDERR -- I was just forgetting that I need to override my println in my new STDERR... here's the relevant code:
```
public static String errfile = "";
static {
final PrintStream currentErr = System.err;
PrintStream newErr = new PrintStream(currentErr)
{
public void println(String string) {
print("File: " + errfile + " --");
print(string);
super.println();
}
};
System.setErr(newErr);
}
```
then for each file that I'm testing all I have to do is change errfile to the filename and my output comes out expected...
thanks a lot! | I'm not sure if this will work, given how System.setErr works.
I would create a new class that extends print stream and overwrites the methods to prepend your comment. Then set the error stream to your new printstream. Do not call System.err.printxxx from this new class.
ex...
```
class PrependPrintStream extends PrintStream {
PrependPrintStream(PrintStream ps, String pre){...}
...
public void print(boolean b) {
super.print(this.pre);
super.print(b);
}
...
```
I looked into sun's PrintStream impl, and it looks like all printxxx delegate to write(String) which is private instead of protected. I guess you can copy/paste the code.
EDIT::
A *much* better solution is to use Logging instead of System.err. This allows you to turn off and on your statements and allows you to create a custom error handler. Your specific handler could prepend the statement you wish to the string before printing to System.err. This also has the advantage that only statements that use your specific logger would have the prepended text and other calls to System.err wouldn't. | Sounds like you probably want to look at Aspect Oriented Programming (AOP). Using AOP, you can create a proxy to the parser you are calling. Before the method call thatGeneratesSTDERR() you can have it invoke you call. From your call you can output the information you want.
Note that it might take a bit of reading to understand how AOP works.
AspectJ - <http://www.eclipse.org/aspectj/>
AOP Alliance - <http://sourceforge.net/projects/aopalliance> | How do I prepend information to STDERR when a method generates stderr? | [
"",
"java",
"hook",
"append",
"stderr",
"prepend",
""
] |
Assume I do not have text indexing on. Let say I have:
```
SELECT * FROM myTable WHERE myTable.columnA LIKE 'bobo'
```
Will the SQL engine go through every row and only return those matching conditions or is SQL smarter and does do some hidden native indexing?
I'm on MSSQL 2000, 2005, 2008 but if other versions of SQL have different approaches I'm all ears.
Is there a good online doc or even book that goes into how operations are carried out? | Put that query into an SQL Server Management Studio query, and enable the "Include actual execution plan" option before you run it. It will give you a detailed diagram of all the steps that are undertaken to execute the query, along with all of the indexes that are being used and how. | If you look into the execution plain for this query:
```
SELECT *
FROM mytable
WHERE columnA LIKE 'bobo%'
```
you will see that it will be rewritten as:
```
SELECT *
FROM mytable
WHERE columnA >= 'bobo'
AND columnA < 'bobP'
```
, using `INDEX SEEK` over an index on `columnA`, if any. | SQL Select with WHERE condition, what happens in the background? | [
"",
"sql",
"sql-server",
""
] |
I am sure this would have been asked before but couldn't find it. Is there any built in (i.e. either using std::wstring's methods or the algorithms) way to case insensitive comparison the two wstring objects? | If you don't mind being tied to Microsoft implementation you can use this function defined in `<string.h>`
```
int _wcsnicmp(
const wchar_t *string1,
const wchar_t *string2,
size_t count
);
```
But if you want best performance/compatibility/functionality ratio you will probably have to look at boost library (part of it is stl anyway). Simple example (taken from [different answer](https://stackoverflow.com/questions/11635/case-insensitive-string-comparison-in-c/315463#315463) to different question):
```
#include <boost/algorithm/string.hpp>
std::wstring wstr1 = L"hello, world!";
std::wstring wstr2 = L"HELLO, WORLD!";
if (boost::iequals(wstr1, wstr2))
{
// Strings are identical
}
``` | Using the standard library:
```
bool comparei(wstring stringA , wstring stringB)
{
transform(stringA.begin(), stringA.end(), stringA.begin(), toupper);
transform(stringB.begin(), stringB.end(), stringB.begin(), toupper);
return (stringA == stringB);
}
wstring stringA = "foo";
wstring stringB = "FOO";
if(comparei(stringA , stringB))
{
// strings match
}
``` | Comparing wstring with ignoring the case | [
"",
"c++",
"string",
"unicode",
"stl",
""
] |
2 months ago I was writing a web-application which use some classes to draw some charts. I've modified little those classes in order to fit with my needs. Now I wish to use a new(and official) version of that class, but also to have my modifications available.
The problem is that I don't remember exactly all the modification I've made and I don't wana loose them when I use the new version of the classes. | I'd just compare those files with a text diff tool that in included in many programs. If you're on Windows, you will find diff tools in Total Commander, PSPad, TortoiseSVN and many others.
My favourite diff tool is that in TortoiseSVN. It works also for files that are not in any repository. | That's really unfortunate. What's your question?
Have you been using version control, because if you had, you could go back to the earliest version of the classes and compare all of your modifications. | new version for the classes I've use in my application | [
"",
"php",
"class",
""
] |
I'm building a gui component that has a tree-based data model (e.g. folder structure in the file system). so the gui component basically has a collection of trees, which are just Node objects that have a key, reference to a piece of the gui component (so you can assign values to the Node object and it in turn updates the gui), and a collection of Node children.
one thing I'd like to do is be able to set "styles" that apply to each level of nodes (e.g. all top-level nodes are bold, all level-2 nodes are italic, etc). so I added this to the gui component object. to add nodes, you call AddChild on a Node object. I would like to apply the style here, since upon adding the node I know what level the node is.
problem is, the style info is only in the containing object (the gui object), so the Node doesn't know about it. I could add a "pointer" within each Node to the gui object, but that seems somehow wrong...or I could hide the Nodes and make the user only be able to add nodes through the gui object, e.g. gui.AddNode(Node new\_node, Node parent), which seems inelegant.
is there a nicer design for this that I'm missing, or are the couple of ways I mentioned not really that bad? | It seems to me that the only thing you need is a Level property on the nodes, and use that when rendering a Node through the GUI object.
But it matters whether your Tree elements are Presentation agnostic like XmlNode or GUI oriented like Windows.Forms.TreeNode. The latter has a TreeView property and there is nothing wrong with that. | Adding a ParentNode property to each node is "not really that bad". In fact, it's rather common. Apparently you didn't add that property because you didn't need it originally. Now you need it, so you have good reason to add it.
Alternates include:
* Writing a function to find the parent of a child, which is processor intensive.
* Adding a separate class of some sort which will cache parent-child relationships, which is a total waste of effort and memory.
Essentially, adding that one pointer into an existing class is a choice to use memory to cache the parent value instead of using processor time to find it. That appears to be a good choice in this situation. | should a tree node have a pointer to its containing tree? | [
"",
"c#",
"data-structures",
"tree",
""
] |
select convert(varbinary(8), 1) in MS SQL Server produces output : 0x00000001
On assigning the above query to dataset in Delphi, and accessing field value, we get byte array as [1, 0, 0, 0] . So Bytes[0] contains 1.
When I use IntToHex() on this bytes array it would result me value as "10000000" .
Why is IntToHex considering it in reverse order?
Thanks & Regards,
Pavan. | I think you forgot to include a reference to the code where you're somehow calling `IntToHex` on a `TBytes` array. It's from the answer to your previous question, [how to convert byte array to its hex representation in Delphi](https://stackoverflow.com/questions/1060321/how-to-convert-byte-array-to-its-hex-representation-in-delphi).
In [my answer](https://stackoverflow.com/questions/1060321/how-to-convert-byte-array-to-its-hex-representation-in-delphi/1060455#1060455), I forgot to account for how a pointer to an array of bytes would have the bytes in big-endian order while `IntToHex` (and everything else on x86) expects them in little-endian order. The solution is to switch them around. I used this function:
```
function Swap32(value: Integer): Integer;
asm
bswap eax
end;
```
In the meantime, I fixed my answer to account for that. | This seems to be a [little/big endian](http://en.wikipedia.org/wiki/Endianness) problem. Just reverse the byte array or the return value from IntToHex. Another way would be to do it yourself:
```
myInt = Bytes[0];
Inc(myInt, (Bytes[1] shl 8));
Inc(myInt, (Bytes[2] shl 16));
Inc(myInt, (Bytes[3] shl 24));
```
Also be careful with the sign. Is the SQL value signed or unsigned - the Delphi datatype should match this (int/longint is signed, Longword/Cardinal is unsigned - see [here](http://www.delphibasics.co.uk/Article.asp?Name=DataTypes) or in the Delphi Help). | Dataset's TBytes column and SQL VarBinary field combination | [
"",
"sql",
"delphi",
"delphi-2009",
""
] |
I am looking for a cross-platform C++ master/worker library or work queue library. The general idea is that my application would create some sort of Task or Work objects, pass them to the work master or work queue, which would in turn execute the work in separate threads or processes. To provide a bit of context, the application is a CD ripper, and the the tasks that I want to parallelize are things like "rip track", "encode WAV to Mp3", etc.
My basic requirements are:
* Must support a configurable number of concurrent tasks.
* Must support dependencies between tasks, such that tasks are not executed until all tasks that they depend on have completed.
* Must allow for cancellation of tasks (or at least not prevent me from coding cancellation into my own tasks).
* Must allow for reporting of status and progress information back to the main application thread.
* Must work on Windows, Mac OS X, and Linux
* Must be open source.
It would be especially nice if this library also:
* Integrated with Qt's signal/slot mechanism.
* Supported the use of threads *or* processes for executing tasks.
By way of analogy, I'm looking for something similar to Java's ExecutorService or some other similar thread pooling library, but in cross-platform C++. Does anyone know of such a beast?
Thanks! | I think this calls for intel's [Threading Building Blocks](http://www.threadingbuildingblocks.org/), which pretty much does what you want. | I haven't used it in long enough that I'm not positive whether it exactly meets your needs, but check out the [Adaptive Communications Environment (ACE)](http://www.cs.wustl.edu/~schmidt/ACE.html). This library allows you to construct "active objects" which have work queues and execute their main body in their own threads, as well as thread pools that can be shared amoung objects. Then you can pass queue work objects on to active objects for them to process. Objects can be chained in various ways. The library is fairly heavy and has a lot to it to learn, but there have been a couple of books written about it and theres a fair amount of tutorial information available online as well. It should be able to do everything you want plus more, my only concern is whether it possesses the interfaces you are looking for 'out of the box' or if you'd need to build on top of it to get exactly what you are looking for. | C++ master/worker | [
"",
"c++",
"multithreading",
"concurrency",
"threadpool",
""
] |
i have a sql query:
```
select id, name from table order by name
```
result looks like this:
```
52 arnold
33 berta
34 chris
47 doris
52 emil
```
for a given id=47 how can i determine the position in the result set?
the result should be 4 because:
```
52 arnold
33 berta
34 chris
```
are before (47, doris) and id=41 is on the 4th position in the result set.
How to do this in SQL?
How in HQL?
In a pagination example, do i have to execute 2 statements or is there a solution where i can retrieve exactly that window which contains the row with id=47?
postgreSQL and java | The previous posts are correct. Use ROW\_NUMBER if using Microsoft SQL Server 2005 or greater.
However, your tags do not specify that you're using MSSQL, so here's a solution that should work across most RDBMS implementations. Essentially, use a correlated subquery to determine the count of rows in the same set that are less than the current row, based on the values of the ORDER clause of the outer query. Something like this:
```
SELECT T1.id,
T1.[name],
(SELECT COUNT(*)
FROM table T2
WHERE T2.[name] < T1.[name]) + 1 AS rowpos
FROM table T1
ORDER BY T1.[name]
``` | You don't mention which RDBMS you're running, but if you're using SQL Server 2005 or greater, you can employ the ROW\_NUMBER() function - like this:
```
SELECT id, name, ROW_NUMBER() OVER (ORDER BY name) AS RowNumber
FROM MyTable
```
Then, to fetch a given row, you can use a derived table or a common table expression - like this:
```
;WITH NumberedRows
AS
(SELECT id, name, ROW_NUMBER() OVER (ORDER BY name) AS RowNumber
FROM MyTable)
SELECT RowNumber FROM NumberedRows WHERE id = 47
```
To sort out "which page" the record is on, you would need to divide the row number by the number of records per page, and round up to the nearest integer. | How to determine position of row in sql result-set? | [
"",
"sql",
"count",
""
] |
I am following this tutorial, I'm using netbeans 6.5.1 <http://www.netbeans.org/kb/docs/java/gui-db-custom.html>
When I get to the part where I create the "new entity class from database", which is in the "Customizing the Master/Detail View" section of the tutoiral. I can't ever compile because I get this error in the task list (and I get a runtime error when I run)... Atleast I think these two are related.
```
Error Named queries can be defined only on an Entity or MappedSuperclass class. Countries.java 27 C:/Users/Danny/dev/NetBeansProjects/Test/src/test
Error Named queries can be defined only on an Entity or MappedSuperclass class. Products.java 28 C:/Users/Danny/dev/NetBeansProjects/Test/src/test
```
note that all I do is do new>entity classes from database, and do exactly as the tutorial says. I stopped on the tutoral at the "Adding Dialog Boxes" heading, because the tutorial writer says the application should be "partially functional" which makes me think it should atleast RUN. I haven't edited the generated code outside of what I've been instructed to do.
This is the output produced by the netbeans output console:
```
run:
Jun 23, 2009 3:03:23 PM org.jdesktop.application.Application$1 run
SEVERE: Application class test.TestApp failed to launch
javax.persistence.PersistenceException: No Persistence provider for EntityManager named MyBusinessRecordsPU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7
Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at test.TestView.initComponents(TestView.java:337)
at test.TestView.(TestView.java:39)
at test.TestApp.startup(TestApp.java:19)
at org.jdesktop.application.Application$1.run(Application.java:171)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:643)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.callPredeploy(JavaSECMPInitializer.java:171)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initPersistenceUnits(JavaSECMPInitializer.java:239)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initialize(JavaSECMPInitializer.java:255)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:155)
... 14 more
Caused by: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:228)
... 19 more
Caused by: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.ValidationException.invalidMapping(ValidationException.java:1069)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataValidator.throwInvalidMappingEncountered(MetadataValidator.java:275)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.OneToManyAccessor.process(OneToManyAccessor.java:161)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.RelationshipAccessor.processRelationship(RelationshipAccessor.java:290)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.processRelationshipDescriptors(MetadataProject.java:579)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.process(MetadataProject.java:512)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.processAnnotations(MetadataProcessor.java:246)
at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:370)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:607)
... 18 more
The following providers:
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at test.TestView.initComponents(TestView.java:337)
at test.TestView.(TestView.java:39)
at test.TestApp.startup(TestApp.java:19)
at org.jdesktop.application.Application$1.run(Application.java:171)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Exception in thread "AWT-EventQueue-0" java.lang.Error: Application class test.TestApp failed to launch
at org.jdesktop.application.Application$1.run(Application.java:177)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: javax.persistence.PersistenceException: No Persistence provider for EntityManager named MyBusinessRecordsPU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:
oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Local Exception Stack:
Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: sun.misc.Launcher$AppClassLoader@11b86e7
Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at test.TestView.initComponents(TestView.java:337)
at test.TestView.(TestView.java:39)
at test.TestApp.startup(TestApp.java:19)
at org.jdesktop.application.Application$1.run(Application.java:171)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:643)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.callPredeploy(JavaSECMPInitializer.java:171)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initPersistenceUnits(JavaSECMPInitializer.java:239)
at oracle.toplink.essentials.internal.ejb.cmp3.JavaSECMPInitializer.initialize(JavaSECMPInitializer.java:255)
at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:155)
... 14 more
Caused by: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.EntityManagerSetupException
Exception Description: predeploy for PersistenceUnit [MyBusinessRecordsPU] failed.
Internal Exception: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:228)
... 19 more
Caused by: Exception [TOPLINK-7244] (Oracle TopLink Essentials - 2.0.1 (Build b09d-fcs (12/06/2007))): oracle.toplink.essentials.exceptions.ValidationException
Exception Description: An incompatible mapping has been encountered between [class test.Products] and [class test.Orders]. This usually occurs when the cardinality of a mapping does not correspond with the cardinality of its backpointer.
at oracle.toplink.essentials.exceptions.ValidationException.invalidMapping(ValidationException.java:1069)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataValidator.throwInvalidMappingEncountered(MetadataValidator.java:275)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.OneToManyAccessor.process(OneToManyAccessor.java:161)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.accessors.RelationshipAccessor.processRelationship(RelationshipAccessor.java:290)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.processRelationshipDescriptors(MetadataProject.java:579)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProject.process(MetadataProject.java:512)
at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataProcessor.processAnnotations(MetadataProcessor.java:246)
at oracle.toplink.essentials.ejb.cmp3.persistence.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:370)
at oracle.toplink.essentials.internal.ejb.cmp3.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:607)
... 18 more
The following providers:
oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider
Returned null to createEntityManagerFactory.
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)
at test.TestView.initComponents(TestView.java:337)
at test.TestView.(TestView.java:39)
at test.TestApp.startup(TestApp.java:19)
at org.jdesktop.application.Application$1.run(Application.java:171)
... 8 more
BUILD SUCCESSFUL (total time: 2 seconds)
```
I'm thinking my netbeans application must be misconfigured or something, I can't seem to find anyone with the same problem as myself | Seems to have been a bug in netbeans, I did a fresh install and it seems to work now. | I had the same problem.
Reinstalled - same problem.
Ran Revo uninstaller on default settings.
Reinstalled.
This time I created entities for the Countries & Products tables as soon as I could in the process - immediately after the New Project wizard.
I'm not sure if that made the difference, but this time all was well | Netbeans / persistence API error | [
"",
"java",
"netbeans",
"persistence",
""
] |
If I have:
```
List<string> myList1;
List<string> myList2;
myList1 = getMeAList();
// Checked myList1, it contains 4 strings
myList2 = getMeAnotherList();
// Checked myList2, it contains 6 strings
myList1.Concat(myList2);
// Checked mylist1, it contains 4 strings... why?
```
I ran code similar to this in Visual Studio 2008 and set break points after each execution. After `myList1 = getMeAList();`, `myList1` contains four strings, and I pressed the plus button to make sure they weren't all nulls.
After `myList2 = getMeAnotherList();`, `myList2` contains six strings, and I checked to make sure they weren't null... After `myList1.Concat(myList2);` myList1 contained only four strings. Why is that? | `Concat` returns a new sequence [without modifying the original list](https://stackoverflow.com/questions/100196/net-listt-concat-vs-addrange). Try `myList1.AddRange(myList2)`. | Try this:
```
myList1 = myList1.Concat(myList2).ToList();
```
[Concat](http://msdn.microsoft.com/en-us/library/bb302894.aspx) returns an IEnumerable<T> that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List<T>, you'll have to call ToList() on the IEnumerable<T> that is returned. | How do you concatenate Lists in C#? | [
"",
"c#",
"arrays",
"list",
"concatenation",
""
] |
Greetings,
With javascript, I am trying to make a very easy animation, an image moves from one X and Y coordination to another X Y coordination.
I have 4 constant such as:
```
var startX = 0; //starting X of an image
var startY = 0; //starting Y of an image
var endX = 100; //ending X of an image
var endY = 200; //ending Y of an image
//these 2 are used for keeping the "current" position of animated image,
var currentX = startX ;
var currentY = startY ;
//every 150 ms, updates the location of the coordinates
function move(){
if( (currentX == endX) && (currentY == endY) )
break;
if(currentX < endX){
currentX = currentX + step_amount;
}
if(currentX > endX){
currentX = currentX - step_amount;
}
if(currentY < endY){
currentY = currentY + step_amount;
}
if(currentY > endY){
currentY = currentY - step_amount;
}
setInterval("move()", 150);
}
```
This does the job, however it is not smooth, I will be grateful if you help me improve my naive algorithm for a better move function that is always going for the "shortest path". | Sounds like you need (a variation of) the [Bresenham line drawing](http://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm) algorithm. | The shortest distance between two points is a straight line. So you should probably move along that.
What that would imply is that in your code, you should not use the same step amount for both X and Y coordinates. Instead compute Y step based on X step and the slope of the shortest path line.
```
slope = (startY - endY) / (startX - endX);
Y_step = X_step * slope;
```
Secondly, in your current algorithm, once your image reaches the destination point, it'll continue to oscillate about it. I think you should get rid of the statements that take a negative step. | help me improve my basic point to point move animation algorithm | [
"",
"javascript",
"algorithm",
"animation",
""
] |
I'm trying to build zimbra from source on a mac mini running on mac os x 10.4.10.
It seems that I need a file like this "jdk-1\_5\_0\_16-linux-i586.bin" but I can't seem to find a jdk binary that is made for mac osx.
Can anybody point me to this binary?
Here is what zimbra does with the binary:
```
sh jdk-1_5_0_15-linux-amd64.bin
tar czf jdk1.5.0_15.tgz jdk1.5.0_15
mv jdk1.5.0_15.tgz /opt/build.zimbra/source/FRANKLIN/ThirdPartyBuilds/x86_64/java/
```
If I cannot download this, Is there a way to create the tgz from an installation of java? | After a lot of searching I was able to find that the JDK is stored in "/System/Library/Frameworks/JavaVM.framework/Versions" just tarred this and I got what I needed! Thanks for the help. this is for 10.4, I don't know with previous or the most current version. | Java is part of the Max OS X install. The JDK for Mac is maintained by Apple, and you cannot download it anywhere else.
You should have JDK 1.5 already. Open a terminal and try "java -version" and "which java".
As for Zimbra, their download page has Mac binaries. They should work "out of the box". Are you sure you need to build from source? | Looking for Java binary for Mac OS X | [
"",
"java",
"macos",
"zimbra",
""
] |
I have a one-dimensional function minimizer. Right now I'm passing it function pointers. However many functions have multiple parameters, some of which are held fixed. I have implemented this using functors like so
```
template <class T>
minimize(T &f) {
}
Functor f(param1, param2);
minimize<Functor>(f);
```
However the functor definition has lots of crud. Boost::bind looks cleaner. So that I could do:
```
minimize(boost:bind(f,_1,param1,param2))
```
However I'm not clear what my `minimize` declaration should like like using `boost::bind`. What type of object is `boost::bind`? Is there an easy pattern for this that avoids the boilerplate of functors but allows multiple parameter binding? | You can just use `boost::function`. I think `boost::bind` does have its own return type, but that is compatible with `boost::function`. Typical use is to make a typedef for the function:
```
typedef boost::function<bool(std::string)> MyTestFunction;
```
and then you can pass any compatible function with `boost::bind`:
```
bool SomeFunction(int i, std::string s) { return true; }
MyTestFunction f = boost::bind(SomeFunction, 42, _1);
f("and then call it.");
```
I hope that is what you want.
It also works with methods by passing the `this` pointer for the call as second parameter to `boost::bind`. | I would define minimize() this way:
```
minimize(boost::function< return_type(param_type1,param_type2,param_type3,...)> f)
{
...
}
```
Then you could call minimize() like this:
```
minimize(boost::bind(&class::function,actual_object,_1,_2,_3,...));
``` | How do you pass boost::bind objects to a function? | [
"",
"c++",
"boost-bind",
""
] |
For example, I get this compiler warning,
> The event 'Company.SomeControl.SearchClick' is never used.
But I know that it's used because commenting it out throws me like 20 new warnings of XAML pages that are trying to use this event!
What gives? Is there a trick to get rid of this warning? | This appears to be [warning 67](http://msdn.microsoft.com/en-us/library/858x0ycc.aspx) and can thus be suppressed with:
```
#pragma warning disable 67
```
Don't forget to restore it as soon as possible (after the event declaration) with:
```
#pragma warning restore 67
```
---
However, I'd check again and make sure you're *raising* the event somewhere, not *just subscribing* to it. The fact that the compiler spits out 20 *warnings* and not 20 *errors* when you comment out the event is also suspicious...
There's also [an interesting article](https://learn.microsoft.com/en-us/archive/blogs/trevor/c-warning-cs0067-the-event-event-is-never-used) about this warning and specifically how it applies to interfaces; there's a good suggestion on how to deal with "unused" events. The important parts are:
> The right answer is to be explicit about what you expect from the event, which in this case, is nothing:
>
> ```
> public event EventHandler Unimportant
> {
> add { }
> remove { }
> }
> ```
>
> This will cleanly suppress the warning, as well as the extra compiler-generated implementation of a normal event. And as another added benefit, it prompts one to think about whether this do-nothing implementation is really the best implementation. For instance, if the event isn't so much unimportant as it is unsupported, such that clients that do rely on the functionality are likely to fail without it, it might be better to explicitly indicate the lack of support and fail fast by throwing an exception:
>
> ```
> public event EventHandler Unsupported
> {
> add { throw new NotSupportedException(); }
> remove { }
> }
> ```
>
> Of course, an interface that can be usefully implemented without some parts of its functionality is sometimes an indication that the interface is not optimally cohesive and should be split into separate interfaces. | If you are forced to implement an event from an interface, that your implementation doesn't need you can do the following to avoid the warning.
```
public event EventHandler CanExecuteChanged { add{} remove{} }
``` | How do I get rid of "[some event] never used" compiler warnings in Visual Studio? | [
"",
"c#",
".net",
"wpf",
"events",
"compiler-warnings",
""
] |
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=utf-8" />
<title>title</title>
</head>
<body>
<script type="text/javascript">
<!--
var pre = document.createElement('pre');
pre.innerHTML = "aaa\naaa\nbbb";
document.body.appendChild(pre);
//-->
</script>
</body>
</html>
```
but break line removed.
Why?
There are another good method? | ```
var pre = document.createElement('pre');
pre.innerHTML = "aaa<br />aaa<br />bbb";
document.body.appendChild(pre);
``` | Internet Explorer normalizes whitespace when assigning to .innerHTML. You might want to try .innerText instead.
see: <http://stud3.tuwien.ac.at/~e0226430/innerHtmlQuirk.html> | innerHTML breakline cannot work in IE6 | [
"",
"javascript",
"html",
""
] |
Okay, here's what I'm trying to do: I'm trying to use PHP to develop what's essentially a *tiny* subset of a markdown implementation, not worth using a full markdown class.
I need essentially do a str\_replace, but alternate the replace string for every occurrence of the needle, so as to handle the opening and closing HTML tags.
For example, italics are a pair of asterisks like \*this\*, and code blocks are surrounded by backticks like `this`.
I need to replace the first occurrence of a pair of the characters with the opening HTML tag corresponding, and the second with the closing tag.
Any ideas on how to do this? I figured some sort of regular expression would be involved... | Personally, I'd loop through each occurrence of `*` or `\` with a counter, and replace the character with the appropriate HTML tag based on the count (for example, if the count is even and you hit an asterisk, replace it with `<em>`, if it's odd then replace it with `</em>`, etc).
But if you're sure that you only need to support a couple simple kinds of markup, then a regular expression for each might be the easiest solution. Something like this for asterisks, for example (untested):
```
preg_replace('/\*([^*]+)\*/', '<em>\\1</em>', $text);
```
And something similar for backslashes. | What you're looking for is more commonly handled by a state machine or lexer/parser.
This is ugly but it works. Catch: only for one pattern type at a time.
```
$input = "Here's some \\italic\\ text and even \\some more\\ wheee";
$output = preg_replace_callback( "/\\\/", 'replacer', $input );
echo $output;
function replacer( $matches )
{
static $toggle = 0;
if ( $toggle )
{
$toggle = 0;
return "</em>";
}
$toggle = 1;
return "<em>";
}
``` | PHP Replace, But Alternate Replace String | [
"",
"php",
"markdown",
"replace",
""
] |
How do I check which version of the Python interpreter is running my script?
---
See [Find full path of the Python interpreter (Python executable)?](https://stackoverflow.com/questions/2589711) if you are looking to find exactly *which interpreter* is being used - for example, to debug a Pip installation problem, or to check which virtual environment (if any) is active. | This information is available in the [`sys.version`](http://docs.python.org/library/sys.html#sys.version) string in the [`sys`](http://docs.python.org/library/sys.html) module:
```
>>> import sys
```
Human readable:
```
>>> print(sys.version) # parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
```
For further processing, use [`sys.version_info`](http://docs.python.org/library/sys.html#sys.version_info) or [`sys.hexversion`](http://docs.python.org/library/sys.html#sys.hexversion):
```
>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
```
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
```
assert sys.version_info >= (2, 5)
```
This compares major and minor version information. Add micro (=`0`, `1`, etc) and even releaselevel (=`'alpha'`,`'final'`, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others. | From the command line (note the capital 'V'):
```
python -V
```
This is documented in 'man python'.
From IPython console
```
!python -V
``` | How do I check which version of Python is running my script? | [
"",
"python",
"version",
""
] |
No boost, just plain STL please.
I have a class Foo\* mapping to a set of pointers of class ID.
and I need to map a pointer to an instance of ID to a FOO class.
say I have this function:
```
void FindXXX(const ID* pID)
{
/*find the containing FOO class quickly, but not at expense of an ugly code*/
}
```
right now I map each ID\* to FOO\* thus having something like that
map myMap; which I think is kind of ugly and redundant.
Please suggest | > right now I map each ID\* to FOO\* thus
> having something like that
>
> map myMap; which I think is kind of
> ugly and redundant.
I assume you have something like this:
```
map<ID*, Foo*> myMap;
```
Why would that be ugly? | Sounds like a job for std::map, but your remarks seem to indicate that you don't want to use one, is that true?
```
std::map <key_type, data_type, [comparison_function]>
``` | Good datastructure for look up of an id mapping to set of elements (c++) | [
"",
"c++",
"algorithm",
"stl",
""
] |
When building a C# application with Visual Studio 2008, is it possible to set a different output filename per configuration?
```
e.g.
MyApp_Debug.exe
MyApp_Release.exe
```
I tried a post-build step to rename the file by appending the current configuration, but that seems a scrappy approach. Plus it meant that Visual Studio could no longer find the file when pressing F5 to start debugging. | You can achieve this by editing your project file by hand. Locate the `<AssemblyName>` node and add a conditional attribute to it:
```
<AssemblyName Condition="'$(Configuration)'=='Debug'">MyApp_Debug.exe</AssemblyName>
<AssemblyName Condition="'$(Configuration)'=='Release'">MyApp_Release.exe</AssemblyName>
```
You'll have to duplicate it also to add another conditional attribute for the release version.
Whilst it is possible, it may cause problems. There is an [AssemblyConfiguration](http://msdn.microsoft.com/en-us/library/system.reflection.assemblyconfigurationattribute(VS.80).aspx) attribute that can be applied to your assembly. In `AssemblyInfo.cs`, put:
```
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
```
This will add a property to your compiled assembly that will tell you which build configuration your application was built using. | As adrianbanks mentioned, you can edit your .csproj file by hand to accomplish this.
I would, however reccomend the simpler form of:
```
<AssemblyName>MyApp_$(Configuration).exe</AssemblyName>
```
If you ever edit the properties of this project however, this change will very likely be lost. It's something you will have to manually stay on top of, as it's not going to be a supported setup.
To manually edit your project definition, right click the project in Visual Studio, and select "Unload", then right click the unloaded project, and select "Edit" and it will open the XML definition for you. | VS2008 - Outputting a different file name for Debug/Release configurations | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
"build-process",
""
] |
**The code is from K. Pollari-Malmi's lecture notes for the course "Introduction to Programming":**
```
def main():
print "Ohjelma laskee asuntolainan kuukausierat."
rivi = raw_input("Anna lainasumma: ")
lainasumma = float(rivi)
rivi = raw_input("Anna laina-aika vuosina: ")
laina_aika = int(rivi)
if laina_aika < 1:
print "liian lyhyt laina-aika"
else:
kk_lkm = 12 * laina_aika
rivi = raw_input("Anna korkoprosentti: ")
korko = float(rivi)
lyhennys = lainasumma / kk_lkm
paaoma = lainasumma
i = 0
print " lyhennys korko yhteensa"
while i < kk_lkm:
i = i + 1
korkoera = korko / 1200.0 * paaoma
paaoma = paaoma - lyhennys
kuukausiera = korkoera + lyhennys
print "%2d. %8.2f %8.2f %8.2f" % \ # mistake probably here
(i, lyhennys, korkoera, kuukausiera)
main()
```
I get the syntax error
```
SyntaxError: unexpected character after line continuation character
```
**How can you solve the error message?** | Several answers already gave you the crux of your problem, but I want to make a plug for my favorite way to get logical line continuation in Python, when feasible:
```
print "%2d. %8.2f %8.2f %8.2f" % ( # no mistake here
i, lyhennys, korkoera, kuukausiera)
```
i.e., instead of using extra parentheses as some answers advise, you can take advantage of any parenthesis you already naturally happen to have -- that will tell Python that you need logical line continuation, too;-) | You can't have *anything*, even whitespace, after the line continuation character.
Either delete the whitespace, or wrap the entire line in a pair of parentheses. [Python implicitly joins lines between parentheses, curly braces, and square brackets](http://docs.python.org/reference/lexical_analysis.html#implicit-line-joining):
```
print ( "%2d. %8.2f %8.2f %8.2f" %
(i, lyhennys, korkoera, kuukausiera) )
``` | Unable to solve a Python error message | [
"",
"python",
""
] |
The unique poll/vote/survey i mean here is, user can only vote once. How do i do that? Track their ip? Login? Beside login, what else? (login is my last option, thus beside login, is there anything else I can do?) | To restrict the number of votes per person, you need to track the person.
Now there can be several ways to do that, and I'll list them with their pros and cons. Its for you to decide which method suits you best.
1. login: this will offer you ultimate control. But its also a little cumbersome for the user. *and* its your last preference
2. IP: how will you handle people behind web proxies? How about people with dialup connections and/or dynamic IPs?
3. cookies: this is good for short term polls, so you can set the expiration of cookies to a time when the poll has ended. But, a potential drawback is that a user (contrasted with a [luser](http://en.wikipedia.org/wiki/Luser)) will know how to delete the cookies!
4. **openId**: While this method is not too different from the 'login' method, this saves the user from registration (which really is the part that sux the most about logins).
EDIT: the problem with this situation is that you need to resolve the *identity* of the user. I think **OpenID** does this pretty darn well.
Cheers,
jrh. | You could always store a cookie on their computer. Beware, though, that the user can easily disable cookies, or modify the contents of a cookie. There is no 100% reliable method to do what you want to do - the user can always create a new account, or move to another computer, etc.
If you want to go with the cookie approach though, there are three possibilities.
1. You can store a bit of text saying this person has already voted
2. You can store a unique id referencing their vote
3. You can store a session cookie and store the rest of the data on the server (probably more secure, since they can't edit the data, only the session id, and doing so will probably invalidate it). | Create unique Poll/vote/survey in php | [
"",
"php",
"survey",
""
] |
I am using thread which will receive messages from the
external application.So my thread shud be alive always.
I want my thread to be running through out the application,
untill application exits. Currently i am calling my thread in program.cs,
which is the startup for windows application c#. Please see the code below
to know how i am doing it.
When i use the below code, the thread starts up when
application starts...But it aborts some how, after the thread recieves
one message from the external application.
I hope i am clear with my questio. Please help. Thanks.
---
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
StartThread();
Application.Run(new Screensaver());
}
public static void StartThread()
{
DeamonEngine Deamon = new DeamonEngine();
Thread ThreadReciever = new Thread(Deamon.Receiver);
if (!(ThreadReciever.IsAlive))
{
ThreadReciever.Start();
}
}
}
```
---
From a comment:
```
void Receiver() {
try {
Initiate socket s;
Bind Ip address;
s.Receiver[bytes];
Access the members of message received in bytes;
Assign the members of message to local variable;
Read Xml File, get the node values and write to batch file;
Execute batch file.
}
catch { }
}
``` | Having a thread execute the Receiver method doesn't mean the thread will repeatedly execute the method.
Given the processing code in the question, `Daemon.Receiver` needs to execute in a loop so that it can go back and retrieve the next message to process. It should look something like this:
```
void Receiver() {
while(!done) // without this loop, only one execution will occur
{
try {
// do stuff
}
catch {
// log/handle error
}
// wait for next message
}
}
``` | Your startup code looks fine: my prognosis is there's something wrong with `DaemonEngine.Receiver()`, perhaps an exception is being thrown, or perhaps the function itself is structured to only handle a single message... Without seeing the exact function it's hard to say.
**EDIT:**
To get my stuff out of my comments:
SOMETHING is going wrong to kill your thread. Exception, logical error, I can't tell you what, because there's no code of what's happening inside your thread, but something is happening. It's nothing to do with the code you've posted already which simply gets the thread running, not keeps it running
Also, from the code you have posted, you're simply throwing away the fact there was an exception... I don't have a link on hand, but swallowing exceptions like that is *horrible*. Especially inside a thread where they don't show up like normal anyway.
There's also no indication of a loop of any kind, so it could be one or both of my suggestions above that is causing problems. | How to keep thread alive throughout the windows application c# | [
"",
"c#",
"windows",
"desktop-application",
""
] |
I'm trying to use DirectSound to capture sound from a microphone. Here's my code:
```
using Microsoft.DirectX.DirectSound;
public MicrophoneSensor()
{
CaptureBufferDescription micBufferDesc = new CaptureBufferDescription();
WaveFormat format = new WaveFormat();
format.SamplesPerSecond = 22000;
format.Channels = 1;
format.BitsPerSample = 8;
format.AverageBytesPerSecond = 22000;
format.BlockAlign = 1;
micBufferDesc.Format = format;
micBufferDesc.BufferBytes = 100000;
micBufferDesc.ControlEffects = false;
micBufferDesc.WaveMapped = true;
micBuffer = new CaptureBuffer(micBufferDesc, microphone);
}
```
The instantiations of the micBufferDesc and format variables cause Visual Studio 2008 to throw the following error:
> The call is ambiguous between the following methods or properties:
> 'Microsoft.DirectX.DirectSound.CaptureBufferDescription.CaptureBufferDescription()'
> and
> 'Microsoft.DirectX.DirectSound.CaptureBufferDescription.CaptureBufferDescription()'
>
> and
>
> The call is ambiguous between the
> following methods or properties:
> 'Microsoft.DirectX.DirectSound.WaveFormat.WaveFormat()'
> and
> 'Microsoft.DirectX.DirectSound.WaveFormet.WaveFormat()'
I've tried quite a few different combinations of stating the namespace and using statements but no luck.
I've also checked the references in the solution explorer and as far as I can tell there are no duplicates.
A brand new test project with only the Microsoft.DirectX.DirectSound reference and nothing else still throws the same error.
I have also uninstalled and reinstalled the DirectX SDK (March 2009) as well as the DirectX SDK (November 2008). Still no luck.
Finally, I've tried a new project on another computer here in the lab and it still doesn't work.
Here are the references I have:
* Graph
* Microsoft.DirectX.DirectSound
* Microsoft.DirectX.DirectInput
* PresentationCore
* PresentationFramework
* Service
* System
* System.Core
* System.Data
* System.Data.DataSetExtensions
* System.Deployment
* System.Drawing
* System.Runtime.Serialization
* System.ServiceModel
* System.Windows.Forms
* System.Xml
* System.Xml.Linq
* UIAutomationProvider
* WindowsBase
* WindowsFormsIntegration | I had the same error, it's not a double reference. Click run and the compiler magically forgets it, or you can stop the annoyance completely with the following.
```
using System.Reflection;
// then instead of WaveFormat fmt = new WaveFormat()
ConstructorInfo constructor = typeof(WaveFormat).GetConstructor(Type.EmptyTypes);
WaveFormat fmt = (WaveFormat)constructor.Invoke(null);
// do the same for CaptureBufferDescription
``` | It sounds like maybe you are referencing multiple versions of the directx assembly. Perhaps double-check your references. If you **need** multiple versions, then `extern alias` may help - but it isn't pretty.
---
In Visual Studio, look for the "solution explorer" (commonly on the right hand side) - this is the tree of everything in your project. One of the items in this tree is the "References". This is a visual representation of the external dlls that your code is configured to make use of.
(there are many, many .NET dlls - you need to tell each project what dlls it might need)
Expand this node, and look for 2 entries that look like directx. If there *are* two, get rid of one of them (ideally the one with the lower version). Then try and rebuild. | C# Ambiguous call in DirectSound | [
"",
"c#",
"visual-studio-2008",
"ambiguous",
""
] |
I need to add a new column to a MS SQL 2005 database with an initial value. However, I do NOT want to automatically create a default constraint on this column. At the point in time that I add the column the default/initial value is correct, but this can change over time. So, future access to the table MUST specify a value instead of accepting a default.
The best I could come up with is:
```
ALTER TABLE tbl ADD col INTEGER NULL
UPDATE tbl SET col = 1
ALTER TABLE tbl ALTER COLUMN col INTEGER NOT NULL
```
This seems a bit inefficient for largish tables (100,000 to 1,000,000 records).
I have experimented with adding the column with a default and then deleting the default constraint. However, I don't know what the name of the default constraint is and would rather not access sysobjects and put in database specific knowledge.
Please, there must be a better way. | I'd `ALTER TABLE tbl ADD col INTEGER CONSTRAINT tempname DEFAULT 1` first,, and drop the *explicitly named* constraint after (presumably within a transaction). | To add the column with a default and then delete the default, you can name the default:
```
ALTER TABLE tbl ADD col INTEGER NOT NULL CONSTRAINT tbl_temp_default DEFAULT 1
ALTER TABLE tbl drop constraint tbl_temp_default
```
This filled in the value 1, but leaves the table without a default. Using SQL Server 2008, I ran this and your code, of `alter update alter` and did not see any noticeable difference on a table of 100,000 small rows. SSMS would not show me the query plans for the alter table statements, so I was not able to compare the resources used between the two methods. | Best way to add a new column with an initial (but not default) value? | [
"",
"sql",
"sql-server",
"database",
"alter-table",
""
] |
I have client/server applications and a very simple protocol for communication. More precisely, it's a set of commands a server sends and a set of requests a client can make.
The idea is as follows:
When a command is made by the server, a client has to execute it.
When a request is made, server checks permissions and if everything is ok it grants the request.
The application is written in C++ and I got slightly stuck designing the architecture for this sort of communication protocol. Assuming that command/request is a tab-delimited string with first parameter being the name of the message, I was planning to make a `MessageManager` class which would store all messages in a hash-table and retrieve them when necessary. The problem here is this:
```
typedef std::vector< std::string > ArgArray;
class Request : public Message
{
public:
Request( const char *name ) : Message( name ) { }
#ifdef CLIENT
/** problem here **/
virtual void make( ... ) = 0;
#elif defined SERVER
virtual void grant( const Client &c, const ArgArray ¶ms ) const = 0;
protected:
virtual void checkPermissions( const Client &c, const ArgArray ¶ms ) const = 0;
#endif
};
```
Because different messages can take different arguments to be constructed I can't really create a complete interface. For example, some messages might need a simple string to be constructed, whereas others might need some numeric data. This complicates things and makes the design a bit untidy... I.e. I have to get round the problem by ommitting `make()` from interface definition and simply add different `make()` for each Request I make. Also, if I wish to store pointers to different Requests in one container I cannot use `dynamic_cast` because `Request` is not a polymorphic type. An obvious (untidy) solution would use `make( int n, ... )` definition and use `stdarg.h` to extract different arguments but I consider this to be unsafe and confusing for the programmer.
There is obviously a design flaw in my idea. I already have a solution in mind but I am just wondering, how would people at SO tackle this problem? What sort of Object architecture would you use? Is there a simpler approach that could solve this problem? There aren't any specific requirements to this except to keep it as simple as possible and to keep the actual protocol as it is (tab-delimited strings with first parameter indicating which message it is). | I think the problem in your design is that you tried to cram too many functionality into one class. For example, the part about constructing/parsing messages to contain numeric data or string (i.e. serialization) should be separate from the underlying connection logic.
Check out [Boost.Serialization](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/index.html) if you are allowed to use additional libraries. Boost has got a very nice network library too called [ASIO](http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio.html). Even if you are not allowed to use boost you should probably consult their library design. | Yes, you say that "command/request is a tab-delimited string": so as kuoson said, it's isn't true that "different messages can take different arguments" ... instead, all messages are being constructed from the tab-delimited string. | Designing a class architecture for network messages | [
"",
"c++",
"oop",
"networking",
"client-server",
""
] |
How to pass information in this flow:
Flash(AS3) -> PHP, using XML -> Database(mysql)
Can anyone write a simple code for that?
Thanks. | <http://www.kirupa.com/developer/actionscript/flashphpxml_integration.htm>
This will tell you most of what you need to know to get started. | If you're not already tied to using XML, you might want to look into using [AMF](http://en.wikipedia.org/wiki/Action_Message_Format). There's a number of OSS implementations of AMF for PHP, from the obviously named [amfphp](http://www.amfphp.org/) to an implementation in the [Zend Framework](http://framework.zend.com/manual/en/zend.amf.html). Hopefully somebody with experience here will come along and provide a better answer. | How to connect these 3 programming languages? | [
"",
"php",
"mysql",
"xml",
"actionscript-3",
""
] |
As most programmers I admire and try to follow the principles of Literate programming, but in C++ I routinely find myself using `std::pair`, for a gazillion common tasks. But `std::pair` is, IMHO, a vile enemy of literate programming...
My point is when I come back to code I've written a day or two ago, and I see manipulations of a `std::pair` (typically as an iterator) I wonder to myself "*what did iter->first and iter->second mean???*".
I'm guessing others have the same doubts when looking at their `std::pair` code, so I was wondering, has anyone come up with some good solutions to recover literacy when using `std::pair`? | How about this:
```
struct MyPair : public std::pair < int, std::string >
{
const int& keyInt() { return first; }
void keyInt( const int& keyInt ) { first = keyInt; }
const std::string& valueString() { return second; }
void valueString( const std::string& valueString ) { second = valueString; }
};
```
It's a bit verbose, however using this in your code might make things a little easier to read, eg:
```
std::vector < MyPair > listPairs;
std::vector < MyPair >::iterator iterPair( listPairs.begin() );
if ( iterPair->keyInt() == 123 )
iterPair->valueString( "hello" );
```
Other than this, I can't see any silver bullet that's going to make things much clearer. | `std::pair` is a good way to make a "local" and essentially anonymous type with essentially anonymous columns; if you're using a certain pair over so large a lexical space that you need to name the type and columns, I'd use a plain `struct` instead. | Literate Coding Vs. std::pair, solutions? | [
"",
"c++",
"literate-programming",
""
] |
What is the most idiomatic way to do the following?
```
def xstr(s):
if s is None:
return ''
else:
return s
s = xstr(a) + xstr(b)
```
**update:** I'm incorporating Tryptich's suggestion to use str(s), which makes this routine work for other types besides strings. I'm awfully impressed by Vinay Sajip's lambda suggestion, but I want to keep my code relatively simple.
```
def xstr(s):
if s is None:
return ''
else:
return str(s)
``` | If you actually want your function to behave like the `str()` built-in, but return an empty string when the argument is None, do this:
```
def xstr(s):
if s is None:
return ''
return str(s)
``` | Probably the shortest would be
`str(s or '')`
Because None is False, and "x or y" returns y if x is false. See [Boolean Operators](http://docs.python.org/library/stdtypes.html#boolean-operations-and-or-not) for a detailed explanation. It's short, but not very explicit. | Most idiomatic way to convert None to empty string? | [
"",
"string",
"python",
"idioms",
""
] |
Which of the following is better and why? (Particular to c++)
a.
```
int i(0), iMax(vec.length());//vec is a container, say std::vector
for(;i < iMax; ++i)
{
//loop body
}
```
b.
```
for( int i(0);i < vec.length(); ++i)
{
//loop body
}
```
I have seen advice for (a) because of the call to length function. This is bothering me. Doesn't any modern compiler do the optimization of (b) to be similar to (a)? | Example (b) has a different meaning to example (a), and the compiler must interpret it as you write it.
If, (for some made-up reason that I can't think of), I wrote code to do this:
```
for( int i(0);i < vec.length(); ++i)
{
if(i%4 == 0)
vec.push_back(Widget());
}
```
I really would not have wanted the compiler to optimise out each call to vec.length(), because I would get different results. | I like:
```
for (int i = 0, e = vec.length(); i != e; ++i)
```
Of course, this would also work for iterators:
```
for (vector<int>::const_iterator i = v.begin(), e = v.end(); i != e; ++i)
```
I like this because it's both efficient (calling `end()` just once), and also relatively succinct (only having to type `vector<int>::const_iterator` once). | c++ for loop temporary variable use | [
"",
"c++",
"for-loop",
""
] |
I am writing a deserialization method that converts xml to a Java object. I would like to do this dynamically and avoid writing hard coded references to specific types.
For example this is a simplified version of one of my classes.
```
public class MyObject {
public ArrayList<SubObject> SubObjects = new ArrayList<SubObject>();
}
```
Here is a stripped down version of the method:
```
public class Serializer {
public static <T> T fromXml(String xml, Class<T> c) {
T obj = c.newInstance();
Field field = obj.getClass().getField("SubObjects");
//help : create instance of ArrayList<SubObject> and add an item
//help#2 : field.set(obj, newArrayList);
return obj;
}
}
```
Calling this method would look like this:
```
MyObject obj = Serializer.fromXml("myxmldata", MyObject.class);
```
Forgive me if this is a trivial problem as I am a C# developer learning Java.
Thanks! | Should be something pretty close to:
```
Object list = field.getType().newInstance();
Method add = List.class.getDeclaredMethod("add",Object.class);
add.invoke(list, addToAddToList);
```
Hope this helps. | It seems like the real issue here is going from XML to java objects. If that is the case (and since you are new to Java), a better solution than rolling your own may be to investigate existing technologies such as:
* [castor](http://www.castor.org/)
* [xstream](http://xstream.codehaus.org/)
* [jaxb](http://en.wikipedia.org/wiki/JAXB) | How to instantiate an ArrayList<?> and add an item through reflection with Java? | [
"",
"java",
"reflection",
"arraylist",
""
] |
I am trying to make an animated clock using Swing in Java. The picture I have posted is a basic idea of what I am looking for. In the end I hope to have the arrow be stationary and the numbers move to indicate the hour, plus I want to have a nested circle with 60 boxes doing the same. I'm not looking for code on how to do this just some tips on how I should get started, links to good tutorials, that kind of thing. Thanks.
---
[](https://i.stack.imgur.com/ZXvX7.png)
---
**edit:** I for got to mention that I'm not actually making a clock, its just the simplest way to explain the premise of what I'm trying to accomplish, to the more general the answers the better. | You could draw it on a [JPanel](http://java.sun.com/javase/6/docs/api/javax/swing/JPanel.html) by overriding the [`paintComponent`](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#printComponent(java.awt.Graphics)) method.
Use a [Timer](http://java.sun.com/javase/6/docs/api/javax/swing/Timer.html) to tick every second to redraw the clock. The timer fires ActionEvents which your panel could listen for.
As for drawing, the center of the boxes with the numbers can be calculated with a bit of trigonometry. For the hour boxes: `x = sin(hour / 12 * 2 * pi)` and `y = cos(hour / 12 * 2 * pi)`. For the minute boxes: `x = sin(minute / 60 * 2 * pi)` and `y = cos(minute / 60 * 2 * pi)`. These will be relative to the center of the clock and will need to be multiplied by some constant. Actually, those equations might not be quite right, but the way to do it is something like that. | This page on [Java 2D](http://java.sun.com/products/java-media/2D/index.jsp) looks like it might be a good place to start. Disclaimer: I've never seriously dealt with Java graphics before. | Where to look to get started with making an animated clock with Swing in Java? | [
"",
"java",
"swing",
"animation",
""
] |
i have some javascript roll over code that works fine in firefox but when i try it in IE i get this error:
> Message: 'document[...]' is null or not an object
> Line: 25
> Char: 13
> Code: 0
> URI: <http://www.jgm-design.com/>
the code im using is:
```
if (document.images)
{
image1 = new Image;
image2 = new Image;
image1.src = "images/logos/logoBlackFadedLow.jpg";
image2.src = "images/logos/logoWhiteFadedLow.jpg";
}
function chgImg(name, image)
{
if (document.images)
{
document[name].src = eval(image+".src");
}
}
```
Any idea why? Or a solution? | The error indicates that the image you're trying to change by name doesn't exist. Unless you post exactly how you're calling the method (chgImg) and what your HTML is, however, I can't really help you specifically.
PS: This is some quite outdated code. It would be a good idea to consider using css :hover pseudo-classes for this problem, as well as finding some more recent javascript to work with. | Aren't you lacking a ".name" => `document.images[name].src = ...` | Javascript error in IE (rollover) | [
"",
"javascript",
"html",
"internet-explorer",
"rollover",
""
] |
I need some help - here are my requirements.
1: I should be able to modify the UML model without affecting the code, and then later apply the changes. This is because I need to print the changes, get them confirmed, and then develop them.
2: I should be able to reuse parts of the model. For example I would create one project which outputs A.dll assembly, and then another UML project would use the classes in the first to crate B.dll
3: Project stored as text so I can see changes in version control history.
4: Together is too expensive :-) | 3 is possible and supported by Visual Studio 2010 Ultimate, which stores all project and model information using XML files. | Visual Studio 2010 Ultimate supports UML class, sequence, component, use case, and activity diagrams, which do not affect your code. It also supports creating sequence and layer diagrams from code. You can then edit these diagrams without affecting the code. Other tools include dependency graphs that you can generate from code as well as Architecture Explorer, which lets you browse and explore your solution. You can create multiple modeling projects in a solution, and you can check these diagrams into Team Foundation version control.
I've posted more links on [my profile](https://stackoverflow.com/users/275715/esther-fan) for more info. | UML tool required for C# | [
"",
"c#",
"uml",
""
] |
I am trying to install ReCaptcha into the user registration of Joomla 1.5. This may just be an issue with Joomla but when i hit register nothing happens. I think it's doing some JavaScript form validation but there is nothing telling the user what went wrong. if, God forbid, they do fill out the form correctly Joomla will redirect the user to the homepage and give no notice of success.
Is this a Joomla issue or is there something wrong with my install? Does anyone know of a plug-in or module for Joomla that would make this easier?
Thanks in advance,
Samuel
UPDATE: Joomla does a lot of "stuff"/"something" to the $\_POST and $\_GET variables which was causing the reCaptcha to not function. This was for work which is past so I am not spending anymore time on it. Shameless Plug: use wordpress instead.
*this can be closed as I don't have time to verify which answer works* | Joomla does a lot of "stuff"/"something" to the $\_POST and $\_GET variables which was causing the reCaptcha to not function. This was for work which is past so I am not spending anymore time on it.
using wordpress from now on. | Are you sure you tried all reCaptcha plugins for Joomla? There are plenty:
<http://extensions.joomla.org/extensions/search/reCaptcha> | Installing Recaptcha in Joomla 1.5 user registration | [
"",
"php",
"joomla",
"joomla1.5",
"recaptcha",
""
] |
How is
```
<None Include="C:\foo.bar" />
```
different from
```
<Content Include="C:\foo.bar" />
```
? | The MSDN article on the [build action](https://learn.microsoft.com/en-us/visualstudio/msbuild/common-msbuild-project-items?view=vs-2019#none) property explains the differences.
> **None** - The file is not included in the project output group and is not compiled in the build process. An example is a text file that contains documentation, such as a Readme file.
>
> **Content** - The file is not compiled, but is included in the Content output group. For example, this setting is the default value for an .htm or other kind of Web file. | One difference is how they get published; "None" items don't get included in a publish, "Content" items do; for example, on the "Application Files" dialog on the Publish tab. | In a .csproj file, what is <None Include="..."> for? | [
"",
"c#",
"csproj",
""
] |
Is there a way to do the following? I [see](https://stackoverflow.com/questions/392083/use-a-global-setting-as-an-attribute-argument) that the Attribute Arguments must be a constant expression, so how would I work around this? If I dont want to load *some* properties into a datagridview using binding, whats the next best alternative?
```
class TestObj
{
private bool isBrowsable = false;
[Browsable(isBrowsable)]
public string String1
{
get
{
return "Foo";
}
}
[Browsable(isBrowsable)]
public string String2
{
get
{
return "Baz";
}
}
}
``` | You can provide dynamic custom type information at runtime by implementing the [ICustomTypeDescriptor](http://msdn.microsoft.com/en-us/library/system.componentmodel.icustomtypedescriptor.aspx) interface - but this is quite a bit of work at not nearly as simple as decorating properties with attributes. | For runtime, I think that you are probably looking at ICustomTypeDescriptor. If it were a compile time decision, you could have used compiler directives:
```
#define ISBROWSABLE
#if ISBROWSABLE
[your attribute]
#endif
``` | C# Dynamic Attribute Arguments | [
"",
"c#",
"properties",
"attributes",
"browsable",
""
] |
I was looking for a way to avoid starting from the head of the list each time I want to find a node, so I thought of assigning indexes to nodes, keeping a pointer to a random (not exactly random; see below) node and then finding the pointer that's closest to the index I want to find. Allow me to explain with code:
```
// head and last are pointers to the first and last items of a doubly-linked list
// current is a pointer that will change over time. It's used as a temporary pointer
template <class T>a
Node<T>* List<T>::get_closest(Node<T> node, int& difference) {
int curr_to_i = current->index - node->index;
int last_to_i = last->index - node->index;
Node* closest = node->index < abs(curr_to_i) ? head : current;
closest = closest->index < abs(last_to_i) ? closest : last;
difference = closest->index - node->index;
return closest;
}
/*
* This functions adds a node with the given value to the given index. The node at that
* index and all the following are moved, and the new node is inserted before them.
*/
template <class T>
bool List<T>::add(T value, int index) {
if (index < 0) { //Invalid index
return false;
} else if (index == last->index +1) {
push(value);
return true;
} else if (index > 0) {
Node* new_n = new Node;
new_n->value = value;
new_n->index = index;
int difference;
Node* closest = get_closest(new_n, difference);
if (difference < 0) {
for (int i = 0; i < abs(difference); i++) {
current = current->previous;
}
} else if (difference > 0) {
for (int i = 0; i < abs(difference); i++) {
current = current->next;
}
} /* current now points to the node we want to move */
new_n->previous = current->previous;
new_n->next = current;
current->previous->next = new_n;
current->previous = new_n;
if (index == 0) {
root = new_n;
}
new_n = new_n->next;
while (new_n != null) {
new_n->index++;
new_n = new_n->next;
}
return true;
}
}
```
Is this more efficient than starting from the head and advancing forward a number of times? | If you need to access elements in the middle of the list, then you're better off using an array. A list is an abstract data structure (ADT) that can be implemented various ways. What you've essentially done is create a redundant representation that has the overhead of both methods.
The advantage of a linked list is that inserts can be very fast at the head of the list - O(1) vs. O(n) for an array. However, since you have to maintain your index, you have O(N) overhead anyways for inserts.
If you need indexing, just use an array. Simpler and faster. | It sounds to me like you're trying to invent [Skip Lists](http://en.wikipedia.org/wiki/Skip_list), which is a sort of balanced, sorted tree.
Probably what you really want is to use something like boost::multi\_index, which will allow you to use a combination of indices to get good performance on a range of operations. One of the [examples](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/tutorial/basics.html#list_fast_lookup) has a very similar feel to what you're trying to do.
Before attempting to use something like this, you should profile your actual uses to determine if there is any real benefit of optimizing that part of your code, and then if it turns out to be a bottleneck, try many different combinations of structures to see which one actually performs the best on your specific use. Unless your data set is quite large, a `std::vector` will almost always be the fastest, because of locality. | Linked List: Is this solution good? | [
"",
"c++",
"algorithm",
"performance",
"linked-list",
""
] |
I've got a CSV file that I'm processing using the opencsv library. So I can read in each line. The particular transformation I need to do requires me to sort that file first before I run through it with the main portion of my java file.
e.g.
```
5423, blah2, blah
5323, blah3, blah
5423, blah4, blah
5444, blah5, blah
5423, blah6, blah
```
should become
```
5323, blah3, blah
5423, blah2, blah
5423, blah4, blah
5423, blah6, blah
5444, blah5, blah
```
etc..
The reason i need to do this is I'm combining all rows with the same id and outputting them to a new file.
Anything wrong with:
1. Read each line of the csv with the opencsv library
2. Add them to a 2 dimensional array
3. Run some sort of sorting on this
4. Loop through sorted array and output to file.
Any other ideas on this and what is the best way to sort the data?
Bit rusty on my Java.
UPDATE:
To Clarify on the final output
It would look like:
```
5323, blah3, blah
5423, blah2!!blah4!!blah6, blah
5444, blah5, blah
```
This is a very simplified version of what I'm doing. It actually is needed for multi option fields in a JBase system. This is the requested file format.
There are over a 100,000 lines in the original file.
This will be run more than once and the speed it runs is important to me. | To accomplish the most recent request, I would highly suggest using [`Multimap`](http://google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/Multimap.html) in the google collection. Your code would look like:
```
CSVReader reader = ...;
CSVWriter writer = ...;
Multimap<String, String> results = TreeMultimap.create();
// read the file
String[] line;
for ((line = reader.readNext()) != null) {
results.put(line[0], line[1]);
}
// output the file
Map<String, Collection<String>> mapView = results.asMap();
for (Map.Entry<String, Collection<String> entry : mapView.entries()) {
String[] nextLine = new String[2];
nextLine[0] = entry.getKey();
nextLine[1] = formatCollection(entry.getValue());
writer.writeNext(nextLine);
}
```
You need to use `"blah\n"` as your line ender. If you care about speed, but not so much about having the entries sorted, you should benchmark against `HashMultimap` as well.
**My previous answer**:
The most straightford way is to use the `sort` command in \*nix (e.g. Linux and Mac OS), like
```
sort -n myfile.csv
```
Windows has a `sort` command as well, but would sort the lines alphabetically (i.e. '5,' would be placed before '13,' lines).
However, there is nothing wrong with the suggested solution. Instead of constructing the array and sorting it, you can also just use [TreeSet](http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html).
EDIT: adding a note about Windows. | Have you tried using `Collections.sort()` and a `Comparator` instance? | Optimal way to sort a txt file in Java | [
"",
"java",
"sorting",
""
] |
I have a simple web.py program to load data. In the server I don't want to install apache or any webserver.
I try to put it as a background service with <http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/>
And subclassing:
(from <http://www.jejik.com/files/examples/daemon.py>)
```
class Daemon:
def start(self):
"""
Start the daemon
"""
... PID CHECKS....
# Start the daemon
self.daemonize()
self.run()
#My code
class WebService(Daemon):
def run(self):
app.run()
if __name__ == "__main__":
if DEBUG:
app.run()
else:
service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid'))
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
service.start()
elif 'stop' == sys.argv[1]:
service.stop()
elif 'restart' == sys.argv[1]:
service.restart()
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
```
However, the web.py software not load (ie: The service no listen)
If I call it directly (ie: No using the daemon code) work fine. | I finally find the problem.
Web.py accept from command-line the optional port number:
```
python code.py 80
```
And the script also take input from the command-line:
```
python WebServer start
```
then web.py try to use "start" as port number and fail. I don't see the error because was in the bacground.
I fix this with a mini-hack:
```
if __name__ == "__main__":
if DEBUG:
app.run()
else:
service = WebService(os.path.join(DIR_ACTUAL,'ElAdministrador.pid'))
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
sys.argv[1] = '8080'
service.start()
``` | you can start the web.py by using this command
```
/usr/bin/python index.py > log.txt 2>&1 &
``` | Run web.py as daemon | [
"",
"python",
"backgroundworker",
""
] |
There are three `Timer` classes that I am aware of, `System.Threading.Timer`, `System.Timers.Timer`, and `System.Windows.Forms.Timer`, but none of these have a `.Reset()` function which would reset the current elapsed time to 0.
Is there a BCL class that has this functionality? Is there a non-hack way of doing it? (I thought perhaps changing the time limit on it might reset it) Thought on how hard it would be to reimplement a `Timer` class that had this functionality, or how to do it reliably with one of the BCL classes? | I always do ...
```
myTimer.Stop();
myTimer.Start();
```
... is that a hack? :)
Per comment, on Threading.Timer, it's the [Change method](https://learn.microsoft.com/en-us/dotnet/api/system.threading.timer.change) ...
> dueTime Type: `System.Int32` The
> amount of time to delay before the
> invoking the callback method specified
> when the Timer was constructed, in
> milliseconds. Specify
> `Timeout.Infinite` to prevent the
> timer from restarting. Specify zero
> (0) to restart the timer immediately. | All the timers have the equivalent of Start() and Stop() methods, except System.Threading.Timer.
So an extension method such as...
```
public static void Reset(this Timer timer)
{
timer.Stop();
timer.Start();
}
```
...is one way to go about it. | How to reset a timer in C#? | [
"",
"c#",
"timer",
""
] |
Hi out there in Stackland. I was wondering if there was either a function or an easy way to change an associative array into an indexed array.
To elaborate, I'm using the Zend framework, and I've got a point in my site where I take out a row of an SQL table as an associative array. I've passed it to javascript via an echoed in JSON. However, I've noticed that I can see the names of my database's columns in Firebug. Having outsiders know the names of your tables and columns is a big security no-no, so I'd like to change it from
```
SQLarray[user_id]
SQLarray[block_id]
SQLarray[b_price] etc.
```
to
```
SQLarray[0]
SQLarray[1]
SQLarray[2] etc.
```
Is there a good way to do this?
It would also work to be able to have a Zend\_Table\_Abstract->fetchAll() return a non-associative array, but I don't think that's possible. Thanks for your help! | Is pure php ok?
```
$array = array_values($array);
```
[Source](http://php.net/manual/en/function.array-values.php) | define function
```
function array_default_key($array) {
$arrayTemp = array();
$i = 0;
foreach ($array as $key => $val) {
$arrayTemp[$i] = $val;
$i++;
}
return $arrayTemp;
}
```
Pass the associative array as a parameter and it will convert into the default index of the array. For example: we have `Array('2014-04-30'=>43,'2014-04-29'=>41)` after the call to the function the array will be `Array(0=>43,1=>41)`. | Change an associative array into an indexed array / get an Zend_Table_Row_Abstract as non-associative | [
"",
"php",
"zend-framework",
"associative-array",
"associative",
""
] |
I have some sql statements that calculates some numbers. It's possible (with bonus points/penalty points) that a person could get a final score OVER 100 (with bonus points) or
UNDER 0 (with penalties).
How can i make sure that the value calculated, if it exceeds 100 it get's maxed at 100. Alternatively, if the score ends up being below 0, then it's min'd at 0.
I'm assuming I could use a simple UDF that does this math - that's not hard. I'm not sure if this already exists?
I checked out [CEILING](http://msdn.microsoft.com/en-us/library/ms189818.aspx) and [MAX](http://msdn.microsoft.com/en-us/library/ms187751.aspx) and both of these are doing other things, not what I'm after.
Thoughts? | Tes, it would be nice if SQL Server had the ANSI-SQL "horizontal" aggregate functions, then you could do exactly what the others have suggested: "*MIN(Score, 100)*", etc. Sadly, it doesn't so you cannot do it that way.
The typical way to do this is with CASE expressions:
```
SELECT
CASE WHEN Score BETWEEN 0 AND 100 THEN Score
WHEN Score < 0 THEN 0
ELSE 100 END as BoundScore
FROM YourTable
``` | Do you mean that the score is stored in a column in a table, or is there some calculated total with these constraints?
In general, probably the easiest would be to put the logic into a trigger that would check to see what value is being inserted, and change it to your max or min if it's out of bounds.
Or, what I would do is use whatever abstraction level is inserting the value do the checking, since it's not a database integrity issue, but an application validation issue. | How do I define my own hardcoded Ceilings and Floors in Sql Server? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I need to invoke a method without knowing a priori what will the amount of arguments be.
I've tried using the member Method.invoke(Object, Object...) passing as second parameter an array of objects which contains my arguments, however that did not really work.
Is there a way to do what I'm after? | The way you describe it is the correct way to do it. Your argument array, however, must have the exact same number of arguments that target method has; they have to be listed in the correct order and have appropriate types. Can you post the exception stack trace you're getting and a code sample? | Once you have the `Method` object, you can use [getParameterTypes()](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Method.html#getParameterTypes()) to determine this. From the JavaDoc:
> Returns an array of Class objects that
> represent the formal parameter types,
> in declaration order, of the method
> represented by this Method object.
> Returns an array of length 0 if the
> underlying method takes no parameters. | Invoke method accepting multiple arguments with arguments array | [
"",
"java",
"reflection",
""
] |
I want to know what actually happens when you annotate a method with `@Transactional`?
Of course, I know that Spring will wrap that method in a Transaction.
But, I have the following doubts:
1. I heard that Spring creates a **proxy class**? Can someone explain this in more **depth**. **What actually resides in that proxy class? What happens to the actual class? And how can I see Spring's created proxied class**
2. I also read in Spring docs that:
> *Note: Since this mechanism is based on proxies, **only 'external' method calls coming in through the proxy will be intercepted**. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with `@Transactional`!*
Source: <http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html>
**Why only external method calls will be under Transaction and not the self-invocation methods?** | This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on [Aspect-Oriented Programming](https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#aop-api) and [Transactions](https://docs.spring.io/spring-framework/docs/current/reference/html/data-access.html#transaction), as Spring's declarative transaction support uses AOP at its foundation.
But at a very high level, Spring creates proxies for classes that declare `@Transactional` on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with `@Transactional`, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.
Transactions in EJB work similarly, by the way.
As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the `this` reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in [this forum post](http://forum.springsource.org/showthread.php?t=11656) in which I use a `BeanFactoryPostProcessor` to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called `me`. Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. `me.someMethod()`.) The forum post explains in more detail.
Note that the `BeanFactoryPostProcessor` code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available. | When Spring loads your bean definitions, and has been configured to look for `@Transactional` annotations, it will create these **proxy objects** around your actual **bean**. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).
However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with `@Transactional`, Spring will create a `TransactionInterceptor`, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the `TransactionInterceptor` (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the `TransactionInterceptor` commits/rolls back the transaction. It's transparent to the client code.
As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.
Does that help? | Spring - @Transactional - What happens in background? | [
"",
"java",
"spring",
"spring-aop",
"spring-jdbc",
"transactional",
""
] |
I've written a method that returns the milisecond value of a string formatted date, and for some reason it's giving me dates 39000 years in the future. any ideas why?
```
private long getTimeInMs(String currentStartTimeString) {
//String newDateString = currentStartTimeString.substring(6,10)+"-"+currentStartTimeString.substring(3, 5)+"-"+currentStartTimeString.substring(0, 2)+ "T" + currentStartTimeString.substring(11);
String newDateString = currentStartTimeString.substring(0,19);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long timeInMs;
try {
timeInMs = df.parse(newDateString).getTime();
} catch (ParseException e) {
log.error("Failed to parse current Start Time",e);
return 0;
}
return timeInMs;
}
```
If I enter the date string "2009-07-07 10:51:01.15" it returns 1246960261000 which is actually Wed Aug 06 41484 11:16:40 GMT+0100 (GMT Daylight Time)
Okay I think the issue is that it's giving ms past the Java epoc and I'm evaluating it against the unix epoch... | I'm guessing that you interpreted the returned value from getTime() as if it was a Unix time\_t value. It's not - it's milliseconds past the Java epoch, not seconds past the Unix epoch. | It looks fine to me. The Date object that comes out of the parse toString's to "Tue Jul 07 10:51:01 BST 2009" (I'm in the UK timezone here), but that should make no big difference). The millis value of 1246960261000 is correct, why do you think that evaluates to the far future? How did you calculate that? | Why is this code giving me a date 39k years in the future? | [
"",
"java",
"datetime",
""
] |
I am having an argument with a developer colleague on the team.
Problem: SQL query X runs for 1 second on the test system, but for an unknown amount of time on live system (150 users can run queries at the same time).
The query causes locks on 8 tables, of which 7 are useless.
His idea is to put a WITH (NOLOCK) on the 7 tables so there aren't any more locks.
My argument:
My suggestion is, with a nolock there is the chance that user 1 runs the select query which needs 10 seconds to complete because the server performance is low at the moment and user 2 changes a value in one of the 7 tables, e.g. a customer.
Then the query would be completely wrong or maybe the expected dataset can't be filled and it crashes and throws an error. So use a Rowlock.
His argument:
We don't need a rowlock, the chances of getting such a scenario are too low. We don't need to be perfect. Do what is asked of you and don't think.
What can I say to win against such people who don't count on perfectionism? | I believe, based on what you have said that you are correct in your reasoning.
If there is ANY chance that something could go wrong, no matter how small a chance in the operation that causes the database to lose integrity it MUST be fixed.
Integrity is one of the basic premises of database design your co worker sounds like he is not being rigorous in his work.
If you are trying to construct a technical argument to "beat" your co worker, note that it may not give you the desired outcome you imagine.
If your co worker is not amenable to what you are saying AND if you are REALLY sure that you are correct in your reasoning, then I would inform your team leader why you think this is important and show him your solution. If he agrees with your co worker because he believes that database integrity is not important, then perhaps you should look at working somewhere else.
Don't get me wrong, I realise that in the real world software cannot be 'perfect' otherwise it would never be released. But something as fundamental as data input checking should not be skipped over, and it isn't difficult to do. It's basically the same as saying, "well let's not bother to validate user input". This is something you learn how to do this in a first year Computer Science class!
We have enough crappy software on this planet and this is the age where we are capable of AMAZING THINGS. Sloppiness in Software Engineering doesn't have a place anymore and I hope that you do not let your co worker lower your standards. Keep your standards high and you will learn more than he does and eventually do better in the long run. | Locking hints in SQL Server 2000 (SS2k) were useful because SS2k was greedy about locking on UPDATE statements and would default to TABLELOCK and narrow it as it progressed. If you knew your UPDATE statement's pattern you could use locking hints to increase performance and SS2k would escalate the lock if needed.
NOLOCK was introduced for dirty reads of locked data. If a table is frequently updated and queries that don't rely on the validity of the underlying data are being blocked, you could use NOLOCK to read the data in whatever state it was in. If you need to read records to generate a search results page you might choose to specify the NOLOCK hint to ensure your query isn't blocked by any update statements.
I believe lock escalation was reworked in SQL Server 2005 and locking hints are no longer respected. | SQL Query with Table Locking | [
"",
"sql",
"locking",
""
] |
For quite a simple table structure, ie. Person, Criteria, and PersonCriteria
(the combi-table), I have set up a query at the moment that selects all persons that possess all selected criteria.
The query itself looks like this at the moment:
```
SELECT
p.PersonID
FROM
Person p,
( SELECT DISTINCT PersonID, CriteriaID
FROM PersonCriteria
WHERE CriteriaID in (#list_of_ids#)
) k
WHERE
p.PersonID= k.PersonID
GROUP BY
p.PersonID
HAVING
Count(*) = #Listlength of list_of_ids#
```
So far no problem and everything works fine.
Now I want to offer the possibility for the user to add some AND and OR variables in their search, ie. someone could say:
> I'm looking for a person that possesses: Criteria 1 AND 3 AND 4
> (which would be covered by the query above) AND (5 OR 6 OR 7) AND (8 OR 9) and so on...
I'm not sure where to start with this additional level. I hope someone else does..:-) | I have to say - I'm stumped. I cannot think of any solution that would come even close. I would try looking for a solution in these directions:
* User-defined aggregate functions. Maybe you can make a function that takes as an argument the desired expression (in a simplified syntax) and the rows for a single person. The function then parses the expression and matches it against the rows. Hmm... maybe MySQL includes some concatenating aggregate function and a regex matching function? This might be a solution then (though probably not a very fast one).
* Analytic functions. I don't pretend that I understand them, but as much as I know about them, I think they are generally in this direction. Although I don't know if there will be a function that will suit this need.
**Added:**
Ahh, I think I got it! Although I think the performance will be miserable. But this will work! For example, if you have the requirement to search for `1 AND 2 AND (3 OR 4)` then you would write:
```
SELECT
*
FROM
Persons A
WHERE
EXISTS (Select * from PersonCriteria B WHERE A.PersonID=B.PersonID AND CriteriaID=1)
AND
EXISTS (Select * from PersonCriteria B WHERE A.PersonID=B.PersonID AND CriteriaID=2)
AND
(
EXISTS (Select * from PersonCriteria B WHERE A.PersonID=B.PersonID AND CriteriaID=3)
OR
EXISTS (Select * from PersonCriteria B WHERE A.PersonID=B.PersonID AND CriteriaID=4)
)
```
**Added 2:** Here's another one, though the performance will likely be even worse:
```
SELECT p.* FROM Person p
JOIN (select PersonID from PersonCriteria WHERE CriteriaID=1) c1 ON p.PersonID=c1.PersonID
JOIN (select PersonID from PersonCriteria WHERE CriteriaID=2) c2 ON p.PersonID=c2.PersonID
JOIN (select PersonID from PersonCriteria WHERE CriteriaID IN (3,4)) c3 ON p.PersonID=c3.PersonID
```
**Added 3:** This is a variation of No. 2, but this might actually have a chance of a decent performance!
```
SELECT p.* FROM
Person p
JOIN PersonCriteria c1 on (p.PersonID=c1.PersonID AND c1.CriteriaID=1)
JOIN PersonCriteria c2 on (p.PersonID=c2.PersonID AND c2.CriteriaID=2)
JOIN PersonCriteria c3 on (p.PersonID=c3.PersonID AND c3.CriteriaID IN (3,4))
```
If you add an index to PersonCriteria on columns (PersonID,CriteriaID) (exactly in this order!), then I think it's about as fast as you're going to get in any case. | You can simplify this a lot, for instance by doing:
SELECT DISTINCT
PersonID
FROM PersonCriteria
WHERE
CriteriaID IN (1,2) OR
CriteriaID IN (8,9)
Also consider using JOIN's instead of sub-selects (for performance) | Advanced (?) AND / OR query | [
"",
"sql",
"mysql",
""
] |
I have the following program to open lot's of sockets, and hold them open to stress test one of our servers. There are several problem's with this. I think it could be a lot more efficient than a recursive call, and it's really still opening sockets in a serial fashion rather than parallel fashion. I realize there are tools like ab that could probably simulate what I'm trying to do, but I'm hoping to increase my python knowledge. Is this something I should be rewriting as either multi-threaded or multi-process?
```
> #!/usr/bin/env python
>
> import socket, time, sys
> sys.setrecursionlimit(2000)
>
> def open_socket(counter):
> sockname = "s" + str(counter)
> port = counter + 3000
> sockname = socket.socket()
> sockname.bind(('localhost', port))
> sockname.listen(1)
> if counter == 2:
> time.sleep(20)
> elif counter > 2:
> counter = counter -1
> open_socket(counter)
>
> open_socket(1500)
``` | I was puzzled why you would use recursion instead of a simple loop. My guess is that with a simple loop, you would have overwritten the variable sockname again and again, so that Python's garbage collection would actually close the previous socket after you created the next one. The solution is to store them all in a list, to prevent Python from garbage-collecting them:
```
def open_socket(counter):
sockets = []
for i in range(counter):
s = socket.socket()
s.bind(('localhost', i+3000))
s.listen(1)
sockets.append(s)
time.sleep(20)
```
Also notice that in your code, the first assignment to sockname is completely redundant, as it is overwritten by the second assignment. | You can try using Twisted for this. It greatly simplifies networking on Python. Their site has [some tutorials](http://twistedmatrix.com/projects/core/documentation/howto/index.html) to get you started.
However, you could easily see using Python an overkill for this task. A faster option to hack up would be to just open 1500 instances of nc:
```
for i in {3000..4500};
do
nc -l -p $i &
done
``` | Python: better way to open lots of sockets | [
"",
"python",
"sockets",
""
] |
How do I know which is the current folder of an App?
I mean... Is there a way to know where is the exe located from the running code? | ```
string fullAppName = Assembly.GetCallingAssembly().GetName().CodeBase;
string fullAppPath = Path.GetDirectoryName(fullAppName);
``` | Windows Mobile doesn't have the concept of a current folder. The "current folder" is basically always set to be the root of the filesystem, no matter where your application is located.
To get the path your application is located, you can use `Assembly.GetExecutingAssembly()`, and the `CodeBase` property or `GetName()` method | Compact Framework Current Folder | [
"",
"c#",
"vb.net",
"windows-mobile",
"compact-framework",
""
] |
When an exe file is run it prints out some stuff. I'm trying to run this on some numbers below and print out line 54 ( = blah ). It says process isn't defined and I'm really unsure how to fix this and get what I want printed to the screen. If anyone could post some code or ways to fix this thank you so very much!
```
for j in ('90','52.62263','26.5651','10.8123'):
if j == '90':
k = ('0',)
elif j == '52.62263':
k = ('0', '72', '144', '216', '288')
elif j == '26.5651':
k = (' 324', ' 36', ' 108', ' 180', ' 252')
else:
k = (' 288', ' 0', ' 72', ' 144', ' 216')
for b in k:
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
blah = outputlist[53]
cmd = ' -j ' + str(j) + ' -b ' + str(b) + ' blah '
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
print cmd
```
I am trying to print out for example:
-j 90 -az 0 (then what blah contains) blah is line 54. Line 54 prints out a lot of information. Words mostly. I want to print out what line 54 says to the screen right after
-j 90 -az 0
@ Robbie: line 39
```
blah = outputlist[53]
```
Indexerror: list index out of range
@ Robbie again. Thanks for your help and sorry for the trouble guys...
I even tried putting in outputlist[2] and it gives same error :/ | I can't help but clean that up a little.
```
# aesthetically (so YMMV), I think the code would be better if it were ...
# (and I've asked some questions throughout)
j_map = {
90: [0], # prefer lists [] to tuples (), I say...
52.62263: [0, 72, 144, 216, 288],
26.5651: [324, 36, 108, 180, 252],
10.8123: [288, 0, 72, 144, 216]
}
# have a look at dict() in http://docs.python.org/tutorial/datastructures.html
# to know what's going on here -- e.g. j_map['90'] is ['0',]
# then the following is cleaner
for j, k in j_map.iteritems():
# first iteration j = '90', k=[0]
# second iteration j = '52.62263'', k= [0,...,288]
for b in k:
# fixed the ordering of these statements so this may actually work
cmd = "program_name -j %f -b %d" % (j, b)
# where program_name is the program you're calling
# be wary of the printf-style %f formatting and
# how program_name takes its input
print cmd
process = Popen(cmd, shell=True, stderr=STDOUT, stdout=PIPE)
outputstring = process.communicate()[0]
outputlist = outputstring.splitlines()
blah = outputlist[53]
```
You need to define cmd -- right now it's trying to execute something like " -j 90 -b 288". I presume you want something like **cmd = "program\_name -j 90 -b 288"**.
Don't know if that answers your question at all, but I hope it gives food for thought. | Are you sure this is right
```
cmd = ' -j ' + str(el) + ' -jk ' + str(az) + ' blah '
```
Where's your executable? | for statement in python | [
"",
"python",
""
] |
I am writing a program that uses prints a hex dump of its input. However, I'm running into problems when newlines, tabs, etc are passed in and destroying my output formatting.
How can I use printf (or cout I guess) to print '\n' instead of printing an actual newline? Do I just need to do some manual parsing for this?
EDIT: I'm receiving my data dynamically, it's not just the \n that I'm corned about, but rather all symbols. For example, this is my printf statement:
```
printf("%c", theChar);
```
How can I make this print \n when a newline is passed in as theChar but still make it print normal text when theChar is a valid printable character? | Print "\\n" – "\\" produces "\" and then "n" is recognized as an ordinary symbol. For more information see [here](http://en.cppreference.com/w/cpp/language/escape). | The function `printchar()` below will print some characters as "special", and print the octal code for characters out of range (a la Emacs), but print normal characters otherwise. I also took the liberty of having `'\n'` print a real `'\n'` after it to make your output more readable. Also note that I use an `int` in the loop in `main` just to be able to iterate over the whole range of `unsigned char`. In your usage you would likely just have an `unsigned char` that you read from your dataset.
```
#include <stdio.h>
static void printchar(unsigned char theChar) {
switch (theChar) {
case '\n':
printf("\\n\n");
break;
case '\r':
printf("\\r");
break;
case '\t':
printf("\\t");
break;
default:
if ((theChar < 0x20) || (theChar > 0x7f)) {
printf("\\%03o", (unsigned char)theChar);
} else {
printf("%c", theChar);
}
break;
}
}
int main(int argc, char** argv) {
int theChar;
(void)argc;
(void)argv;
for (theChar = 0x00; theChar <= 0xff; theChar++) {
printchar((unsigned char)theChar);
}
printf("\n");
}
``` | How to print '\n' instead of a newline? | [
"",
"c++",
"formatting",
"printf",
"cout",
""
] |
I am currently working on fixing a c# codebase which does not have a good pattern of Dispose usage.
It is a large codebase, it is a resource demanding codebase and it uses many custom unmanaged c++ libraries at the low level.
I have a good understanding of the dispose pattern. I have spent some time understanding what I believe to be the gold standard article on the issue: [Joe Duffy's dispose article](http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae)
In an attempt to minimise code duplication, we have been considering some dispose helper classes, and so my question:
**If a base class implements a standard Dispose pattern should it allow its disposed flag to be shared ie. marked as protected?**
To clarify I mean should there only be a single boolean state within an inheritance heirarchy that defines whether an object instance has been disposed or should there be a private boolean at each step of the inheritance ladder?
The examples in MSDN and at the above link set a flag at each level, but never explain the reasoning behind it. I am in two minds on the issue, what are your thoughts and reasons? | I would say no it should not share the flag. Sharing the flag creates opportunities for failure which better encapsulation could prevent.
For instance, consider the scenario where you have a readonly Disposed property on the base most class. The backing field is only set to true in the Dispose(disposing) method on the base class. This means that the property Disposed can only ever return true if the base class Dispose is called (barring evil reflection of course). This allows the base class to provide an enforceable contract.
Now consider the opposite, where there is a protected setter. Any class can now arbitrarily set the Disposed property to true without disposing anything. This creates an opportunity for Dispose to return true when nothing is disposed.
I would choose the first option because it provides the most enforceable contract. | I would recommend having a Disposed property on the base class with a public getter and a protected setter. | In an IDisposable pattern should a base class allow derived classes to share its disposed flag? | [
"",
"c#",
".net",
"idisposable",
""
] |
Most C++ programmers like me have made the following mistake at some point:
```
class C { /*...*/ };
int main() {
C c(); // declares a function c taking no arguments returning a C,
// not, as intended by most, an object c of type C initialized
// using the default constructor.
c.foo(); // compiler complains here.
//...
}
```
Now while the error is pretty obvious once you know it I was wondering if there is any sensible use for this kind of local function declaration except that you can do it -- especially since there is no way to *define* such a local function in the same block; you have to define it elsewhere.
I think that Java-style local classes are a pretty nice feature which I tend to use often, especially the anonymous sort. Even local C++ classes (which can have inline-defined member functions) have some use. But this local function declaration without definition thing seems very awkward to me. Is it just a C-legacy or is there some deeper use case which I am not aware of?
**Edit** for the non-believers: `C c()` is *not* a function pointer declaration.
This program
```
int main()
{
void g();
cout << "Hello ";
g();
return 0;
}
void g()
{
cout << "world." << endl;
}
```
outputs `Hello world.` This program
```
void fun()
{
cout << "world." << endl;
}
int main()
{
void g();
g = fun;
cout << "Hello ";
g();
return 0;
}
```
does not compile. gcc complains:
```
error: cannot convert 'void ()()' to 'void ()()' in assignment
```
comeau:
```
error: expression must be a modifiable lvalue
``` | I've wanted local function declarations in C when I wanted to pass them as arguments to some other function. I do this all the time in other languages. The reason is to encapsulate the implementation of data structures.
E.g. I define some data structure, e.g. a tree or a graph, and I don't want to expose the details of its internal implementation, e.g. because I may want to change or vary it. So I expose accessor and mutator functions for its elements, and a traversal function to iterate over the elements. The traversal function has as its argument a function that operates on an element; the traversal function's task is to execute the argument function on each element and possibly aggregate the results in some way. Now when I call the traversal function, the argument function is usually some specialized operation that depends on local state and therefore should be defined as a local function. Having to push the function, with the variables that contain the local state, outside to be global, or into an inner class created specifically to hold them, is butt ugly. But this is a problem I have with C and Java, not with C++. | The only use I can think of is to reduce the scope of function declarations:
```
int main()
{
void doSomething();
doSomething();
return 0;
}
void otherFunc()
{
doSomething(); // ERROR, doSomething() not in scope
}
void doSomething()
{
...
}
```
Of course, there are much better solutions to this. If you need to hide a function, you should really restructure your code by moving functions into separate modules so that the functions which need to call the function you want to hide are all in the same module. Then, you can make that function module-local by declaring it static (the C way) or by putting it inside an anonymous namespace (the C++ way). | Is there any use for local function declarations? | [
"",
"c++",
"function",
"definition",
"local",
""
] |
Thank you one and all ahead of time.
I am currently in the process of tweaking/improving a MVC framework I wrote from scratch for my company. It is relatively new, so it is certainly incomplete. I need to incorporate error handling into the framework (everything should have access to error handling) and it should be able to handle different types and levels of errors (User errors and Framework errors). My question is what is the best way and best mechanism to do this? I know of PHP 5 exception handling and PEAR's different error mechanism, but I have never used any of them. I need something efficient and easy to use.
Would it be better to create my own error handling or use something already made? Any suggestions, tips, questions are certainly welcomed. I would ultimately think it sweetness to somehow register the error handler with PHP so that I would just need to throw the error and then decide what to do with it and whether to continue.
EDIT: Sorry, I should of provided a more details about what type of errors I wanted to log. I am looking to log 2 main types of errors: User and Framework.
For user errors, I mean things like bad urls (404), illegal access to restricted pages, etc. I know I could just reroute to the home page or just blurt out a JavaScript dialog box, but I want to be able to elegently handle these errors and add more user errors as they become evident.
By Framework errors I means things like cannot connect to the database, someone deleted a database table on accident or deleted a file somehow, etc.
Also, I will take care of development and live server handling. | > I would ultimately think it sweetness
> to somehow register the error handler
> with PHP so that I would just need to
> throw the error and then decide what
> to do with it and whether to continue.
You can do exactly that, with [set\_error\_handler()](http://us.php.net/set_error_handler) and [set\_exception\_handler()](http://us.php.net/set_exception_handler).
There is no "one right way" to do error handling, but here are some things to consider.
* trigger\_error() is similar to throw new Exception in that they both escape out of the current execution immediately, only trigger\_error() is not catchable.
* How do you want errors handled on a dev environment (show on screen?) versus in a production environment (logged and emailed?)
* You can use the above functions to essentially "convert" errors into exceptions, or vice versa
* Not all error types can be handled with a custom error handler | Here's some things that I usually do:
* Use a global configuration setting or flag to switch between development and production.
* Don't use php errors when you have a choice: Prefer exceptions for your own error handeling. If you're using a library that doesn't use exceptions, detect the errors and throw your own exceptions.
* Use a top level exception catcher that displays exceptions in a way that's easy to read. If you place this try-catch-block strategically, you don't have to register a global exception handler.
* Always develop with `error_handeling(E_ALL | E_STRICT)`
* Catch PHP warnings and notices using `set_error_handler()`, and halt execution. This elimates a lot of bugs in advance, with very solid code as a result.
* The global error handeling code should be very light-weight, in order to avoid errors. There's always a risk for recursion when dealing with global error handlers.
* If the system is in production mode, don't display any details: Log the error, and generate a unique identifier that the user can refer to if they want to file a bug or report the error. | PHP Error handling | [
"",
"php",
""
] |
How do I databind a single TextBlock to say "Hi, Jeremiah"?
```
<TextBlock Text="Hi, {Binding Name, Mode=OneWay}"/>
```
Looking for an elegant solution. What is out there? I'm trying to stay away from writing a converter for each prefix/suffix combination. | If you've only got a single value you need to insert, you can use Binding's [StringFormat](https://learn.microsoft.com/en-us/dotnet/api/system.windows.data.bindingbase.stringformat) property. Note that this **requires .NET 3.5 SP1** (or .NET 3.0 SP2), so only use it if you can count on your production environment having the latest service pack.
```
<TextBlock Text="{Binding Name, Mode=OneWay, StringFormat='Hi, {0}'}"/>
```
If you wanted to insert two or more different bound values, I usually just make a StackPanel with Orientation="Horizontal" that contains multiple TextBlocks, for example:
```
<StackPanel Orientation="Horizontal">
<TextBlock Text="Good "/>
<TextBlock Text="{Binding TimeOfDay}"/>
<TextBlock Text=", "/>
<TextBlock Text="{Binding Name}"/>
<TextBlock Text="!"/>
</StackPanel>
``` | I think this should do it.
```
<TextBlock>
<TextBlock Text="Hi, " />
<TextBlock Text="{Binding Name, Mode=OneWay}" />
</TextBlock>
``` | How do I properly add a prefix (or suffix) to databinding in XAML? | [
"",
"c#",
"wpf",
"xaml",
"data-binding",
""
] |
I am working on a codebase that uses php within .html files. How do I tell VIM to highlight php correctly in .html files without renaming all of my .html to .php? | Alec led me in the right direction as to what to look for, but I was looking for a hardcoded solution in the vimrc file. I went ahead with this:
```
augroup filetype
autocmd BufNewFile,BufRead <Directory Path>/*.html set filetype=php
augroup END
```
This changes all files within the codebase to php for highlighting | Perhaps with `:set filetype`?
[<http://vimdoc.sourceforge.net/htmldoc/usr_06.html>](http://vimdoc.sourceforge.net/htmldoc/usr_06.html) | Highlight PHP syntax in .html extensions in VIM | [
"",
"php",
"vim",
""
] |
All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a variable to do with as I please. | Use:
```
window.location.href
```
As noted in the comments, the line below works, but it is bugged for Firefox.
```
document.URL
```
See **[URL of type DOMString, readonly](https://web.archive.org/web/20170327080647/http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-46183437)**. | **URL Info Access**
JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser's address bar. All these methods use the [`Location` object](https://developer.mozilla.org/en-US/docs/Web/API/Location), which is a property of the `Window` object. You can read the current `Location` object by reading [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/Window/location):
```
var currentLocation = window.location;
```
**Basic URL Structure**
```
<protocol>//<hostname>:<port>/<pathname><search><hash>
```
* **protocol:** Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
* **hostname:** Host name specifies the host that owns the resource. For example, `www.stackoverflow.com`. A server provides services using the name of the host.
* **port:** A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
* **pathname:** The path gives info about the specific resource within the host that the Web client wants to access. For example, `/index.html`.
* **search:** A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
* **hash:** The anchor portion of a URL, includes the hash sign (#).
With these `Location` object properties you can access all of these URL components and what they can set or return:
* **href** - the entire URL
* **protocol** - the protocol of the URL
* **host** - the hostname and port of the URL
* **hostname** - the hostname of the URL
* **port** - the port number the server uses for the URL
* **pathname** - the path name of the URL
* **search** - the query portion of the URL
* **hash** - the anchor portion of the URL
* [**origin**](https://developer.mozilla.org/en-US/docs/Web/API/Location/origin) - the `window.location.protocol + '//' + window.location.host` | Get the current URL with JavaScript? | [
"",
"javascript",
"url",
""
] |
Given two strings `text1` and `text2`:
```
public SOMEUSABLERETURNTYPE Compare(string text1, string text2)
{
// DO SOMETHING HERE TO COMPARE
}
```
Examples:
1. First String: StackOverflow
Second String: StaqOverflow
Return: Similarity is 91%
The return can be in % or something like that.
2. First String: The simple text test
Second String: The complex text test
Return: The values can be considered equal
Any ideas? What is the best way to do this? | There are various different ways of doing this. Have a look at the [Wikipedia "String similarity measures" page](http://en.wikipedia.org/wiki/Category:String_similarity_measures) for links to other pages with algorithms.
I don't *think* any of those algorithms take sounds into consideration, however - so "staq overflow" would be as similar to "stack overflow" as "staw overflow" despite the first being more similar in terms of pronunciation.
I've just found [another page](http://www.dcs.shef.ac.uk/~sam/stringmetrics.html) which gives rather more options... in particular, the [Soundex](http://www.dcs.shef.ac.uk/~sam/stringmetrics.html#soundex) algorithm ([Wikipedia](http://en.wikipedia.org/wiki/Soundex)) may be closer to what you're after. | [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) is probably what you're looking for. | How can I measure the similarity between 2 strings? | [
"",
"c#",
"string",
"comparison",
"phonetics",
""
] |
I have an url like this:
> <http://www.w3schools.com/PHP/func_string_str_split.asp>
I want to split that url to get the host part only. For that I am using
```
parse_url($url,PHP_URL_HOST);
```
it returns www.w3schools.com.
I want to get only 'w3schools.com'.
is there any function for that or do i have to do it manually? | There are many ways you could do this. A simple replace is the fastest if you know you always want to strip off 'www.'
```
$stripped=str_replace('www.', '', $domain);
```
A regex replace lets you bind that match to the start of the string:
```
$stripped=preg_replace('/^www\./', '', $domain);
```
If it's always the first part of the domain, regardless of whether its www, you could use explode/implode. Though it's easy to read, it's the most inefficient method:
```
$parts=explode('.', $domain);
array_shift($parts); //eat first element
$stripped=implode('.', $parts);
```
A regex achieves the same goal more efficiently:
```
$stripped=preg_replace('/^\w+\./', '', $domain);
```
Now you might imagine that the following would be more efficient than the above regex:
```
$period=strpos($domain, '.');
if ($period!==false)
{
$stripped=substr($domain,$period+1);
}
else
{
$stripped=$domain; //there was no period
}
```
But I benchmarked it and found that over a million iterations, the `preg_replace` version consistently beat it. Typical results, normalized to the fastest (so it has a unitless time of 1):
* Simple str\_replace: 1
* preg\_replace with `/^\w+\./`: 1.494
* strpos/substr: 1.982
* explode/implode: 2.472
The above code samples always strip the first domain component, so will work just fine on domains like "www.example.com" and "www.example.co.uk" but not "example.com" or "www.department.example.com". If you need to handle domains that may already be the main domain, or have multiple subdomains (such as "foo.bar.baz.example.com") and want to reduce them to just the main domain ("example.com"), try the following. The first sample in each approach returns only the last two domain components, so won't work with "co.uk"-like domains.
* `explode`:
```
$parts = explode('.', $domain);
$parts = array_slice($parts, -2);
$stripped = implode('.', $parts);
```
Since `explode` is consistently the slowest approach, there's little point in writing a version that handles "co.uk".
* regex:
```
$stripped=preg_replace('/^.*?([^.]+\.[^.]*)$/', '$1', $domain);
```
This captures the final two parts from the domain and replaces the full string value with the captured part. With multiple subdomains, all the leading parts get stripped.
To work with ".co.uk"-like domains as well as a variable number of subdomains, try:
```
$stripped=preg_replace('/^.*?([^.]+\.(?:[^.]*|[^.]{2}\.[^.]{2}))$/', '$1', $domain);
```
* str:
```
$end = strrpos($domain, '.') - strlen($domain) - 1;
$period = strrpos($domain, '.', $end);
if ($period !== false) {
$stripped = substr($domain,$period+1);
} else {
$stripped = $domain;
}
```
Allowing for co.uk domains:
```
$len = strlen($domain);
if ($len < 7) {
$stripped = $domain;
} else {
if ($domain[$len-3] === '.' && $domain[$len-6] === '.') {
$offset = -7;
} else {
$offset = -5;
}
$period = strrpos($domain, '.', $offset);
if ($period !== FALSE) {
$stripped = substr($domain,$period+1);
} else {
$stripped = $domain;
}
}
```
The regex and str-based implementations can be made ever-so-slightly faster by sacrificing edge cases (where the primary domain component is a single letter, e.g. "a.com"):
* regex:
```
$stripped=preg_replace('/^.*?([^.]{3,}\.(?:[^.]+|[^.]{2}\.[^.]{2}))$/', '$1', $domain);
```
* str:
```
$period = strrpos($domain, '.', -7);
if ($period !== FALSE) {
$stripped = substr($domain,$period+1);
} else {
$stripped = $domain;
}
```
Though the behavior is changed, the rankings aren't (most of the time). Here they are, with times normalized to the quickest.
* multiple subdomain regex: 1
* .co.uk regex (fast): 1.01
* .co.uk str (fast): 1.056
* .co.uk regex (correct): 1.1
* .co.uk str (correct): 1.127
* multiple subdomain str: 1.282
* multiple subdomain explode: 1.305
Here, the difference between times is so small that it wasn't unusual for . The fast .co.uk regex, for example, often beat the basic multiple subdomain regex. Thus, the exact implementation shouldn't have a noticeable impact on speed. Instead, pick one based on simplicity and clarity. As long as you don't need to handle .co.uk domains, that would be the multiple subdomain regex approach. | You have to strip off the subdomain part by yourself - there is no built-in function for this.
```
// $domain beeing www.w3scools.com
$domain = implode('.', array_slice(explode('.', $domain), -2));
```
The above example also works for subdomains of a unlimited depth as it'll alwas return the last two domain parts (domain and top-level-domain).
If you only want to strip off *www.* you can simply do a [`str_replace()`](http://de.php.net/manual/en/function.str-replace.php), which will be faster indeed:
```
$domain = str_replace('www.', '', $domain);
``` | Url splitting in php | [
"",
"php",
""
] |
Horrible title I know, horrible question too. I'm working with a bit of software where a dll returns a ptr to an internal class. Other dlls (calling dlls) then use this pointer to call methods of that class directly:
```
//dll 1
internalclass m_class;
internalclass* getInternalObject() {
return &m_class;
}
//dll 2
internalclass* classptr = getInternalObject();
classptr->method();
```
This smells pretty bad to me but it's what I've got... I want to add a new method to internalclass as one of the calling dlls needs additional functionality. I'm certain that all dlls that access this class will need to be rebuilt after the new method is included but I can't work out the logic of why.
My thinking is it's something to do with the already compiled calling dll having the physical address of each function within internalclass in the other dll but I don't really understand it; is anyone here able to provide a concise explanation of how the dlls (new internal class dll, rebuilt calling dll and calling dll built with previous version of the internal class dll) would fit together?
Thanks,
Patrick | The client dll's 'learn' the actual address of the class' functions at load-time by looking at the export table of the serving dll. So as long as the export table stays compatible, no harm is done.
Compatibility will be broken when your class has a virtual function table, and the functions in it change order. It will also break when linking by ordinal instead of by symbol. | You should have returned a ptr to a derived class object as a base class type. Then you can change the derived class freely. Can't change the base class though.
Edit: you may be able to change it a bit. But carefully. Adding methods should work (unless they are virtual). Adding variables may work if you add them at the end. | C++ Changing a class in a dll where a pointer to that class is returned to other dlls | [
"",
"c++",
"dll",
""
] |
I had some code that ran commands through **Runtime.getRuntime.exec(String)**, and it worked on Windows. When I moved the code to Linux, it broke, and the only way of fixing it was to switch to the **exec(String[])** version. If I leave things this way, will the code work the same on Windows and Linux, or should I use the exec(String) on Windows and exec(String[]) on Linux? | Use **String[]** on both.
The answer I [gave you before](https://stackoverflow.com/questions/1080578/i-dont-understand-why-this-classnotfoundexception-gets-thrown/1080800#1080800) was the result of several miserable hours of debugging a production software running on windows.
After a lot of effort we ( I ) came to the solution posted before ( use **String[]** )
Since the problems you've got were on Linux, I guess using the array on both will be the best.
BTW. I tried that method with Java 1.4, Since then a new class is available: [ProcessBuilder](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html) added on Java1.5. I'm not sure what is that all about, but there should be a good reason for it. Take a look at it and read what the difference between that an Runtime.exec is. Probably it will be a better option.
Finally some commands won't work on either platform because they are built in with the shell ( either Windows cmd or bash/sh/ etc ) such as *dir* or *echo* and some of those. So I would recommend do extra/extra test on each target platform and add exception handlers for the unsupported commands.
:) | Okay, I give up: What non-trivial command can you pass to exec(), and expect to get reasonable results on both Windows and Linux? Asking whether exec() is platform independent kind of seems to be missing the whole point of exec(), which is to invoke platform-specific behavior.
To actually address your question, yes - the way that the command string is interpreted will be different on different platforms (and potentially, for different shells, on Linux), and using the String[] version is more likely to end up with the parameters getting passed correctly. | Is java Runtime.exec(String[]) platform independent? | [
"",
"java",
"process",
"command-execution",
""
] |
I think I may be missing something here that should be relatively common. How can I make all form validation errors, including field-bound errors, show up at the top of the form (global)? | Add something like this at the top of your template:
```
foreach($form->getWidgetSchema()->getPositions() as $widgetName)
{
echo $form[$widgetName]->renderError();
}
``` | In advance
```
<ul>
<?php foreach($form->getWidgetSchema()->getPositions() as $widgetName): ?>
<?php if($form[$widgetName]->hasError()): ?>
<li><?php echo $form[$widgetName]->renderLabelName().': '.__($form[$widgetName]->getError()->getMessageFormat()); ?></li>
<?php endif; ?>
<?php endforeach;?>
</ul>
``` | Make all form validation errors show up at top in symfony? | [
"",
"php",
"mysql",
"forms",
"symfony1",
"propel",
""
] |
Okay, Here's a breakdown of what's up:
1. `<? $foo = new Imagick(); ?>` works without error when ran from the command-line (e.g., sudo php myscript.php
2. However, when run via the web browswer I get `Fatal error: Class 'Imagick' not found in /var/www/lhackwith_www/test_html/magic.php on line 1`.
3. magickwand is not installed
4. extension=imagick.so is in imagick.ini which is successfully being read according to phpInfo();
5. However, imagick is NOT showing up in PHP info.
Any advice would be appreciated. | I take it you're absolutely sure you've edited the right php.ini...
Did you check the webserver's error.log for hints? You might want to increase the LogLevel for that test. If it's an apache see <http://httpd.apache.org/docs/2.2/mod/core.html#loglevel> and <http://httpd.apache.org/docs/2.2/logs.html#errorlog>
or maybe [ldd - print shared library dependencies](http://unixhelp.ed.ac.uk/CGI/man-cgi?ldd+1) can shed some light on the issue:
```
<?php
$p = get_cfg_var('extension_dir');
$modpath = $p.DIRECTORY_SEPARATOR.'imagick.so';
echo $modpath, is_readable($modpath) ? ' readable':' not readable', "<br />\n";
echo '<pre>';
passthru('ldd '.$modpath.' 2>&1'); // in case of spaces et al in the path-argument use escapeshellcmd()
echo '</pre>';
```
please run this script both on the command line and through the webserver. Does it complain about a missing dependency?
echo
is\_dir($path) ? ' d':' -',
is\_readable($path) ? 'r':'-',
is\_writable($path) ? 'w':'-',
is\_executable($path) ? 'x ':'- ',
$path, "<br />\n";
}
$modpath = get\_cfg\_var('extension\_dir').DIRECTORY\_SEPARATOR.'imagick.so';
foo($modpath); | I had a similar problem with imagick after upgrading ubuntu from 12.04 to 12.10.
After much fiddling I eventually discovered that there is a different package needed (for php5?) and fixed it with:
```
sudo apt-get install php5-imagick
``` | Imagick Installation Errors - Class Undefined | [
"",
"php",
"imagick",
""
] |
```
<div><span>shanghai</span><span>male</span></div>
```
For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a
javascript function,how to do that job?
**EDIT**: and how to change the background color of div when mouse is on?
**EDIT AGAIN**:how to make the first span's width=120px?Seems not working in firefox | Give it an ID like "something", then:
```
var something = document.getElementById('something');
something.style.cursor = 'pointer';
something.onclick = function() {
// do something...
};
```
Changing the background color (as per your updated question):
```
something.onmouseover = function() {
this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
this.style.backgroundColor = '';
};
``` | `<div style="cursor: pointer;" onclick="theFunction()">`
is the simplest thing that works.
Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it [on a list apart](http://www.alistapart.com/articles/behavioralseparation) for good practices on not just solving this particular problem but in markup design in general. | how to make div click-able? | [
"",
"javascript",
"css",
"html",
"click",
""
] |
I'm working on a stored proc that executes some dynamic sql. Here's the example I found on [4GuysFromRolla.com](https://web.archive.org/web/20210310160204/http://www.4guysfromrolla.com/webtech/020600-1.shtml)
```
CREATE PROCEDURE MyProc
(@TableName varchar(255),
@FirstName varchar(50),
@LastName varchar(50))
AS
-- Create a variable @SQLStatement
DECLARE @SQLStatement varchar(255)
-- Enter the dynamic SQL statement into the
-- variable @SQLStatement
SELECT @SQLStatement = "SELECT * FROM " +
@TableName + "WHERE FirstName = '"
+ @FirstName + "' AND LastName = '"
+ @LastName + "'"
-- Execute the SQL statement
EXEC(@SQLStatement)
```
If you notice, they are using the keyword **SELECT** intead of **SET**. I didn't know you could do this. Can someone explain to me the differences between the 2? I always thought **SELECT** was simply for selecting records. | SELECT is ANSI, SET @LocalVar is MS T-SQL
SELECT allows multiple assignents: eg SELECT @foo = 1, @bar = 2 | Basically, SET is SQL ANSI standard for settings variables, SELECT is not. SET works only for single assignments, SELECT can do multiple assignments. Rather than write a long explanation that is well summarized in many places on the net:
[ryan farley blog](http://ryanfarley.com/blog/archive/2004/03/01/390.aspx)
[tony rogerson](http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/05/18/449.aspx)
[stackoverflow](https://stackoverflow.com/questions/189588/speed-of-select-vs-set-in-t-sql) | What is the difference between SELECT and SET in T-SQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Suppose I have the following:
```
using(var ctx = DataContextFactory.Create(0))
{ ... Some code ... }
```
Why not just do the following and lose a couple of curly braces?:
```
var ctx = DataContextFactory.Create(0);
ctx.Dispose();
```
Thanks for the advice! | The first is better. It ensures it is disposed even if an exception is thrown, and it correctly handles the case where `Create(0)` returns null (i.e. it doesn't attempt to call `Dispose()` on a null instance). | A `using` statement is always better because...
* you can't forget to call `Dispose()`, even as the code evolves into different code paths
* `Dispose()` gets called even if there's an exception. It also checks for `null` before calling `Dispose()`, which may be useful (assuming you're not just calling `new`).
One non-obvious (to me, anyway) trick with `using` is how you can avoid excessive nesting when you have multiple disposable objects:
```
using (var input = new InputFile(inputName))
using (var output = new OutputFile(outputName))
{
input.copyTo(output);
}
```
The VS code formatter will leave the two statements starting in the same column.
---
In fact, in some situations you don't even have to repeat the using statement...
```
using (InputFile input1 = new InputFile(inputName1), input2 = new InputFile(inputName2))
```
However, the restrictions for declaring multiple variables on the same line applies here so the types must be the same and you cannot use the implicit type **var**. | Which is better, and when: using statement or calling Dispose() on an IDisposable in C#? | [
"",
"c#",
".net",
"asp.net",
"idisposable",
"using-statement",
""
] |
I'm without my Java reference book and I'm having a tough time finding an answer with Google.
What is the difference between the ">>" and ">>>" operators in Java?
```
int value = 0x0100;
int result = (value >> 8);
System.out.println("(value >> 8) = " + result); // Prints: "(value >> 8) = 1"
result = (value >>> 8);
System.out.println("(value >>> 8) = " + result); // Prints: "(value >>> 8) = 1"
``` | `>>>` is [logical shift](http://en.wikipedia.org/wiki/Logical_shift), `>>` is [arithmetic shift](http://en.wikipedia.org/wiki/Arithmetic_shift).
* `0xDEADBEEF >>> 8` ⇒ `0x00DEADBE` *(logical shift, the one you want)*
* `0xDEADBEEF >> 8` ⇒ `0xFFDEADBE` *(arithmetic shift)* | Signed integers use the high-order bit to denote sign.
So `>>` preserves the sign, while `>>>` doesn't. This is why `>>` is referred to as the *arithmetic* shift and `>>>` is the *logical* shift.
This way, you can do (assuming 32-bit integers) the following:
* `-10 >> 1` yields -5 (`0xFFFFFFF6 >> 1` yields 0xFFFFFFFB - notice the high-order bit stays the same.)
* `-10 >>> 1` yields 2147483643 (`0xFFFFFFF6 >>> 1` yields 0x7FFFFFFB - notice all of the bits were shifted, so the high-order bit is now zero. The number is no longer negative according to twos-complement arithemetic.)
For positive integers, `>>` and `>>>` act the same, since the high-order bit is already zero.
It also explains why there is no need for a `<<<` operator. Since the sign would be trashed by sliding the bits to the left, it would map to no reasonable arithmetic operation. | Java's >> versus >>> Operator? | [
"",
"java",
"operators",
"bit-manipulation",
""
] |
When I use Java applets, they tend to be slow, don't integrate very well with the browser environment and often require a few click throughs ("No, I don't want to give this unsigned application free reign of my hard disk").
So, I'm curious.
Are these problems insurmountable? Are there Java applets out there which integrate well with the browser experience (in, for example, the way a well-designed Flash application does?) Can you point out any examples of really "nice" Java applets?
I'm asking this because I want to know if I should be taking a more serious look at Java-in-the-browser, or if Flash will remain dominant for the foreseeable future.
**Edit**: Unintentional flame bait has been removed. Sorry for any offence caused. | The Facebook asynchronous image uploader is a Java applet.
*Update*: Apparently not developed in house at Facebook. [This seems to be the product](http://www.aurigma.com/Products/ImageUploader/OnlineDemo.aspx).
*Amendment*:
Now that the question has been updated to be a bit more concise, I thought I'd add more to this answer.
This kind of problem, a mass image uploader (in this case), is the kind perfectly solved by a Java applet. Why?
1. It uses native UI elements, so users are not confused, or have to learn a new interface.
2. It can save massive amounts of bandwidth and overhead, because image transformations, such as resizing and cropping, can take place on the client side, rather than the server.
3. Write once, deploy everywhere (almost, sorta). | [Visual Thesaurus](http://www.visualthesaurus.com/) is the coolest / best applet I know of. | Do beautiful, user-friendly Java applets exist? | [
"",
"java",
"applet",
""
] |
I am sending a stream to methods to write on, and in those methods I am using a binary reader/wrtier. When the reader/writer gets disposed, either by `using` or just when it is not referenced, is the stream closed as well??
I would send a BinaryReader/Writer, but I am using a StreamReader too (maybe I should go around that. I am only using that for GetLine and ReadLine). This is quite troublesome if it closes the stream each time a writer/reader gets closed. | Yes, `StreamReader`, `StreamWriter`, `BinaryReader` and `BinaryWriter` all close/dispose their underlying streams when you call `Dispose` on them. They *don't* dispose of the stream if the reader/writer is just garbage collected though - you should always dispose of the reader/writer, preferrably with a `using` statement. (In fact, none of these classes have finalizers, nor should they have.)
Personally I prefer to have a using statement for the stream as well. You can nest `using` statements without braces quite neatly:
```
using (Stream stream = ...)
using (StreamReader reader = new StreamReader(stream, Encoding.Whatever))
{
}
```
Even though the `using` statement for the stream is somewhat redundant (unless the `StreamReader` constructor throws an exception) I consider it best practice as then if you get rid of the `StreamReader` and just use the stream directly at a later date, you'll already have the right disposal semantics. | This is an old one, but I wanted to do something similar today and found that things have changed. Since .net 4.5, there is a `leaveOpen` argument:
```
public StreamReader( Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int bufferSize, bool leaveOpen )
```
The only problem is that it is not entirely obvious what to set for the other parameters. Here is some help:
From **[the msdn page](http://msdn.microsoft.com/en-us/library/yhfzs7at%28v=vs.110%29.aspx)** for StreamReader Constructor (Stream):
> This constructor initializes the encoding to UTF8Encoding, the
> BaseStream property using the stream parameter, and the internal
> buffer size to 1024 bytes.
That just leaves `detectEncodingFromByteOrderMarks` which judging by **[the source code](http://www.dotnetframework.org/default.aspx/DotNET/DotNET/8@0/untmp/whidbey/REDBITS/ndp/clr/src/BCL/System/IO/StreamReader@cs/1/StreamReader@cs)** is `true`
```
public StreamReader(Stream stream)
: this(stream, true) {
}
public StreamReader(Stream stream, bool detectEncodingFromByteOrderMarks)
: this(stream, Encoding.UTF8, detectEncodingFromByteOrderMarks, DefaultBufferSize) {
}
```
It would be nice if some of those defaults were exposed or if the arguments were optional so that we could just specify the ones that we want. | Does disposing streamreader close the stream? | [
"",
"c#",
"stream",
"streamreader",
""
] |
Should a business object contain a reference to other objects (as in the id field references another database record) or should it have an instance of the actual objects.
For example:
```
public class Company
{
public int Id { get; set; }
public CompanyStatus Status { get; set; }
}
```
or
```
public class Company
{
public int Id { get; set; }
public int Status { get; set; }
}
``` | From my understanding, it should contain references to interfaces, not concrete classes.
```
public class Company
{
public int Id { get; set; }
public ICompanyStatus Status { get; set; }
}
```
Assuming that the concrete implementation of CompanyStatus in your example was a class and not an enum. | When creating Business Layer objects in an OO fashion, you should be using objects directly.
In your example, does `int Status` refers to the Id of a CompanyStatus object stored somewhere? In that case, it really feels like that's more of a data layer concern. It is usually best to avoid mixing your data layer with your business layer. | Should business objects contain objects or references? | [
"",
"c#",
"business-objects",
""
] |
I'm dealing with a large code base that uses the following construct throughout
```
class MyClass
{
public:
void f(int x);
private:
int x;
};
void MyClass::f(int x)
{
'
'
this->x = x;
'
'
}
```
Personally, I'd always used and hence prefer the form
```
class MyClass
{
public:
void f(int x);
private:
int _x;
};
void MyClass::f(int x)
{
'
'
_x = x;
'
'
}
```
The reasons I prefer the latter are that it is more succinct (less code = fewer potential bugs), and that I don't like having multiple variables of the same name in scope at the same time where I can avoid it. That said, I am seeing the former usage more and more often these days. Is there any upside to second approach that I am unaware of? (e.g. effect on compile time, use with templated code, etc...) Are the advantages of either approach significant enough merit a refactor to the other? Reason I ask, that while I don't like the second approach present in the code, the amount of effort and associated risk of introducing further bugs don't quite merit a refactor. | Your version is a bit cleaner, but while you're at it, I would:
1. Avoid leading underscore: \_x is ok until somebody chooses \_MyField which is a reserved name. An initial underscore followed by a capital letter is not allowed as a variable name. See: [What are the rules about using an underscore in a C++ identifier?](https://stackoverflow.com/q/228783/55075)
2. Make the attribute private or protected: the change is safe if it compiles, and you'll ensure your setter will be used.
3. The this-> story has a use, for example in templated code to make the field name dependent on your type (can solve some lookup issues).
A small example of name resolutions which are fixed by using an explicit this-> (tested with g++ 3.4.3):
```
#include <iostream>
#include <ostream>
class A
{
public:
int g_;
A() : g_(1) {}
const char* f() { return __FUNCTION__; }
};
const char* f() { return __FUNCTION__; }
int g_ = -1;
template < typename Base >
struct Derived : public Base
{
void print_conflicts()
{
std::cout << f() << std::endl; // Calls ::f()
std::cout << this->f() << std::endl; // Calls A::f()
std::cout << g_ << std::endl; // Prints global g_
std::cout << this->g_ << std::endl; // Prints A::g_
}
};
int main(int argc, char* argv[])
{
Derived< A >().print_conflicts();
return EXIT_SUCCESS;
}
``` | Field naming has nothing to do with a codesmell. As [Neil](https://stackoverflow.com/users/69307/neil-butterworth) said, field visibility is the only codesmell here.
There are various articles regarding naming conventions in C++:
* [naming convention for public and private variable?](https://stackoverflow.com/questions/589535/naming-convention-for-public-and-private-variable)
* [Private method naming convention](https://stackoverflow.com/questions/383850/private-method-naming-convention)
* [c++ namespace usage and naming rules](https://stackoverflow.com/questions/603378/c-namespace-usage-and-naming-rules)
etc. | Excessive use of `this` in C++ | [
"",
"c++",
"refactoring",
"this",
""
] |
I have the string
```
u"Played Mirror's Edge\u2122"
```
Which should be shown as
```
Played Mirror's Edge™
```
But that is another issue. My problem at hand is that I'm putting it in a model and then trying to save it to a database. AKA:
```
a = models.Achievement(name=u"Played Mirror's Edge\u2122")
a.save()
```
And I'm getting :
```
'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
```
full stack trace (as requested) :
```
Traceback:
File "/var/home/ptarjan/django/mysite/django/core/handlers/base.py" in get_response
86. response = callback(request, *callback_args, **callback_kwargs)
File "/var/home/ptarjan/django/mysite/yourock/views/alias.py" in import_all
161. types.import_all(type, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/types.py" in import_all
52. return modules[type].import_all(siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/xbox.py" in import_all
117. achiever = self.add_achievement(dict, siteAlias, alias)
File "/var/home/ptarjan/django/mysite/yourock/types/base_profile.py" in add_achievement
130. owner = siteAlias,
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in get
304. num = len(clone)
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in __len__
160. self._result_cache = list(self.iterator())
File "/var/home/ptarjan/django/mysite/django/db/models/query.py" in iterator
275. for row in self.query.results_iter():
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in results_iter
206. for rows in self.execute_sql(MULTI):
File "/var/home/ptarjan/django/mysite/django/db/models/sql/query.py" in execute_sql
1734. cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/util.py" in execute
19. return self.cursor.execute(sql, params)
File "/var/home/ptarjan/django/mysite/django/db/backends/mysql/base.py" in execute
83. return self.cursor.execute(query, args)
File "/usr/lib/pymodules/python2.5/MySQLdb/cursors.py" in execute
151. query = query % db.literal(args)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in literal
247. return self.escape(o, self.encoders)
File "/usr/lib/pymodules/python2.5/MySQLdb/connections.py" in string_literal
180. return db.string_literal(obj)
Exception Type: UnicodeEncodeError at /import/xbox:bob
Exception Value: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
```
And the pertinant part of the model :
```
class Achievement(MyBaseModel):
name = models.CharField(max_length=100, help_text="A human readable achievement name")
```
I'm using a MySQL backend with this in my settings.py
```
DEFAULT_CHARSET = 'utf-8'
```
So basically, how the heck should I deal with all this unicode stuff? I was hoping it would all "just work" if I stayed away from funny character sets and stuck to UTF8. Alas, it seems to not be just that easy. | Thank you to everyone who was posting here. It really helps my unicode knowledge (and hoepfully other people learned something).
We seemed to be all barking up the wrong tree since I tried to simplify my problem and didn't give ALL information. It seems that I wasn't using "REAL" unicode strings, but rather BeautifulSoup.NavigableString which repr themselves as unicode strings. So all the printouts looked like unicode, but they weren't.
Somewhere deep in the MySQLDB library they couldn't deal with these strings.
This worked :
```
>>> Achievement.objects.get(name = u"Mirror's Edge\u2122")
<Achievement: Mirror's Edge™>
```
On the other hand :
```
>>> b = BeautifulSoup(u"<span>Mirror's Edge\u2122</span>").span.string
>>> Achievement.objects.get(name = b)
... Exceptoins ...
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2122' in position 13: ordinal not in range(128)
```
But this works :
```
>>> Achievement.objects.get(name = unicode(b))
<Achievement: Mirror's Edge™>
```
So, thanks again for all the unicode help, I'm sure it will come in handy. But for now ...
**WARNING** : BeautifulSoup doesn't return **REAL** unicode strings and should be coerced with unicode() before doing anything meaningful with them. | A few remarks:
* Python 2.x has two string types
+ "str", which is basically a byte array (so you can store anything you like in it)
+ "unicode" , which is UCS2/UCS4 encoded unicode internally
* Instances of these types are considered "decoded" data. The internal representation is the reference, so you "decode" external data into it, and "encode" into some external format.
* A good strategy is to decode as early as possible when data enters the system, and encode as late as possible. Try to use unicode for the strings in your system as much as possible. (I disagree with Nikolai in this regard).
* This encoding aspect applies to Nicolai's answer. He takes the original unicode string, and encodes it into utf-8. But this **doesn't solve** the problem (at least not generally), because the resulting byte buffer can **still** contain bytes outside the range(127) (I haven't checked for \u2122), which means you will hit the same exception again.
* Still Nicolai's analysis holds that you are passing a unicode string, but somewhere down in the system this is regarded a str instance. It suffices if somewhere the str() function is applied to your unicode argument.
* In that case Python uses the so called default encoding which is ascii if you don't change it. There is a function sys.setdefaultencoding which you can use to switch to e.g. utf-8, but the function is only available in a limited context, so you cannot easily use it in application code.
* My feeling is the problem is somewhere deeper in the layers you are calling. Unfortunately, I cannot comment on Django or MySQL/SQLalchemy, but I wonder if you could specify a unicode type when declaring the 'name' attribute in your model. It would be good DB practice to handle type information on the field level. Maybe there is an alternative to CharField?!
* And yes, you can safely embed a single quote (') in a double quoted (") string, and vice versa. | python - Problem storing Unicode character to MySQL with Django | [
"",
"python",
"mysql",
"django",
"unicode",
"django-models",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.