input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
UIComboBox... Where is it? <p>So I'm pretty sure i already know the answer to this, but does the SDK include access to the combo box control used in mobile safari?</p>
<p>It should be easy enough to build one... but I'm not looking to re-invent the wheel if I don't have to.</p>
| <p>Not built in, no. Even as they have its just a text field and a UITable working together.</p>
|
ASP.net: Does anyone know how to implement youtube search box like effect? <p>When the search text box on youtube have focus on it, it is sort of highlighted with blue color around the text box. I'll like to implement that kind of effect on my web app. does anyone know how that's done or something similar?</p>
<p>Jack</p>
| <p>You'll use Javascript to change the textbox behavior based on the client events (gaining/losing focus). You might see <a href="http://www.dotnet2themax.com/showcontent.aspx?id=00fa0fd6-4970-4ddf-aa6b-335c3d1259be" rel="nofollow">this article</a> to start which covers the highlighting. Adjusting border properties would be done in a similar fashion.</p>
|
Good tools for analysing COM object registry interference? <p>I have inherited two complicated COM objects. One was derived from the other and (allegedly) the GUIDs, etc., were all changed so that they should not interfere. They do interfere and so far our debugging has not identified the culprit -- we've done registry compares and source code diffs and looked through the SCCS checkins. Obviously we're missing something, but they're big and complicated enough that I'm not surprised.</p>
<p>Is there a tool which can help, perhaps by checking COM objects for good behavior or detecting clashes between two COM objects or analyzing the registry?</p>
| <p>If you have Visual Studio, you could use <a href="http://nidget.wordpress.com/2012/08/01/create-registry-file-reg-equivalent-to-the-regsvr32-command/" rel="nofollow">regcap</a> to pull out the registry entries and then just collect a list of GUIDs via a script. You could also use OLEView (also from Visual Studio) to do this. </p>
<p>There are also other free tools that can do this:<br>
MMM (Make My Manifest) can be suckered into doing this if you have VB.<br>
Heat or Tallow from Wix 3.0 and 2.0, respectively, can also do something like this.</p>
<p>The output format will be a little different in each case but it will be enough to collect the relevant information into a text file.</p>
|
Google maps api database interaction <p>I am currently working on a project where users need to be able to enter geological data (such as a certain street name) into a website which will be put into a database and then retrieved and displayed on a Google map for all users to see.</p>
<p>I've done a little research and so far it looks like the best way to do this is to use a php script for getting data and sending it to a mySQL database where it can then be retrieved by another php script and then passed to javascript to display on the map.</p>
<p>From a big picture standpoint is this the best way to do things?</p>
<p>Thanks in advance!</p>
| <p>Looks like your problem has a few separate steps:</p>
<ol>
<li><p>Sign up for a Google Maps API key.</p></li>
<li><p>Write something that lets the user input the address and save it in the database.</p></li>
<li><p>The same script should convert the address to a coordinate using Geocodeing. The result should (must) be saved in the database as well since Google will only accept 15k Geocode queries per ip per day. Since you will be saving the results it would only be a problem if you are going to add more than 15k items to your map in one day.</p></li>
<li><p>Write the script that generate the map. There may be some cool Google API calls, if not you will have to do do some work yourself. Cache the map with a time-stamp so you can save some processor / time.</p></li>
<li><p>Create an interface that will display the map, integrate with step 2a, and call step 3.</p></li>
</ol>
|
How to fix: Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information <p>My code works. After I copy about 10 tables I get an error. <code>Dynamic SQL generation for the DeleteCommand is not supported against a SelectCommand that does not return any key column information.</code> Okay, I know I need to generate a primary key. But why can I copy 10 or so tables over, and THEN I get the error. Does each row have to return a primary key? If a row doesn't have a primary key, how do I generate one?</p>
<p>Here is my code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Text;
namespace LCR_ShepherdStaffupdater_1._0
{
public class DatabaseHandling
{
static DataTable datatableB = new DataTable();
static DataTable datatableA = new DataTable();
public static DataSet datasetA = new DataSet();
public static DataSet datasetB = new DataSet();
static OleDbDataAdapter adapterA = new OleDbDataAdapter();
static OleDbDataAdapter adapterB = new OleDbDataAdapter();
static string connectionstringA = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Settings.getfilelocationA();
static string connectionstringB = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + Settings.getfilelocationB();
static OleDbConnection dataconnectionB = new OleDbConnection(connectionstringB);
static OleDbConnection dataconnectionA = new OleDbConnection(connectionstringA);
static DataTable tableListA;
static DataTable tableListB;
static public void addTableA(string table, bool addtoDataSet)
{
dataconnectionA.Open();
datatableA = new DataTable(table);
try
{
OleDbCommand commandselectA = new OleDbCommand("SELECT * FROM [" + table + "]", dataconnectionA);
adapterA.SelectCommand = commandselectA;
adapterA.Fill(datatableA);
}
catch
{
Logging.updateLog("Error: Tried to get " + table + " from DataSetA. Table doesn't exist!", true, false, false);
}
if (addtoDataSet == true)
{
datasetA.Tables.Add(datatableA);
Logging.updateLog("Added DataTableA: " + datatableA.TableName.ToString() + " Successfully!", false, false, false);
}
dataconnectionA.Close();
}
static public void addTableB(string table, bool addtoDataSet)
{
dataconnectionB.Open();
datatableB = new DataTable(table);
try
{
OleDbCommand commandselectB = new OleDbCommand("SELECT * FROM [" + table + "]", dataconnectionB);
adapterB.SelectCommand = commandselectB;
adapterB.Fill(datatableB);
}
catch
{
Logging.updateLog("Error: Tried to get " + table + " from DataSetB. Table doesn't exist!", true, false, false);
}
if (addtoDataSet == true)
{
datasetB.Tables.Add(datatableB);
Logging.updateLog("Added DataTableB: " + datatableB.TableName.ToString() + " Successfully!", false, false, false);
}
dataconnectionB.Close();
}
static public string[] getTablesA(string connectionString)
{
dataconnectionA.Open();
tableListA = dataconnectionA.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
string[] stringTableListA = new string[tableListA.Rows.Count];
for (int i = 0; i < tableListA.Rows.Count; i++)
{
stringTableListA[i] = tableListA.Rows[i].ItemArray[2].ToString();
}
dataconnectionA.Close();
return stringTableListA;
}
static public string[] getTablesB(string connectionString)
{
dataconnectionB.Open();
tableListB = dataconnectionB.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "TABLE" });
string[] stringTableListB = new string[tableListB.Rows.Count];
for (int i = 0; i < tableListB.Rows.Count; i++)
{
stringTableListB[i] = tableListB.Rows[i].ItemArray[2].ToString();
}
dataconnectionB.Close();
return stringTableListB;
}
static public void createDataSet()
{
string[] tempA = getTablesA(connectionstringA);
string[] tempB = getTablesB(connectionstringB);
int percentage = 0;
int maximum = (tempA.Length + tempB.Length);
Logging.updateNotice("Loading Tables...");
Logging.updateLog("Started Loading File A", false, false, true);
for (int i = 0; i < tempA.Length ; i++)
{
if (!datasetA.Tables.Contains(tempA[i]))
{
addTableA(tempA[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
else
{
datasetA.Tables.Remove(tempA[i]);
addTableA(tempA[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
}
Logging.updateLog("Finished loading File A", false, false, true);
Logging.updateLog("Started loading File B", false, false, true);
for (int i = 0; i < tempB.Length ; i++)
{
if (!datasetB.Tables.Contains(tempB[i]))
{
addTableB(tempB[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
else
{
datasetB.Tables.Remove(tempB[i]);
addTableB(tempB[i], true);
percentage++;
Logging.loadStatus(percentage, maximum);
}
}
Logging.updateLog("Finished loading File B", false, false, true);
Logging.updateLog("Both files loaded into memory successfully", false, true, false);
}
static public DataTable getDataTableA()
{
datatableA = datasetA.Tables[Settings.textA];
return datatableA;
}
static public DataTable getDataTableB()
{
datatableB = datasetB.Tables[Settings.textB];
return datatableB;
}
static public DataSet getDataSetA()
{
return datasetA;
}
static public DataSet getDataSetB()
{
return datasetB;
}
static public void InitiateCopyProcessA()
{
DataSet tablesA;
tablesA = DatabaseHandling.getDataSetA();
int percentage = 0;
int maximum = (tablesA.Tables.Count);
foreach (DataTable table in tablesA.Tables)
{
Logging.loadStatus(percentage, maximum);
OverwriteTable(table, table.TableName);
Logging.updateLog("Copied " + table.TableName + " successfully.", false, true, false);
percentage++;
}
}
static void OverwriteTable(DataTable sourceTable, string tableName)
{
using (var destConn = new OleDbConnection(connectionstringA))
using (var destCmd = new OleDbCommand(tableName, destConn) { CommandType = CommandType.TableDirect })
using (var destDA = new OleDbDataAdapter(destCmd))
{
// Since we're using a single table, we can have the CommandBuilder
// generate the appropriate INSERT and DELETE SQL statements
using (var destCmdB = new OleDbCommandBuilder(destDA))
{
destCmdB.QuotePrefix = "["; // quote reserved column names
destCmdB.QuoteSuffix = "]";
destDA.DeleteCommand = destCmdB.GetDeleteCommand();
destDA.InsertCommand = destCmdB.GetInsertCommand();
// Get rows from destination, and delete them
var destTable = new DataTable();
destDA.Fill(destTable);
foreach (DataRow dr in destTable.Rows)
{
dr.Delete();
}
destDA.Update(destTable);
// Set rows from source as Added, so the DataAdapter will insert them
foreach (DataRow dr in sourceTable.Rows)
{
dr.SetAdded();
}
destDA.Update(sourceTable);
}
}
}
}
}
</code></pre>
<p>Google was not very helpful to me on this. Please provide a coding example.</p>
| <p>No coding example is really going to work. You have to make a determination from the table as to what is the unique identifier for the table. If there is no primary key (or at the least, a unique index), then you are out of luck.</p>
<p>The only way around this is to create a dynamic command yourself, which compares every value in the table to the record you want to delete. If they are the same, then delete them.</p>
<p>However, you run the risk of deleting multiple rows from the table, since there might be multiple rows in the table with the same values.</p>
|
Passing a method as a parameter in Ruby <p>I am trying to mess around a little bit with Ruby. Therefor I try to implement the algorithms (given in Python) from the book "Programming Collective Intelligence" Ruby.</p>
<p>In chapter 8 the author passes a method a as parameter. This seems to work in Python but not in Ruby.</p>
<p>I have here the method</p>
<pre><code>def gaussian(dist, sigma=10.0)
foo
end
</code></pre>
<p>and want to call this with another method</p>
<pre><code>def weightedknn(data, vec1, k = 5, weightf = gaussian)
foo
weight = weightf(dist)
foo
end
</code></pre>
<p>All I got is an error</p>
<pre><code>ArgumentError: wrong number of arguments (0 for 1)
</code></pre>
| <p>The comments referring to blocks and Procs are correct in that they are more usual in Ruby. But you can pass a method if you want. You call <code>method</code> to get the method and <code>.call</code> to call it:</p>
<pre><code>def weightedknn( data, vec1, k = 5, weightf = method(:gaussian) )
...
weight = weightf.call( dist )
...
end
</code></pre>
|
How can I strip Python logging calls without commenting them out? <p>Today I was thinking about a Python project I wrote about a year back where I used <code>logging</code> pretty extensively. I remember having to comment out a lot of logging calls in inner-loop-like scenarios (the 90% code) because of the overhead (<code>hotshot</code> indicated it was one of my biggest bottlenecks).</p>
<p>I wonder now if there's some canonical way to programmatically strip out logging calls in Python applications without commenting and uncommenting all the time. I'd think you could use inspection/recompilation or bytecode manipulation to do something like this and <strong>target only the code objects that are causing bottlenecks</strong>. This way, you could add a manipulator as a post-compilation step and use a centralized configuration file, like so:</p>
<pre><code>[Leave ERROR and above]
my_module.SomeClass.method_with_lots_of_warn_calls
[Leave WARN and above]
my_module.SomeOtherClass.method_with_lots_of_info_calls
[Leave INFO and above]
my_module.SomeWeirdClass.method_with_lots_of_debug_calls
</code></pre>
<p>Of course, <strong>you'd want to use it sparingly and probably with per-function granularity</strong> -- only for code objects that have shown <code>logging</code> to be a bottleneck. Anybody know of anything like this?</p>
<p><strong>Note:</strong> There are a few things that make this more difficult to do in a performant manner because of dynamic typing and late binding. For example, any calls to a method named <code>debug</code> may have to be wrapped with an <code>if not isinstance(log, Logger)</code>. In any case, I'm assuming all of the minor details can be overcome, either by a gentleman's agreement or some run-time checking. :-)</p>
| <p>What about using <a href="http://docs.python.org/library/logging.html?highlight=logging#logging.disable">logging.disable</a>?</p>
<p>I've also found I had to use <a href="http://docs.python.org/library/logging.html?highlight=logging#logging.Logger.isEnabledFor">logging.isEnabledFor</a> if the logging message is expensive to create.</p>
|
Android TextView Timer <p>For my Android application there is a timer that measures how much time has passed. Ever 100 milliseconds I update my TextView with some text like "Score: 10 Time: 100.10 seconds". But, I find the TextView only updates the first few times. The application is still very responsive, but the label will not update. I tried to call .invalidate(), but it still does not work. I don't know if there is some way to fix this, or a better widget to use.</p>
<p>Here is a example of my code:</p>
<pre><code>float seconds;
java.util.Timer gametimer;
void updatecount() { TextView t = (TextView)findViewById(R.id.topscore);
t.setText("Score: 10 - Time: "+seconds+" seconds");
t.postInvalidate();
}
public void onCreate(Bundle sis) {
... Load the UI, etc...
gametimer.schedule(new TimerTask() { public void run() {
seconds+=0.1; updatecount();
} }, 100, 100);
}
</code></pre>
| <p>The general solution is to use android.os.Handler instead which runs in the UI thread. It only does one-shot callbacks, so you have to trigger it again every time your callback is called. But it is easy enough to use. A blog post on this topic was written a couple of years ago: </p>
<p><a href="http://android-developers.blogspot.com/2007/11/stitch-in-time.html">http://android-developers.blogspot.com/2007/11/stitch-in-time.html</a> </p>
|
How do you specify a tab in .screenrc? <p>According to <a href="http://www.mattcutts.com/blog/screen-power-tips-screenrc/" rel="nofollow">this website</a>, you can change to command key sequence used by the Unix "screen" utility like this:</p>
<pre><code>escape ^Bb # Instead of Control-a, make the
# escape/command character be
# Control-b
</code></pre>
<p>How would you make it Control-Tab, I wonder?</p>
| <p>Never tried it, but you may have a go with this <a href="http://www.staldal.nu/tech/2009/01/10/how-to-use-ctrl-tab-in-gnu-screen/" rel="nofollow">link</a></p>
|
C# regular expressions - matching whole words? <p>I am writing a program that needs to search a LARGE text document for a large collection of words. The words are all file names, with underscores in them (eg, this_file_name). I know how to open and iterate through a text document, but I'm curious whether I should use Regex to search for these names, and if so, what kind of reg. ex. sequence should I use? I've tried </p>
<pre>
Regex r = new Regex("?this\_file\_name");
</pre>
<p>but I get an invalid argument error every time.</p>
| <p>It would be helpful to see a sample of the source text. but maybe this helps</p>
<pre><code>var doc = @"asdfsdafjkj;lkjsadf asddf jsadf asdfj;lksdajf
sdafjkl;sjdfaas sadfj;lksadf sadf jsdaf jf sda sdaf asdf sad
jasfd sdf sadf sadf sdajlk;asdf
this_file_name asdfsadf asdf asdf asdf
asdf sadf asdfj asdf sdaf sadfsadf
sadf asdf this_file_name asdf asdf ";
var reg = new Regex("this_file_name", RegexOptions.IgnoreCase | RegexOptions.Multiline);
var matches = reg.Matches(doc);
</code></pre>
|
Star Programmers [Team] vs Overall team quality <p>I want to know if others have experienced the situation where people around you are very smart and have few star programmers but as a team you are still struggling to move. I am not talking about people with arrogance/pride or social handicap. </p>
<p>Does motivation to create shared vision of product play any part?</p>
<p><hr /></p>
<p>I understand the value of Star programmer and teams but what I am really looking for is when even in the presence of such teams, product team is not reflecting that! Have people experienced such situation?</p>
| <p>Star programmers are supposed to be the <strong>leaders</strong>. If none of your programmers are taking intiative and carrying on the project, <strong>none of them are star programmers</strong> (or good star programmers, if bad ones exist).</p>
<p>That, or, as <a href="http://stackoverflow.com/questions/523050/star-programmers-team-vs-overall-team-quality/523064#523064">MrTelly</a> suggests, your star programmers are leading (or at least trying to lead) each other in <strong>opposite directions</strong>. Anyone who knows vector math knows that the sum of opposite-facing vectors is ... nothing!</p>
|
How do I get a user GUID from a selected item in a DropDownBox that is databound to a LINQ datasource? <p>This should be pretty straight forward but I can't seem to get my newbie mind around it. I have a ASP.net page that needs to create a new database entry based on user input from a web form. </p>
<p>One control in the form is a DropDownBox that is databound to a LinqDataSource whose context is a LinqToSQL data class. The table it is bound to is the default ASP.net aspnet_Users table.</p>
<p>So I have this drop down list that displays all of the users stored in that table. I have a table called Events that has a foreign key relationship with aspnet_Users (each Event has a aspnet_User) and so I need that aspnet_Users UserId value to create a new Event object. How do I get this value from the selected item in the drop-down box? I'm sure this is much simpler than I'm making it.</p>
| <p>Can you post some code of how you're binding this?</p>
<p>If it is bound to the user properly, you should be able to do the following.</p>
<pre><code>UserClass user = MyDropDown.SelectedValue as UserClass;
</code></pre>
<p>Just substitute the actual class name for the user and the proper name for the dropdown.</p>
|
Awesome Visual Studio Macros <p>For a small community discussion, what are some essential Visual Studio macros you use?</p>
<p>I just started learning about them, and want to hear what some of you can't live without.</p>
| <p>I add buttons on the toolbar for the following 3 macros. Each will take the currently selected text in any file and google it (or MSDN-it, or spell-check-it). Make up a nifty icon for the toolbar for extra style-points.</p>
<pre><code>Private Const BROWSER_PATH As String = "C:\Program Files\Mozilla Firefox\firefox.exe"
Sub SearchGoogle()
Dim cmd As String
cmd = String.Format("{0} http://www.google.com/search?hl-en&q={1}", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
Shell(cmd, AppWinStyle.NormalFocus)
End Sub
Sub SearchMSDN()
Dim cmd As String
cmd = String.Format("{0} http://www.google.com/search?hl-en&q={1}+site%3Amsdn.microsoft.com", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
Shell(cmd, AppWinStyle.NormalFocus)
End Sub
Sub SpellCheck()
Dim cmd As String
cmd = String.Format("{0} http://www.spellcheck.net/cgi-bin/spell.exe?action=CHECKWORD&string={1}", BROWSER_PATH, DTE.ActiveDocument.Selection.Text)
Shell(cmd, AppWinStyle.NormalFocus)
End Sub
</code></pre>
|
Sequentially firing multiple random timeouts in JavaScript <p>I know at first glance (due to the title) this looks like one of the "Did you try searching Google before posting?" questions, but I can't seem to find an answer for the specific issue I'm experiencing. Sorry if I'm a noob.... still learning :)</p>
<p>I need to simulate a pause in javascript, but the setTimeout(function_call, timeout) function is not working for me. Reason being... when that setTimeout function is called, it then makes the function call asynchronously.</p>
<p>A little background:<br>
I'm trying to simulate text being typed into a div at randomly timed intervals. I want it to appear as if a person is actually typing a message while the user is viewing the page. Since the timeout is a random interval and the function call is made asynchronously, the text ends up being printed in a random order.</p>
<p>Here is a snippet of what I have thus far:</p>
<pre><code>typeString: function(s)
{
for(var i=0;i<s.length;i++)
{
var c = s.charAt(i);
var temp = setTimeout("MessageType.typeChar('" + c + "')", this.genRandomTime());
}
}
</code></pre>
<p><br><br>
Thanks in advance for your help.</p>
<p>CJAM</p>
<p><br><br>
UPDATE: By adding the timer delay to a varialbe, it enabled me to offset timeOut for the asynchronous calls. Thank you all for your quick responses. Here is the updated code:</p>
<pre><code>typeString: function(s)
{
var delay = 0;
for(var i=0;i<s.length;i++)
{
var c = s.charAt(i);
setTimeout("GoogleTyper.typeChar('"+c+"')", delay += this.genRandomTime());
}
}
</code></pre>
| <p>Have you tried cumulatively setting the timeout? Stick a variable outside of your loop and initialize it to 0. Let's call it timeout for now. Add a random amount of time to this variable at the beginning of each iteration of your loop, and make the timeout work off of that. This way, you are ensured that functions are being called in order.</p>
|
Kdevelop as a Rails IDE <p>I would like to use Kdevelep as a Ruby on Rails IDE as I'm using Linux. How do I set up Kdevelop to enable this?</p>
| <p>You could use Kdevelop or Kate, although I don't know that there is a big community of support for these editors. If you are on Linux you are best to check out VIM, it's the 2nd most popular editor for Ruby/Rails (with Textmate being #1). </p>
<p>There is a really good writeup on how to set-up VIM at:</p>
<p><a href="http://blog.adamlowe.com/2009/12/vim-destroys-all-other-rails-editors.html" rel="nofollow">http://blog.adamlowe.com/2009/12/vim-destroys-all-other-rails-editors.html</a></p>
<p>If you use VIM with all the various tpope and NerdTree plugins you'll pretty much be set.</p>
|
Crawling Ajax.request url directly ... permission error <p>I need to crawl a web board, which uses ajax for dynamic update/hide/show of comments without reloading the corresponding post.
I am blocked by this comment area.</p>
<p>In Ajax.request, url is specified with a path without host name like this :</p>
<pre><code>new Ajax(**'/bbs/comment_db/load.php'**, {
update : $('comment_result'),
evalScripts : true,
method : 'post',
data : 'id=work_gallery&no=i7dg&sno='+npage+'&spl='+splno+'&mno='+cmx+'&ksearch='+$('ksearch').value,
onComplete : function() {
$('cmt_spinner').setStyle('display','none');
try {
$('cpn'+npage).setStyle('fontWeight','bold');
$('cpf'+npage).setStyle('fontWeight','bold');
} catch(err) {}
}
}).request();
</code></pre>
<p>If I try to access the url with the full host name then
I just got the message: "Permission Error" :</p>
<pre><code>new Ajax(**'http://host.name.com/bbs/comment_db/load.php'**, {
update : $('comment_result'),
evalScripts : true,
method : 'post',
data : 'id=work_gallery&no=i7dg&sno='+npage+'&spl='+splno+'&mno='+cmx+'&ksearch='+$('ksearch').value,
onComplete : function() {
$('cmt_spinner').setStyle('display','none');
try {
$('cpn'+npage).setStyle('fontWeight','bold');
$('cpf'+npage).setStyle('fontWeight','bold');
} catch(err) {}
}
}).request();
</code></pre>
<p>will result in the same error.</p>
<p>This is the same even when I call the actual php url in the web browser like this:
<a href="http://host.name.com/bbs/comment_db/load.php" rel="nofollow">http://host.name.com/bbs/comment_db/load.php</a>?'id=work_gallery&..'</p>
<p>I guess that the php module is restricted to be called by an url in the same host. </p>
<p>Any idea for crawling this data ?</p>
<p>Thanks in advance.</p>
<p>-- Shin </p>
| <p>Cross site XMLHttpRequest are forbidden by most browsers. If you want to crawl different sites, you will need to do it in a server side script.</p>
|
retrieve a multi-column PK in MySQL <p>How do I retrieve a multi-column PK in MySQL?</p>
<p>For example I have my primary key setup as
PRIMARY KEY (<code>donor_id</code>,<code>country_id</code>)</p>
<p>Now if I want to get the primary key value without concatenating those 2 fields in a select query, how do I do that? I want to use this in a view (or better yet, directly in phpmaker).</p>
| <p>It's not clear what you mean by "without concatenating". A simple</p>
<pre><code>SELECT donor_id, country_id FROM table WHERE ...;
</code></pre>
<p>will retrieve the records; you don't need to apply a <code>CONCATENATE()</code> function or anything like that. This is the Right Way to select two records from a table; the fact that they both happen to be declared part of the primary key changes nothing.</p>
|
Is there a view for inputing integers in Android? <p>I'm looking for something like the individual parts of the date picker dialog. A view that allows you to input integers (and only integers) that you can limit (between 1 and 10 for example), where you can use the keyboard or the arrows in the view itself. Does it exists?</p>
<p>It is for a dialog. A ready-made dialog to request an integer would also help.</p>
| <p>The NumberPicker widget is probably what you want. Unfortunatly it's located in com.android.internal.Widget.NumberPicker which we cannot get to through normal means.</p>
<p>There are two ways to use it:</p>
<ol>
<li>Copy the code from android source</li>
<li>Use reflection to access the widget</li>
</ol>
<p>Here's the xml for using it in a layout:</p>
<pre><code><com.android.internal.widget.NumberPicker
android:id="@+id/picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</code></pre>
<p>Here's the reflection to set the NumberPicker settings (I have not tested this):</p>
<pre><code>Object o = findViewById(R.id.picker);
Class c = o.getClass();
try
{
Method m = c.getMethod("setRange", int.class, int.class);
m.invoke(o, 0, 9);
}
catch (Exception e)
{
Log.e("", e.getMessage());
}
</code></pre>
<p>Since it's an internal widget and not in the SDK, future compatibility could be broken if you use reflection. It would be safest to roll your own from the source.</p>
<p>The original source for this informaiton is here:</p>
<p><a href="http://groups.google.com/group/android-developers/browse_frm/thread/65da9820998fddc9/6151cc9800e6a04d#6151cc9800e6a04d">http://groups.google.com/group/android-developers/browse_frm/thread/65da9820998fddc9/6151cc9800e6a04d#6151cc9800e6a04d</a></p>
|
JUMP and CALL <p>How is a JUMP and CALL instruction different? How does it relate to the higher level concepts such as a GOTO or a procedure call? (Am I correct in the comparison?)</p>
<p>This is what I think: </p>
<p>JUMP or GOTO is a transfer of the control to another location and the control does not automatically return to the point from where it is called. </p>
<p>On the other hand, a CALL or procedure/function call returns to the point from where it is called. Due to this difference in their nature, languages typically make use of a stack and a stack frame is pushed to "remember" the location to come back for each procedure called. This behaviour applies to recursive procedures too. In case of tail recursion, there is however no need to "push" a stack frame for <em>each</em> call.</p>
<p>Your answers and comments will be much appreciated.</p>
| <p>You're mostly right, if you are talking about CALL/JMP in x86 assembly or something similar. The main difference is:</p>
<ul>
<li>JMP performs a jump to a location, without doing anything else</li>
<li>CALL pushes the current instruction pointer on the stack (rather: one after the current instruction), and then JMPs to the location. With a RET you can get back to where you were.</li>
</ul>
<p>Usually, CALL is just a convenience function implemented using JMP. You could do something like</p>
<pre><code> movl $afterJmp, -(%esp)
jmp location
afterJmp:
</code></pre>
<p>instead of a CALL.</p>
|
How to return value from html popup <p>I need a terse, clean way to implement this in asp.net mvc (+/- jquery or js)?</p>
<p>User clicks an element in webform A;
Webform B pops up;
User interracts with webform B;
On closing webform B, probably by a submit button, the source element in webform a is updated with a value from webform B</p>
<p>Thanks.</p>
| <p>With ASP.NET MVC, I'd probably render a DIV on the page, initially hidden, perhaps via AJAX if the contents depend on values selected on the initial page. I'd use the jQuery UI dialog plugin to popup the dialog. The dialog could contain a form that submits back to the server. You could also use the onclose handler for the dialog to both copy values from the inputs in the dialog for use on the rest of the page. If you populated the dialog via AJAX you could have the server generate the HTML -- say by rendering a partial view and returning it -- or return json and generate the dialog on the fly in the browser.</p>
|
Find and Remove some text in Excel Worksheet with c# <p>i wanna find some text for example "Joe" and remove it from where it is in Excel Worksheet with C# ?</p>
| <p>You would need to use the Range.Replace method, and simply replace with an empty string. </p>
<pre class="lang-cs prettyprint-override"><code>static void ReplaceTextInExcelFile(string filename, string replace, string replacement)
{
object m = Type.Missing;
// open excel.
Application app = new ApplicationClass();
// open the workbook.
Workbook wb = app.Workbooks.Open(
filename,
m, false, m, m, m, m, m, m, m, m, m, m, m, m);
// get the active worksheet. (Replace this if you need to.)
Worksheet ws = (Worksheet)wb.ActiveSheet;
// get the used range.
Range r = (Range)ws.UsedRange;
// call the replace method to replace instances.
bool success = (bool)r.Replace(
replace,
replacement,
XlLookAt.xlWhole,
XlSearchOrder.xlByRows,
true, m, m, m);
// save and close.
wb.Save();
app.Quit();
app = null;
}
</code></pre>
|
Union or Use Flow Control Logic to Determine which table to report on <p>I'm working with a 3rd pary app where I can't alter the tables. We built custom matching "Monthly" tables with an additional datetime column "AsOfDate" where we dump the data at the end of the month and flag those data with the date of last day of the month.</p>
<p>I want to be able to create a single Stored Procedure (Application is designed to require a view or stored proc as the source of all reports.) and use a parameter which will either use the current data table (Parameter may be NULL or = Today's Date) or use the month end table and filter by the End of the month date. This way, I have one report where the user can either use current or data from a particular month end period. </p>
<p>Which would you prefer (And why) Sorry, this is not fully coded</p>
<p><strong>Solution #1 Union Query</strong></p>
<pre><code>Create Proc Balance_Report (@AsOfDate)
AS
Select Column1
From
(Select GetDate() as AsOfDate
, Column1
From Current.Balance
Union
Select AsOfDate
, Column1 From MonthEnd.Balance
) AS All_Balances
Where All_Balances.AsOfDate = @AsOfDate
</code></pre>
<p><strong>Solution #2 Use If Statement to select table</strong></p>
<pre><code>Create Proc Balance_Report (@AsOfDate)
AS
If @AsOfDate IS NULL or @AsOfDate = GetDate()
Select GetDate() as AsOfDate
, Column1
From Current.Balance
Else
Select AsOfDate
, Column1 From MonthEnd.Balance
Where AsOfDate = @AsOfDate
</code></pre>
<p>Again, this is not fully coded and is sort of db agnostic (But it is SQL Server 2005).</p>
<p><strong>Edit: Variation to Solution #2 using separate stored procedures</strong></p>
<pre><code>Create Proc Balance_Report (@AsOfDate)
AS
If @AsOfDate IS NULL or @AsOfDate = GetDate()
Exec Current_Balance_Date -- no param necessary
Else
exec MonthEnd_Balance_Date @AsOfDate
</code></pre>
| <p>I prefer the non-union solution. Selecting from a single table will always be faster than doing a union and selecting a single table's data from the union.</p>
|
Update trigger behavior in SQL 2005 <p>I used an Update statement inside a procedure to update a table which has an update trigger. Does the update statement complete after the trigger completes or what?</p>
| <p>the trigger runs as part of the UPDATE statement (after the data in the table has been updated); the proc resumes after this. There are also "instead of" triggers that <em>replace</em> the UPDATE statement.</p>
<p>See <a href="http://msdn.microsoft.com/en-us/magazine/cc164047.aspx" rel="nofollow">here</a> for more.</p>
|
Generate combinations ordered by an attribute <p>I'm looking for a way to generate combinations of objects ordered by a single attribute. I don't think lexicographical order is what I'm looking for... I'll try to give an example. Let's say I have a list of objects A,B,C,D with the attribute values I want to order by being 3,3,2,1. This gives A3, B3, C2, D1 objects. Now I want to generate combinations of 2 objects, but they need to be ordered in a descending way:</p>
<ul>
<li>A3 B3</li>
<li>A3 C2</li>
<li>B3 C2</li>
<li>A3 D1</li>
<li>B3 D1</li>
<li>C2 D1</li>
</ul>
<p>Generating all combinations and sorting them is not acceptable because the real world scenario involves large sets and millions of combinations. (set of 40, order of 8), and I need only combinations above the certain threshold. </p>
<p>Actually I need count of combinations above a threshold grouped by a sum of a given attribute, but I think it is far more difficult to do - so I'd settle for developing all combinations above a threshold and counting them. If that's possible at all.</p>
<p>EDIT - My original question wasn't very precise... I don't actually need these combinations ordered, just thought it would help to isolate combinations above a threshold. To be more precise, in the above example, giving a threshold of 5, I'm looking for an information that the given set produces 1 combination with a sum of 6 ( A3 B3 ) and 2 with a sum of 5 ( A3 C2, B3 C2). I don't actually need the combinations themselves.</p>
<p>I was looking into subset-sum problem, but if I understood correctly given dynamic solution it will only give you information is there a given sum or no, not count of the sums.</p>
<p>Thanks</p>
| <p>Actually, I think you <em>do</em> want lexicographic order, but descending rather than ascending. In addition:</p>
<ul>
<li>It's not clear to me from your description that A, B, ... D play any role in your answer (except possibly as the container for the values).</li>
<li>I think your question example is simply "For each integer at least 5, up to the maximum possible total of two values, how many distinct pairs from the set {3, 3, 2, 1} have sums of that integer?"</li>
<li>The interesting part is the early bailout, once no possible solution can be reached (remaining achievable sums are too small).</li>
</ul>
<p><strike>I'll post sample code later.</strike></p>
<p>Here's the sample code I promised, with a few remarks following:</p>
<pre><code>public class Combos {
/* permanent state for instance */
private int values[];
private int length;
/* transient state during single "count" computation */
private int n;
private int limit;
private Tally<Integer> tally;
private int best[][]; // used for early-bail-out
private void initializeForCount(int n, int limit) {
this.n = n;
this.limit = limit;
best = new int[n+1][length+1];
for (int i = 1; i <= n; ++i) {
for (int j = 0; j <= length - i; ++j) {
best[i][j] = values[j] + best[i-1][j+1];
}
}
}
private void countAt(int left, int start, int sum) {
if (left == 0) {
tally.inc(sum);
} else {
for (
int i = start;
i <= length - left
&& limit <= sum + best[left][i]; // bail-out-check
++i
) {
countAt(left - 1, i + 1, sum + values[i]);
}
}
}
public Tally<Integer> count(int n, int limit) {
tally = new Tally<Integer>();
if (n <= length) {
initializeForCount(n, limit);
countAt(n, 0, 0);
}
return tally;
}
public Combos(int[] values) {
this.values = values;
this.length = values.length;
}
}
</code></pre>
<h3>Preface remarks:</h3>
<p>This uses a little helper class called Tally, that just isolates the tabulation (including initialization for never-before-seen keys). I'll put it at the end.</p>
<p>To keep this concise, I've taken some shortcuts that aren't good practice for "real" code:</p>
<ul>
<li>This doesn't check for a null value array, etc.</li>
<li>I assume that the value array is already sorted into descending order, required for the early-bail-out technique. (Good production code would include the sorting.)</li>
<li>I put transient data into instance variables instead of passing them as arguments among the private methods that support <code>count</code>. That makes this class non-thread-safe.</li>
</ul>
<h3>Explanation:</h3>
<p>An instance of <code>Combos</code> is created with the (descending ordered) array of integers to combine. The <code>value</code> array is set up once per instance, but multiple calls to <code>count</code> can be made with varying population sizes and limits.</p>
<p>The <code>count</code> method triggers a (mostly) standard recursive traversal of unique combinations of <code>n</code> integers from <code>values</code>. The <code>limit</code> argument gives the lower bound on sums of interest.</p>
<p>The <code>countAt</code> method examines combinations of integers from <code>values</code>. The <code>left</code> argument is how many integers remain to make up <code>n</code> integers in a sum, <code>start</code> is the position in <code>values</code> from which to search, and <code>sum</code> is the partial sum.</p>
<p>The early-bail-out mechanism is based on computing <code>best</code>, a two-dimensional array that specifies the "best" sum reachable from a given state. The value in <code>best[n][p]</code> is the largest sum of <code>n</code> values beginning in position <code>p</code> of the original <code>values</code>.</p>
<p>The recursion of <code>countAt</code> bottoms out when the correct population has been accumulated; this adds the current <code>sum</code> (of <code>n</code> values) to the <code>tally</code>. If <code>countAt</code> has not bottomed out, it sweeps the <code>values</code> from the <code>start</code>-ing position to increase the current partial <code>sum</code>, as long as:</p>
<ul>
<li>enough positions remain in <code>values</code> to achieve the specified population, and</li>
<li>the <code>best</code> (largest) subtotal remaining is big enough to make the <code>limit</code>.</li>
</ul>
<p>A sample run with your question's data:</p>
<pre><code> int[] values = {3, 3, 2, 1};
Combos mine = new Combos(values);
Tally<Integer> tally = mine.count(2, 5);
for (int i = 5; i < 9; ++i) {
int n = tally.get(i);
if (0 < n) {
System.out.println("found " + tally.get(i) + " sums of " + i);
}
}
</code></pre>
<p>produces the results you specified:</p>
<pre><code>found 2 sums of 5
found 1 sums of 6
</code></pre>
<p>Here's the Tally code:</p>
<pre><code>public static class Tally<T> {
private Map<T,Integer> tally = new HashMap<T,Integer>();
public Tally() {/* nothing */}
public void inc(T key) {
Integer value = tally.get(key);
if (value == null) {
value = Integer.valueOf(0);
}
tally.put(key, (value + 1));
}
public int get(T key) {
Integer result = tally.get(key);
return result == null ? 0 : result;
}
public Collection<T> keys() {
return tally.keySet();
}
}
</code></pre>
|
jQuery UI datepicker translation <p>How can I translate the datepicker from jQuery UI into an other language (german for exaple)?</p>
| <p>There are already <a href="http://ui.jquery.com/demos/datepicker/#localization">localized versions of the jQuery Datepicker</a>. The demo doesn't appear to work as intended, but if you take the source code and build a page, you can see that it works</p>
<p><strong>EDIT:</strong></p>
<p>You can see the <a href="http://ui.jquery.com/demos/datepicker/localization.html">working versions here</a></p>
|
.Net- should I use the Split-function or the split-method? <p>Background:</p>
<p>I needed to split a string of numerous words into an array which separates the words for me for further use later on in my code. However, I needed to get rid of any numbers which might be present in the string so I declared a string contaning characters which I wanted to use as separators/delimiters as follows:</p>
<pre><code>dim Separators As String = " 1234567890"
</code></pre>
<p>so my code became more or less as follows:</p>
<pre><code>''//USING SPLIT-FUNCTION
dim MyTestString as String = "This is 9 a 567 test"
dim Separators As String = " 1234567890"
dim ResultWithNoNumbers() as String
ResultWithNoNumbers = Split(MyTestString,Separators.ToCharArray)
Messagebox.Show(ResultWithNoNumbers.Length.ToString)
''//Result is 1 and no split was performed
</code></pre>
<p>This did not work since the Split-functions did not consider my Separators as individual characters</p>
<p>however this worked..</p>
<pre><code>''//USING SPLIT-METHOD
dim MyTestString as String = "This is 9 a 567 test"
dim Separators As String = " 1234567890"
dim ResultWithNoNumbers() as String
ResultWithNoNumbers = MyTestString.Split(Separators.ToCharArray,
_StringSplitOptions.RemoveEmptyEntries)
Messagebox.Show(ResultWithNoNumbers.Length.ToString)
''//Result is 4 and split was performed
</code></pre>
<p>So far, so good - since one has more options with the Split-method compared to the Split-function, I managed to resolve my problem.</p>
<p>Now to my question, let's say I only needed the standard space-character (" ") as a delimiter (and no need to get rid of numbers like in above example), then both ways would work. So which one would you use? Apart from various options available, are there any advantages using a particular one? Perhaps one is faster, less memory-hungry?</p>
<p>EDIT: I'm developing for Windows Mobile and that's why speed- and memory-issues get important.</p>
<p>Thank you.</p>
| <p>Here's the code that gets executed for both; decide for yourself. I like string.split() more. </p>
<p>Here is the code that gets executed when you call <strong>string.split()</strong>:</p>
<pre><code>Private Function InternalSplitKeepEmptyEntries(ByVal sepList As Integer(), ByVal lengthList As Integer(), ByVal numReplaces As Integer, ByVal count As Integer) As String()
Dim startIndex As Integer = 0
Dim index As Integer = 0
count -= 1
Dim num3 As Integer = IIf((numReplaces < count), numReplaces, count)
Dim strArray As String() = New String((num3 + 1) - 1) {}
Dim i As Integer = 0
Do While ((i < num3) AndAlso (startIndex < Me.Length))
strArray(index++) = Me.Substring(startIndex, (sepList(i) - startIndex))
startIndex = (sepList(i) + IIf((lengthList Is Nothing), 1, lengthList(i)))
i += 1
Loop
If ((startIndex < Me.Length) AndAlso (num3 >= 0)) Then
strArray(index) = Me.Substring(startIndex)
Return strArray
End If
If (index = num3) Then
strArray(index) = String.Empty
End If
Return strArray
End Function
</code></pre>
<p>Here is the code that gets executed when you call the <strong>Split() function</strong>:</p>
<pre><code>Private Shared Function SplitHelper(ByVal sSrc As String, ByVal sFind As String, ByVal cMaxSubStrings As Integer, ByVal [Compare] As Integer) As String()
Dim invariantCompareInfo As CompareInfo
Dim num2 As Integer
Dim ordinal As CompareOptions
Dim length As Integer
Dim num5 As Integer
Dim num6 As Integer
If (sFind Is Nothing) Then
length = 0
Else
length = sFind.Length
End If
If (sSrc Is Nothing) Then
num6 = 0
Else
num6 = sSrc.Length
End If
If (length = 0) Then
Return New String() { sSrc }
End If
If (num6 = 0) Then
Return New String() { sSrc }
End If
Dim num As Integer = 20
If (num > cMaxSubStrings) Then
num = cMaxSubStrings
End If
Dim strArray As String() = New String((num + 1) - 1) {}
If ([Compare] = 0) Then
ordinal = CompareOptions.Ordinal
invariantCompareInfo = Strings.m_InvariantCompareInfo
Else
invariantCompareInfo = Utils.GetCultureInfo.CompareInfo
ordinal = (CompareOptions.IgnoreWidth Or (CompareOptions.IgnoreKanaType Or CompareOptions.IgnoreCase))
End If
Do While (num5 < num6)
Dim str As String
Dim num4 As Integer = invariantCompareInfo.IndexOf(sSrc, sFind, num5, (num6 - num5), ordinal)
If ((num4 = -1) OrElse ((num2 + 1) = cMaxSubStrings)) Then
str = sSrc.Substring(num5)
If (str Is Nothing) Then
str = ""
End If
strArray(num2) = str
Exit Do
End If
str = sSrc.Substring(num5, (num4 - num5))
If (str Is Nothing) Then
str = ""
End If
strArray(num2) = str
num5 = (num4 + length)
num2 += 1
If (num2 > num) Then
num = (num + 20)
If (num > cMaxSubStrings) Then
num = (cMaxSubStrings + 1)
End If
strArray = DirectCast(Utils.CopyArray(DirectCast(strArray, Array), New String((num + 1) - 1) {}), String())
End If
strArray(num2) = ""
If (num2 = cMaxSubStrings) Then
str = sSrc.Substring(num5)
If (str Is Nothing) Then
str = ""
End If
strArray(num2) = str
Exit Do
End If
Loop
If ((num2 + 1) = strArray.Length) Then
Return strArray
End If
Return DirectCast(Utils.CopyArray(DirectCast(strArray, Array), New String((num2 + 1) - 1) {}), String())
End Function
</code></pre>
|
Sockets in C#: How to get the response stream? <p>I'm trying to replace this:</p>
<pre><code>void ProcessRequest(object listenerContext)
{
var context = (HttpListenerContext)listenerContext;
Uri URL = new Uri(context.Request.RawUrl);
HttpWebRequest.DefaultWebProxy = null;
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
httpWebRequest.Method = context.Request.HttpMethod;
httpWebRequest.Headers.Clear();
if (context.Request.UserAgent != null) httpWebRequest.UserAgent = context.Request.UserAgent;
foreach (string headerKey in context.Request.Headers.AllKeys)
{
try { httpWebRequest.Headers.Set(headerKey, context.Request.Headers[headerKey]); }
catch (Exception) { }
}
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
Stream responseStream = httpWebResponse.GetResponseStream();
if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
MemoryStream memStream = new MemoryStream();
byte[] respBuffer = new byte[4096];
try
{
int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
while (bytesRead > 0)
{
memStream.Write(respBuffer, 0, bytesRead);
bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
}
}
finally
{
responseStream.Close();
}
byte[] msg = memStream.ToArray();
context.Response.ContentLength64 = msg.Length;
using (Stream strOut = context.Response.OutputStream)
{
strOut.Write(msg, 0, msg.Length);
}
}
catch (Exception ex)
{
// Some error handling
}
}
</code></pre>
<p>with sockets. This is what I have so far:</p>
<pre><code>void ProcessRequest(object listenerContext)
{
HttpListenerContext context = (HttpListenerContext)listenerContext;
Uri URL = new Uri(context.Request.RawUrl);
string getString = string.Format("GET {0} HTTP/1.1\r\nHost: {1}\r\nAccept-Encoding: gzip\r\n\r\n",
context.Request.Url.PathAndQuery,
context.Request.UserHostName);
Socket socket = null;
string[] hostAndPort;
if (context.Request.UserHostName.Contains(":"))
{
hostAndPort = context.Request.UserHostName.Split(':');
}
else
{
hostAndPort = new string[] { context.Request.UserHostName, "80" };
}
IPHostEntry ipAddress = Dns.GetHostEntry(hostAndPort[0]);
IPEndPoint ip = new IPEndPoint(IPAddress.Parse(ipAddress.AddressList[0].ToString()), int.Parse(hostAndPort[1]));
socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ip);
</code></pre>
<p><strong>BEGIN NEW CODE</strong></p>
<pre><code>Encoding ASCII = Encoding.ASCII;
Byte[] byteGetString = ASCII.GetBytes(getString);
Byte[] receiveByte = new Byte[256];
string response = string.Empty;
socket.Send(byteGetString, byteGetString.Length, 0);
Int32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
response += ASCII.GetString(receiveByte, 0, bytes);
while (bytes > 0)
{
bytes = socket.Receive(receiveByte, receiveByte.Length, 0);
strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);
}
socket.Close();
string separator = "\r\n\r\n";
string header = strPage.Substring(0,strPage.IndexOf(separator));
string content = strPage.Remove(0, strPage.IndexOf(separator) + 4);
byte[] byteResponse = ASCII.GetBytes(content);
context.Response.ContentLength64 = byteResponse .Length;
context.Response.OutputStream.Write(byteResponse , 0, byteResponse .Length);
context.Response.OutputStream.Close();
</code></pre>
<p><strong>END NEW CODE</strong></p>
<p>After connecting to the socket I don't know how to get the Stream response to decompress, and send back to <strong>context.Response.OutputStream</strong></p>
<p>Any help will be appreciated.
Thanks.
Cheers.</p>
<p><strong>EDIT 2:</strong>
With this edit now seems to be working fine (same as HttpWebRequest at least). Do you find any error here?</p>
<p><strong>EDIT 3:</strong>
False alarm... Still can't get this working</p>
<p><strong>EDIT 4:</strong>
I needed to add the following lines to Scott's code ... because not always the first to bytes of reponseStream are the gzip magic number.
The sequence seems to be: 0x0a (10), 0x1f (31), 0x8b (139). The last two are the gzip magic number. The first number was always before in my tests.</p>
<pre><code>if (contentEncoding.Equals("gzip"))
{
int magicNumber = 0;
while (magicNumber != 10)
magicNumber = responseStream.ReadByte();
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
</code></pre>
| <p>Here's some code that works for me.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO.Compression;
namespace HttpUsingSockets {
public class Program {
private static readonly Encoding DefaultEncoding = Encoding.ASCII;
private static readonly byte[] LineTerminator = new byte[] { 13, 10 };
public static void Main(string[] args) {
var host = "stackoverflow.com";
var url = "/questions/523930/sockets-in-c-how-to-get-the-response-stream";
IPHostEntry ipAddress = Dns.GetHostEntry(host);
var ip = new IPEndPoint(ipAddress.AddressList[0], 80);
using (var socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) {
socket.Connect(ip);
using (var n = new NetworkStream(socket)) {
SendRequest(n, new[] {"GET " + url + " HTTP/1.1", "Host: " + host, "Connection: Close", "Accept-Encoding: gzip"});
var headers = new Dictionary<string, string>();
while (true) {
var line = ReadLine(n);
if (line.Length == 0) {
break;
}
int index = line.IndexOf(':');
headers.Add(line.Substring(0, index), line.Substring(index + 2));
}
string contentEncoding;
if (headers.TryGetValue("Content-Encoding", out contentEncoding)) {
Stream responseStream = n;
if (contentEncoding.Equals("gzip")) {
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
}
else if (contentEncoding.Equals("deflate")) {
responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
}
var memStream = new MemoryStream();
var respBuffer = new byte[4096];
try {
int bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
while (bytesRead > 0) {
memStream.Write(respBuffer, 0, bytesRead);
bytesRead = responseStream.Read(respBuffer, 0, respBuffer.Length);
}
}
finally {
responseStream.Close();
}
var body = DefaultEncoding.GetString(memStream.ToArray());
Console.WriteLine(body);
}
else {
while (true) {
var line = ReadLine(n);
if (line == null) {
break;
}
Console.WriteLine(line);
}
}
}
}
}
static void SendRequest(Stream stream, IEnumerable<string> request) {
foreach (var r in request) {
var data = DefaultEncoding.GetBytes(r);
stream.Write(data, 0, data.Length);
stream.Write(LineTerminator, 0, 2);
}
stream.Write(LineTerminator, 0, 2);
// Eat response
var response = ReadLine(stream);
}
static string ReadLine(Stream stream) {
var lineBuffer = new List<byte>();
while (true) {
int b = stream.ReadByte();
if (b == -1) {
return null;
}
if (b == 10) {
break;
}
if (b != 13) {
lineBuffer.Add((byte)b);
}
}
return DefaultEncoding.GetString(lineBuffer.ToArray());
}
}
}
</code></pre>
<p>You could substitute this for the Socket/NetworkStream and save a bit of work.</p>
<pre><code>using (var client = new TcpClient(host, 80)) {
using (var n = client.GetStream()) {
}
}
</code></pre>
|
ASP.NET: Your most used httpmodules <p>Interested in description of your most used ASP.NET httpmodules that solved a specific problem for your webapp.<br/>
Best practices and in-the-field usages are welcome.</p>
| <p><a href="http://msdn.microsoft.com/en-us/library/aa479332.aspx" rel="nofollow">ELMAH</a> is very popular and useful for exception logging in ASP.NET applications.</p>
|
Is there a Delphi library which reads and writes .properties files? <p>I thought about creating my own, but there are many details to consider to make it 100% compatible with Java .properties files, so I'm asking first.</p>
| <p>There used to be a Java IDE called <a href="http://www.gexperts.com/products/gel/gel.asp" rel="nofollow">Gel</a>. It was written in Delphi, and it was a good IDE, so I expect it was capable of working with property files. The author has discontinued work on the project. In his <a href="http://www.gexperts.com/blog/archives/2008/06/entry_387.html" rel="nofollow">blog post describing the project's cancellation</a>, he mentions being open to the prospect of making the project open source, but it never really took off. If you ask nicely, you might get the parts of that code you're looking for.</p>
<p>Be skeptical of any solution you find that uses <code>TStrings</code> for its interface. Although that class has <code>Names</code> and <code>Values</code> properties that make it attractive as a class for working with key/value pairs, it won't be completely compatible with Java's property files. The reason is that Java allows "=" as a character in the key name, and the <code>TStrings</code> class detects the end of a name and the start of a value by looking for the first "=" character in a string. Furthermore, Java property files can use ":" as the separator, and they can even use ordinary whitespace.</p>
|
How do you find the paths of linked images in Adobe Illustrator 9? <p>I have an Illustrator file with linked images. I'd actually like to instead embed the images. I first have to know which files they are. How do I find out? I'm using Illustrator 9.</p>
| <p>The first Illustrator version I ever used was 10, but, is there a links pallete in version 9? Try the window menu and look for "links". It has a few options there to search for the image you want, relink, open the original, etc.</p>
|
Easy way to pdf a web report <p>We are trying to create a web reporting system, with the standard flash chart's, one of the major requirements is that this report must be emailed to customers on a regular schedule as a PDF file.</p>
<p>Does anyone know of either</p>
<ul>
<li>An easy tool to point at the webpage and pdf it, including flash charts</li>
<li>Another way of doing this?</li>
</ul>
<p>We have tried sql server reporting in the past and found it to be a little slow and generally the charting is a little unpretty.</p>
<p>Any help is appreciated.</p>
| <p>If your web reporting system is being built using .NET you may want to look into ABCpdf Component for .NET which can be found <a href="http://www.websupergoo.com/abcpdf-1.htm" rel="nofollow">here</a>. I am not sure if it works with flash charts, as at my work we use charts that are images, but give it a try.</p>
|
Using ironscheme in visual studio 2008 <p>Though it says on the IronScheme codeplex site that a plugin is included for visual studio, I have no idea how to get ironscheme working with VS...</p>
<p>Is it possible? If so , how?</p>
<p>Thanks </p>
| <p>Firstly, you definitely need Visual Studio 2008 SP1, without SP1 it will <a href="http://ironscheme.codeplex.com/Thread/View.aspx?ThreadId=50805" rel="nofollow">cause problems</a>.</p>
<p>Secondly, follow the instructions in the <a href="https://ironscheme.svn.codeplex.com/svn/IronScheme/IronScheme.Console/docs/visual-studio.txt" rel="nofollow">visual-studio.txt</a> file.</p>
<p>Run from the command line: </p>
<ol>
<li><p>If admin: RegPkg /codebase <absolute path of IronScheme.VisualStudio.dll></p></li>
<li><p>If not admin: RegPkg /ranu /codebase <absolute path of IronScheme.VisualStudio.dll></p></li>
<li>devenv /setup</li>
</ol>
<p>Now start VS, and open a file with a 'ss' or 'sls' or 'scm' extension.</p>
<p>Cheers</p>
<p>leppie</p>
|
Timer code for online quiz on mobiles <p>We are doing project on online quiz tool for mobile devices using J2ME. We got the code for midlet interface, webserver and connections. But we need to implement timer in it. So anyone can give suggestions for that code and where can be it beneficial to implement it?</p>
| <p>I am not sure if I understand the question but it sounds like you want to use java.util.Timer. See <a href="http://www.java2s.com/Code/Java/J2ME/Timer.htm" rel="nofollow">http://www.java2s.com/Code/Java/J2ME/Timer.htm</a> for the details.</p>
|
Best Practice for PK in SQL Server <p>I have been wondering what the best practices or ramifications are in setting up the PK in a M2M table in SQL Server. For instance:</p>
<p>I have 2 tables</p>
<ul>
<li>Users</li>
<li>Roles</li>
</ul>
<p>I am making a new table</p>
<ul>
<li>UserRole</li>
</ul>
<p>Which has 2 fields
RoleId & UserID</p>
<p>now should I </p>
<ol>
<li>create a UserRoleID as the PK and make UserID and RoleID the FKs</li>
<li>make the PK UserID AND RoleID and set them as FKs</li>
<li>something else</li>
</ol>
<p>I would like to know the performance issues with each of the options and what the recommended best practices are.</p>
| <p>Standard procedure for these cases is to have two indexes. The unique PK is the two fields composite, with the field with the greater cardinality first, i.e. UserID; and the second index with just the secondary field (i.e. RoleID).</p>
<p>Then cluster on whichever is likely to be involved in more multirecord result sets (i.e. if querying for multiple roles per user, or multiple users per role).</p>
|
what is the best way to mark any text? <p>I need users to mark some section of text with custom tags, I can't use the xml based tags as the whole text will be embedded in XML documents and all the < will be converted to html escape code <. I want users to marks some section of text with tags like skip, bookmark, these tags can have attributes also like bookmark name="first".
Which is the best way of allowing users to mark text using the BB forum way like [b]abcd[/b]
or using {{bookmark name="first"}}.
Or is there any better scheme or technique available.</p>
<p>I don't want to change the structure of the text as down by the markdown or textile, I just want to tag some section of text, like the phpBB tags. The question is there any other style than phpBB? Like in some software I see {{bookmark name = "abcd"}} style.</p>
| <p>The three common markups I know of for this purpose are <a href="http://daringfireball.net/projects/markdown/" rel="nofollow">Markdown</a> (used, I believe, by SO), <a href="http://www.textism.com/tools/textile/" rel="nofollow">textile</a>, and <a href="http://pear.php.net/pepr/pepr-bbcode-help.php" rel="nofollow">BBCode</a>. The first two are commonly used for blog sites and CMS frameworks, and BBCode I think is usually associated with bulletin-board sites. Preview and mapping utilities are available for each.</p>
|
Asp.net E-commerce performance <p>I am developing e-commerce project on Asp.Net 3.5 with C#. I am using 3 tiers (Data + Business + UI) structure to reach the data from database (Msql 2005).</p>
<p>There are stored procedures and everything going on from them.(CRUD methods)</p>
<p>There is a performance issue here, project is running so slowly. I couldn't find any problem in transaction model.</p>
<p>Also the project is running on shared hosting at overseas country.Database server and web server are running on different machines.Database server has nearly 1000 databases.</p>
<p>How can I test and learn where is the problem ?</p>
| <p>Since there is upwards of 1000 Databases sharing resources I would take a stab that might be your issue.... If you connect to your database and it takes 5 seconds to run a simple query then you can guess the problem.</p>
<p>I would add some stopwatch functionality onto a "testpage" that runs on your web server. This should give you the basic info to see if there is a "bottle neck" in waiting for the database to return your query. If you have made it that far then I would suspect it would be your web server.</p>
<p>Your last option would be be to set up a simple low spec machine with DB and web server on it and just test. Depending on how much traffic your site is getting you should be able to get a pretty good idea of its response time. </p>
<p>Tools such as <a href="http://developer.yahoo.com/yslow/" rel="nofollow">YSlow</a> might also be of some help however these are usually used more for fine tuning. </p>
|
The right language for OpenGL UI prototyping. Ditching Python <p>So, I got this idea that I'd try to prototype an experimental user interface using OpenGL and some physics. I know little about either of the topics, but am pretty experienced with programming languages such as C++, Java and C#. After some initial research, I decided on using Python (with Eclipse/PyDev) and Qt, both new to me, and now have four different topics to learn more or less simultaneously.</p>
<p>I've gotten quite far with both OpenGL and Python, but while Python and its ecosystem initially seemed perfect for the task, I've now discovered some serious drawbacks. Bad API documentation and lacking code completion (due to dynamic typing), having to import every module I use in every other module gets tedious when having one class per module, having to select the correct module to run the program, and having to wait 30 seconds for the program to start and obscure the IDE before being notified of many obvious typos and other mistakes. It gets really annoying really fast. Quite frankly, i don't get what all the fuzz is about. Lambda functions, list comprehensions etc. are nice and all, but there's certainly more important things.</p>
<p>So, unless anyone can resolve at least some of these annoyances, Python is out. C++ is out as well, for obvious reasons, and C# is out, mainly for lack of portability. This leaves Java and JOGL as an attractive option, but I'm also curious about Ruby and Groovy. I'd like your opinion on these and others though, to keep my from making the same mistake again.</p>
<p>The requirements are:</p>
<ul>
<li>Keeping the hell out of my way.</li>
<li>Good code completion. Complete method signatures, including data types and parameter names.</li>
<li>Good OpenGL support.</li>
<li>Qt support is preferable.</li>
<li>Object Oriented</li>
<li>Suitable for RAD, prototyping</li>
<li>Cross-platform</li>
<li>Preferably Open-Source, but at least free.</li>
</ul>
| <p>It seems you aren't mainly having a problem with Python itself, but instead with the IDE.</p>
<p><em>"Bad API documentation"</em></p>
<p>To what API? Python itself, Qt or some other library you are using?</p>
<p><em>"lacking code completion (due to dynamic typing)"</em></p>
<p>As long as you are not doing anything magic, I find that PyDev is pretty darn good at figuring these things out. If it gets lost, you can always typehint by doing:</p>
<pre><code>assert isinstance(myObj, MyClass)
</code></pre>
<p>Then, PyDev will provide you with code completion even if myObj comes from a dynamic context.</p>
<p><em>"having to import every module I use in every other module gets tedious when having one class per module"</em></p>
<p>Install PyDev Extensions, it has auto-import on the fly. Or collect all your imports in a separate module and do:</p>
<pre><code>from mymodulewithallimports import *
</code></pre>
<p><em>"having to select the correct module to run the program"</em></p>
<p>In Eclipse, you can set up a default startup file, or just check "use last run configuration". Then you never have to select it again.</p>
<p><em>"before being notified of many obvious typos and other mistakes"</em></p>
<p>Install PyDev Extensions, it has more advanced syntax checking and will happily notify you about unused imports/variables, uninitialized variables etc.</p>
|
Fast min on span <p>Given a list of arrays and lots of setup time I need to quickly find the smallest value in some sub-span of each array. In concept:</p>
<pre><code>class SpanThing
{
int Data;
SpanThing(int[][] data) /// must be rectangulare
{
Data = data;
//// process, can take a while
}
int[] MinsBruteForce(int from, int to)
{
int[] result = new int[data.length];
foreach(int index, int[] dat; Data)
{
result[i] = int.max;
foreach(int v; dat[from .. to]);
result[i] = min(result[i], v);
}
return result;
}
int[] MinsSmart(int from, int to)
{
// same as MinsBruteForce but faster
}
}
</code></pre>
<p>My current thinking on how to do this would be to build a binary tree over the data where each node contains the min in the related span. That way finding the min in the span for one row would consist of finding the min of only the tree nodes that compose it. This set would be the same for each row so could be computed once.</p>
<p>Does any one see any issues with this idea or known of better ways?</p>
<p><hr /></p>
<p>To clarify, the tree I'm talking about would be set up sutch that the root node would contain the min value for the entire row and for each node, it's left child would have the min value for the left half of the parent's span and the same for the right.</p>
<pre><code> 0 5 6 2 7 9 4 1 7 2 8 4 2
------------------------------------------------
| 5 | 6| | 7 | 9 | | 1 | 7 | 2 | 8 | 4 | 2
0 | 5 | 2 | 7 | 4 | 1 | 2 | 2
0 | 2 | 1 | 2
0 | 1
0
</code></pre>
<p>This tree can be mapped to an array and defined in such a way that the segment bounds can be computed resulting in fast look-up. </p>
<p>The case I'm optimizing for is where I have a fixed input set and lots of up front time but then need to do many fast tests on a veriety of spans.</p>
| <p>Your described approach sounds like you're trying to do some sort of <a href="http://en.wikipedia.org/wiki/Memoization" rel="nofollow">memoization</a> or caching, but that's only going to help you if you're checking the same spans or nested spans repeatedly.</p>
<p>The general case for <em>min([0..n])</em> is going to be <em>O(n)</em>, which is what you've got already.</p>
<p>Your code seems to care more about the actual numbers in the array than their order in the array. If you're going to be checking these spans repeatedly, is it possible to just sort the data first, which could be a single <em>O(n log n)</em> operation followed by a bunch of <em>O(1)</em> ops? Most languages have some sort of built in <a href="http://en.wikipedia.org/wiki/Sorting_algorithm" rel="nofollow">sorting algorithm</a> in their standard libraries.</p>
|
Showing data and counting from multiple databases in MySQL <p>I have two tables, that is joined in some way. I've spent the last hour googling around, not finding any concrete answers that worked in my case.</p>
<p>The case is, table 1 is called Clients, and table 2 is called Projects. I need to list all the client names, followed by number of projects related to that project and the project title.</p>
<p>For example:</p>
<p>Client 1 (2 projects)<br />
- Project 1 title<br />
- Project 2 title<br /></p>
<p>Client 2 (0 projects)</p>
<p>Client 3 (1 project)<br />
- Project 1 title</p>
<p>How is this doable, in the simplest and easiest way?</p>
| <p>You don't say anything about your app, but I'd recommend separating querying from displaying. Let SQL get the data for you and then let something else do presentation.</p>
|
C# ComboBox in DropDownList style, how do I set the text? <p>I want to use a ComboBox with the DropDownList style (the one that makes it look like a button so you can't enter a value) to insert a value into a text box. I want the combobox to have a text label called 'Wildcards' and as I select a wildcard from the list the selected value is inserted in to a text box and the combobox text remains 'Wildcard'. My first problem is I can't seem to set a text value when the combobox is in DropDownList style. Using the properties pallet doesn't work the text value is simply cleared when you click off, adding comboBox.Text = "Wildcards"; to form_load doesn't work either. Can anyone help?</p>
| <p>The code you specify:</p>
<pre><code>comboBox.Text = "Wildcards";
</code></pre>
<p>...should work. The only reason it would not is that the text you specify is not an item within the comboBox's item list. When using the DropDownList style, you can only set Text to values that actually appear in the list.</p>
<p>If it is the case that you are trying to set the text to Wildcards and that item does not appear in the list, and an alternative solution is not acceptable, you may have to be a bit dirty with the code and add an item temporarily that is removed when the drop-down list is expanded.</p>
<p>For example, if you have a form containing a combobox named "comboBox1" with some items and a button named "button1" you could do something like this:</p>
<pre><code>private void button1_Click(object sender, EventArgs e)
{
if (!comboBox1.Items.Contains("Wildcards"))
{
comboBox1.Items.Add("Wildcards");
}
comboBox1.Text = "Wildcards";
}
private void comboBox1_DropDown(object sender, EventArgs e)
{
if (comboBox1.Items.Contains("Wildcards"))
comboBox1.Items.Remove("Wildcards");
}
</code></pre>
<p>That's pretty quick and dirty but by capturing the DropDownClosed event too you could clean it up a bit, adding the "Wildcards" item back as needed.</p>
|
Best way to send email from my web app so it looks like it came from my users account <p>I'm working on a web application. A user will create an email message that will be sent to another person.</p>
<p>I would like the e-mail that gets sent to appear from the user's name and e-mail address of the user on my system. And if they reply to the e-mail then it should go directly to the sender's email address.</p>
<p>However I am worried about the email message looking like spam to email filters along the way.</p>
<p>Is there a proper way to do this?</p>
<p>I noticed on a "contact" page on a WordPress blog that something very similar is done. The e-mail headers look like:</p>
<pre><code>To: email@domain.com
Subject: [Test Blog] =?UTF-8?B?aGVsbA==?=
MIME-Version: 1.0
Content-Type: text/plain; charset="utf-8"
From:=?UTF-8?B?aGVsbA==?=<sender@senderdomain.com>
Message-Id: <20090207234737.39C9522802F3@web7.sat.wordpress.com>
Date: Sat, 7 Feb 2009 23:47:37 +0000 (UTC)
Return-Path: donotreply@wordpress.com
</code></pre>
<p>What is interesting is that the display name in the "from" tag and the name that shows up in the subject line is encoded. I do not know if this helps with the spam filters or not, but thought it was at least worth mentioning.</p>
<p>Also, who would receive an undeliverable notification in this example? Would it go to sender@senderdomain.com or would it go to donotreply@wordpress.com?</p>
| <p>Basically all you need to do is set the <code>From</code> header to the email address of the user sending the email. The value of <code>From</code> is what is displayed in a recipient's email client. Most spam detection systems in place today look only at the message content, not the email headers, so you currently wouldn't have that much of a problem based on what you set the From header to.</p>
<p>However, there are some systems which are gaining popularity which could prevent you from sending email with somebody else's email address - most notably SPF, the <a href="http://www.openspf.org/" rel="nofollow">Sender Policy Framework</a> Basically, a mail server that implements SPF will check the domain of the <code>From</code> address of each email it receives and check with that domain directly to see if it authorizes the email. For example, if your server is <code>mydomain.com</code>, the email address of the user is <code>abcdef@gmail.com</code>, and the recipient is <code>blah@example.com</code>,</p>
<ol>
<li><code>mydomain.com</code> contacts <code>example.com</code> via SMTP to try to send the email</li>
<li><code>example.com</code> looks up the SPF records for <code>gmail.com</code></li>
<li><code>example.com</code> checks whether <code>mydomain.com</code> is on the list of domains allowed to send email with the domain <code>gmail.com</code></li>
<li>If it's not, the email is blocked</li>
</ol>
<p>Also, I found a <a href="http://www.emaildiscussions.com/showthread.php?threadid=15009" rel="nofollow">forum post</a> suggesting that <code>Return-Path</code> is the intended destination for undeliverable notifications. Apparently that header is set based on the value of the SMTP MAIL FROM command.</p>
|
Ajax.BeginForm, user controls and updating something <p>I have a bit of a problem with user controls. Basically what I want to accomplish is the following:</p>
<ol>
<li>I have a view for editing an invoice.</li>
<li>In this view I have a usercontrol with a list of invoice items</li>
<li>I also have a div that is activated with jQuery for adding a new invoice item</li>
<li>When I add the invoice item I want to refresh just the user control with the list of items</li>
</ol>
<p>How would I do this without hacks? Something I was thinking of was the following:</p>
<pre><code>[AcceptVerbs(HttpVerbs.Post), ValidateAntiForgeryToken]
public ActionResult Create(InvoiceLine line)
{
if (Request.IsAjaxRequest())
{
if (!ModelState.IsValid)
{
return PartialView("CreateLineControl", product);
}
}
return PartialView("DisplayLinesControl", product);
}
</code></pre>
| <p>First you would call an aspx page w/ jQuery (we will use an http handler that we will map in the web.config below, more on this later)</p>
<p>the basic idea is that we want the server side to render the user control as xhtml and dump this "updated" markup back into the DOM in our success method (client side)</p>
<pre><code>$.ajax({
type: "GET",
url: "UserDetails.aspx?id=" + id,
dataType: "html",
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert(XMLHttpRequest.responseText);
},
success: function(xhtml)
{
var container = document.createElement('div');
container.innerHTML = xhtml;
document.getElementById('someElement').appendChild(container);
}
});
</code></pre>
<p>The technique below is what I used to leverage a user control via the HttpHandler to reuse the control
for both ajax and .net work</p>
<p>The below was done w/ .NET 1.1 (but i'm sure you can do it in .NET 2.0+)
the class below implements IHttpHandler, and the real work is in the process request sub as you can see below</p>
<p>The only issue I had with this at the time was that asp.net controls would not render w/out a form tag in the user
control so I used normal html and all was good</p>
<pre><code>Public Class AJAXHandler
Implements IHttpHandler
Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable
Get
Return False
End Get
End Property
Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest
Dim Request As System.Web.HttpRequest = context.Request
Dim path As String = Request.ApplicationPath
Dim newHtml As String
Dim pg As New System.Web.UI.Page
context.Response.Cache.SetCacheability(HttpCacheability.NoCache)
context.Response.ContentType = "text/html"
Dim uc As New UserDetail
uc = CType(pg.UserControl(path + "/Controls/UserDetail.ascx"), UserDetail)
Dim sb As New System.Text.StringBuilder
Dim sw As New System.IO.StringWriter(sb)
Dim htmlTW As New HtmlTextWriter(sw)
uc.LoadPage(custid, CType(pro, Integer))
uc.RenderControl(htmlTW)
context.Response.Write(sb.ToString())
context.Response.End()
End Sub
End Class
</code></pre>
<p>And finally in your web.config you need to define the handler and map it to the aspx path you listed in your ajax call</p>
<pre><code> <system.web>
<httpHandlers>
<add verb="*" path="UserDetails.aspx" type="project.AJAXHandler, project" />
</httpHandlers>
</system.web>
</code></pre>
<p>Now you can call the user control with UserDetails.aspx and render the user control as html. Then after you render this it will return html (after response.end is called)</p>
<p>then in javascript you can find the parent DOM element to your user control, remove it and append or innerHTML this new html</p>
<p><strong>Update</strong></p>
<p>Above is the solution I used with webforms, but with MVC the below will produce the same result with much less work.</p>
<p>The jQuery function would be the same but on the server side you would simply create a new controller action + PartialView w/ the markup you wanted (basically a user control)</p>
<pre><code>Function Edit(ByVal id As Integer) As ActionResult
Dim User As User = UserService.GetUserById(id)
Return PartialView("User", User)
End Function
</code></pre>
<p>Now inside my ascx I simply render the html and this is what gets sent back to the browser for the container.innerHTML work (again the client side code is the same for both MVC and Webforms in this scenario)</p>
<pre><code><%@ Control Language="VB" Inherits="System.Web.Mvc.ViewUserControl(Of User)" %>
<% Dim User As User = DirectCast(Model, User)%>
<div id="innerDetail">
<label for='username'>Username</label>
<input type="text" id='username' name='username' value="<%= User.Username %>" /><br />
<a id='lnkUpdate' href='/Application/User.aspx/Edit/<%= User.ID %>' onclick='UpdateUser(this); return false;'>Update User Information</a>
<span id='lblUpdateStatus' style='display: inline;'></span>
</div>
</div>
</code></pre>
<p>The reason this works with much less code in MVC is that we don't have to work around the page lifecycle that is required with a normal aspx file in webforms.</p>
|
NumPy, PIL adding an image <p>I'm trying to add two images together using NumPy and PIL. The way I would do this in <a href="http://en.wikipedia.org/wiki/MATLAB">MATLAB</a> would be something like:</p>
<pre><code>>> M1 = imread('_1.jpg');
>> M2 = imread('_2.jpg');
>> resM = M1 + M2;
>> imwrite(resM, 'res.jpg');
</code></pre>
<p>I get something like this:</p>
<p><img src="http://www.deadlink.cc/matlab.jpg" alt="alt text"></p>
<p>Using a compositing program and adding the images the MATLAB result seems to be right.</p>
<p>In Python I'm trying to do the same thing like this:</p>
<pre><code>from PIL import Image
from numpy import *
im1 = Image.open('/Users/rem7/Desktop/_1.jpg')
im2 = Image.open('/Users/rem7/Desktop/_2.jpg')
im1arr = asarray(im1)
im2arr = asarray(im2)
addition = im1arr + im2arr
resultImage = Image.fromarray(addition)
resultImage.save('/Users/rem7/Desktop/a.jpg')
</code></pre>
<p>and I get something like this:</p>
<p><img src="http://www.deadlink.cc/python.jpg" alt="alt text"></p>
<p>Why am I getting all those funky colors? I also tried using <code>ImageMath.eval("a+b", a=im1, b=im2)</code>, but I get an error about RGB unsupported.</p>
<p>I also saw that there is an <code>Image.blend()</code> but that requires an alpha.</p>
<p>What's the best way to achieve what I'm looking for?</p>
<p>Source Images (images have been removed):</p>
<p><img src="http://www.deadlink.cc/_1.jpg" alt="alt text">
<img src="http://www.deadlink.cc/_2.jpg" alt="alt text"></p>
<p>Humm, OK, well I added the source images using the add image icon and they show up when I'm editing the post, but for some reason the images don't show up in the post. </p>
<p>(images have been removed) 2013 05 09</p>
| <p>As everyone suggested already, the weird colors you're observing are overflow. And as you point out in the <a href="http://stackoverflow.com/questions/524930/numpy-pil-adding-an-image/524943#524943">comment of schnaader's answer</a> you <strong>still get overflow</strong> if you add your images like this:</p>
<pre><code>addition=(im1arr+im2arr)/2
</code></pre>
<p>The reason for this overflow is that your NumPy arrays (<em>im1arr</em> <em>im2arr</em>) are of the <strong>uint8</strong> type (i.e. 8-bit). This means each element of the array can only hold values up to 255, so when your sum exceeds 255, it loops back around 0:</p>
<pre><code>>>>array([255,10,100],dtype='uint8') + array([1,10,160],dtype='uint8')
array([ 0, 20, 4], dtype=uint8)
</code></pre>
<p>To avoid overflow, your arrays should be able to contain values beyond 255. You need to <strong>convert them to floats</strong> for instance, perform the blending operation and <strong>convert the result back to uint8</strong>:</p>
<pre><code>im1arrF = im1arr.astype('float')
im2arrF = im2arr.astype('float')
additionF = (im1arrF+im2arrF)/2
addition = additionF.astype('uint8')
</code></pre>
<p>You <strong>should not</strong> do this:</p>
<pre><code>addition = im1arr/2 + im2arr/2
</code></pre>
<p>as you lose information, by squashing the dynamic of the image (you effectively make the images 7-bit) before you perform the blending information.</p>
<p><strong>MATLAB note</strong>: the reason you don't see this problem in MATLAB, is probably because MATLAB takes care of the overflow implicitly in one of its functions.</p>
|
python coding speed and cleanest <p>Python is pretty clean, and I can code neat apps quickly.
But I notice I have some minor error someplace and I dont find the error at compile but at run time. Then I need to change and run the script again. Is there a way to have it break and let me modify and run?</p>
<p>Also, I dislike how python has no enums. If I were to write code that needs a lot of enums and types, should I be doing it in C++? It feels like I can do it quicker in C++.</p>
| <p><strong>"I don't find the error at compile but at run time"</strong></p>
<p>Correct. True for all non-compiled interpreted languages.</p>
<p><strong>"I need to change and run the script again"</strong></p>
<p>Also correct. True for all non-compiled interpreted languages.</p>
<p><strong>"Is there a way to have it break and let me modify and run?"</strong></p>
<p>What?</p>
<p>If it's a run-time error, the script breaks, you fix it and run again.</p>
<p>If it's not a proper error, but a logic problem of some kind, then the program finishes, but doesn't work correctly. No language can anticipate what you hoped for and break for you.</p>
<p>Or perhaps you mean something else.</p>
<p><strong>"...code that needs a lot of enums"</strong></p>
<p>You'll need to provide examples of code that needs a lot of enums. I've been writing Python for years, and have no use for enums. Indeed, I've been writing C++ with no use for enums either.</p>
<p>You'll have to provide code that needs a lot of enums as a specific example. Perhaps in another question along the lines of "What's a Pythonic replacement for all these enums."</p>
<p>It's usually polymorphic class definitions, but without an example, it's hard to be sure.</p>
|
LdapContext, how to do select count(*) <p>I am using an LdapContext in java to query an LDAP server (I think the server is Sun server version 5.2).
I use the LdapContext.search(String name, String filter, SearchControls cons) method for the regular querys, but I don't know how to run a query equivalent to sql's "select count(*)".
Any idea? Performance is important so I don't want to just run a regular query and count the results.</p>
| <p>Have you tried the Context.list(String name) method? I don't know about the performance and you can't apply filters.</p>
|
which design pattern to use for filtering query? c# <p>I have a database table with a list of products (clothing). The products belong to categories and are from different stores.</p>
<p>Sample categories: tops, bottoms, shoes</p>
<p>Sample stores: gap.com, macys.com, target.com</p>
<p>My customers can request to filter products in the following ways:</p>
<ul>
<li>all products (no filter)</li>
<li>by category</li>
<li>by store</li>
<li>by category and store</li>
</ul>
<p>Right now I have ONE method in my "Products" class that returns the products depending on the type of filter requested by the user. I use a FilterBy enum to determine which products need to be returned.</p>
<p>For example, if the user wants to view all products in the "tops" category I call this function:</p>
<pre><code>Products.GetProducts(FilterBy.Category, "tops", "");
</code></pre>
<p>I have the last parameter empty because it's the string that contains the "store" to filter by but in this case there is no store. However, if the user wants to filter by category AND store I'd call the method this way:</p>
<pre><code>Product.GetProducts(FilterBy.CategoryAndStore, "tops", "macys.com");
</code></pre>
<p>My question is, what's a better way to do this? I just learned about the strategy design pattern. Could I use that to do this in a better (easier to extend and easier to maintain) way?</p>
<p>The reason I'm asking this question is because I figure this must be a pretty common problem that people are repeatedly solving (filtering products in various ways)</p>
| <p>According to Eric Evan's "Domain Drive Design" you need the specification pattern. Something like this</p>
<pre><code>public interface ISpecification<T>
{
bool Matches(T instance);
string GetSql();
}
public class ProductCategoryNameSpecification : ISpecification<Product>
{
readonly string CategoryName;
public ProductCategoryNameSpecification(string categoryName)
{
CategoryName = categoryName;
}
public bool Matches(Product instance)
{
return instance.Category.Name == CategoryName;
}
public string GetSql()
{
return "CategoryName like '" + { escaped CategoryName } + "'";
}
}
</code></pre>
<p>Your repository can now be called with specifications</p>
<pre><code>var specifications = new List<ISpecification<Product>>();
specifications.Add(
new ProductCategoryNameSpecification("Tops"));
specifications.Add(
new ProductColorSpecification("Blue"));
var products = ProductRepository.GetBySpecifications(specifications);
</code></pre>
<p>You could also create a generic CompositeSpecification class which would contain sub specifications and an indicator as to which logical operator to apply to them AND/OR</p>
<p>I'd be more inclined to combine LINQ expressions though.</p>
<p><strong>Update - Example of LINQ at runtime</strong></p>
<pre><code>var product = Expression.Parameter(typeof(Product), "product");
var categoryNameExpression = Expression.Equal(
Expression.Property(product, "CategoryName"),
Expression.Constant("Tops"));
</code></pre>
<p>You can add an "and" like so</p>
<pre><code>var colorExpression = Expression.Equal(
Expression.Property(product, "Color"),
Expression.Constant("Red"));
var andExpression = Expression.And(categoryNameExpression, colorExpression);
</code></pre>
<p>Finally you can convert this expression into a predicate and then execute it...</p>
<pre><code>var predicate =
(Func<Product, bool>)Expression.Lambda(andExpression, product).Compile();
var query = Enumerable.Where(YourDataContext.Products, predicate);
foreach(Product currentProduct in query)
meh(currentProduct);
</code></pre>
<p>Probably wont compile because I have typed it directly into the browser, but I believe it is generally correct.</p>
<p><strong>Another update</strong> :-)</p>
<pre><code>List<Product> products = new List<Product>();
products.Add(new Product { CategoryName = "Tops", Color = "Red" });
products.Add(new Product { CategoryName = "Tops", Color = "Gree" });
products.Add(new Product { CategoryName = "Trousers", Color = "Red" });
var query = (IEnumerable<Product>)products;
query = query.Where(p => p.CategoryName == "Tops");
query = query.Where(p => p.Color == "Red");
foreach (Product p in query)
Console.WriteLine(p.CategoryName + " / " + p.Color);
Console.ReadLine();
</code></pre>
<p>In this case you would be evaluating in memory because the source is a List, but if your source was a data context that supported Linq2SQL for example I <strong>think</strong> this would evaluate using SQL. </p>
<p>You could still use the Specification pattern in order to make your concepts explicit.</p>
<pre><code>public class Specification<T>
{
IEnumerable<T> AppendToQuery(IEnumerable<T> query);
}
</code></pre>
<p>The main difference between the two approaches is that the latter builds a known query based on explicit properties, whereas the first one could be used to build a query of any structure (such as building a query entirely from XML for example.)</p>
<p>This should be enough to get you started :-)</p>
|
Java: Accounting for taskbars/menubars/etc when placing a window on the desktop? <p>When my program starts, the main window places itself where it was when it was last closed. I want to modify this behavior some so if the window is off-screen (or partially off-screen) it moves itself to fully on screen. </p>
<p>I've got this working perfectly. Here's the code:<br><br></p>
<pre><code> int x = gameConfig.windowX;
int y = gameConfig.windowY;
int width = gameConfig.windowWidth;
int height = gameConfig.windowHeight;
if( x < 0 ) x = 0;
if( y < 0 ) y = 0;
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if( x + width > screenSize.width ) x = screenSize.width - width;
if( y + height > screenSize.height ) y = screenSize.height - height;
if( width > screenSize.width ) width = screenSize.width;
if( height > screenSize.height ) height = screenSize.height;
this.setLocation(x, y);
this.setSize(width, height );
if( gameConfig.screenMaximized ) {
this.setExtendedState(getExtendedState() | MAXIMIZED_BOTH );
}
</code></pre>
<p><br><br>
This works as expected, but with one big exception; it doesn't account for taskbars. On windows, if the window is past the bottom of the screen, this code will correct it, but it still leaves a piece of the window blocked by the taskbar.</p>
<p>I'm not sure how to do this. Is there someway to ask java about any taskbars in the system, and what their width/height is?</p>
<hr>
<p>Thanks that worked perfectly.</p>
<p>Do you know how to get it so Java will reflect the total screen size of both of my monitors when I call getScreenSize() ? Right now it is returning 1600x1200, when it's really 3200x1200, spanned across two monitors.</p>
<p>The Java API suggests that GraphicsConfiguration.getBounds() would do the trick, but that still returns the rectangle {0, 0, 1600, 1200}. </p>
| <p>Use getScreenInsets (Java 4+):</p>
<pre><code>static public Insets getScreenInsets(Window wnd) {
Insets si;
try {
if(wnd==null) { si=Toolkit.getDefaultToolkit().getScreenInsets(new Frame().getGraphicsConfiguration()); }
else { si=wnd.getToolkit() .getScreenInsets(wnd.getGraphicsConfiguration()); }
} catch(NoSuchMethodError thr) { si=new Insets(0,0,0,0); }
return si;
}
</code></pre>
<p>(This method allows for multiple screens, and older JVM's that don't support the API).</p>
<p>And, always remember the task bar may be on any edge of the screen, not just the bottom.</p>
|
C# to SQL Server on client's network <p>I have a client with an established accounting database for which I want to write a report. I am planning to use VS 2008. I have no difficulty doing this for SQL Server running on my own machine but want to know how best to publish a c# program to run on the client's network SQL Server. So there are two main issues:
1.) How to adapt the connection string for the remote environment?
2.) A recommendation for good remote assistance method for a fledgling contractor working on someone else's network.</p>
| <p>Store the connection string in a configuration file (Visual Studio will do this for you most of the time now) and just adjust it when you deploy the app on the client's network.</p>
<p>Remote Assistance Method - check out Microsoft SharedView, and if you want to pay for a higher-end solution, LogMeIn Rescue. Edit - Also, check out TeamViewer (www.teamviewer.com).</p>
<p>Additional Information on Remote Clients:</p>
<p><strong>SharedView</strong> - <a href="http://connect.microsoft.com/site/sitehome.aspx?SiteID=94" rel="nofollow">http://connect.microsoft.com/site/sitehome.aspx?SiteID=94</a> - Free, requires Windows Live ID, up to 15 people can watch a screen and you can change presenters at any time.</p>
<p><strong>TeamViewer</strong> - <a href="http://www.teamviewer.com" rel="nofollow">http://www.teamviewer.com</a> - Free (and / or pay version) - Start up in "Remote Support", "Presenter", "File Transfer", or "VPN" mode. Can switch sides with partner easily. (Warning - I've had issues with using this in Vista with the UAC command prompts).</p>
<p><strong>LogMeIn Rescue</strong> - <a href="http://www.logmein.com" rel="nofollow">http://www.logmein.com</a> - Pay Product (expensive but extremely nice tool for professional client support). One-way (can't change sides with customer).</p>
|
How to remove diagramming support objects from SQL Server? <p>I need to remove diagramming support tables, stored procs, views, etc from SQL Servrer using TSQL script. </p>
<p>Is there such a script available? </p>
<p>SQL 2005 and 2008.</p>
| <pre><code>DROP PROCEDURE dbo.sp_alterdiagram;
DROP PROCEDURE dbo.sp_creatediagram;
DROP PROCEDURE dbo.sp_dropdiagram;
DROP PROCEDURE dbo.sp_helpdiagramdefinition;
DROP PROCEDURE dbo.sp_renamediagram;
DROP PROCEDURE dbo.sp_upgraddiagrams;
DROP PROCEDURE dbo.sp_helpdiagrams;
DROP FUNCTION dbo.fn_diagramobjects;
DROP TABLE dbo.sysdiagrams;
</code></pre>
<p>That removes all of them. Would be nice if there was as remove diagrams references wizard like the add.</p>
|
How are variables on the stack accessed? <p>Suppose we have these local variables:</p>
<pre><code>int a = 0;
int b = 1;
int c = 2;
int d = 3;
</code></pre>
<p>As far as I know, these will be allocated on the system stack, like this:</p>
<pre><code>| |
| 3 | d
| 2 | c
| 1 | b
|_0_| a
</code></pre>
<p>Does this mean that in order to get the value of a, the values of d, c and b must first be popped out of the stack? If so, where do these values go? Does this mean that accessing more recently declared variables will be faster? Or am I missing something (which I suspect is the case), and the whole thing works in some other way?</p>
<p><strong>EDIT:</strong> thanks, guys!</p>
| <p>The local variables on the stack are usually accessed relative to the so-called <i>frame pointer</i>, which points at the start of your stack frame. It would also be possible to do this relative to the stack pointer, but since this moves around during evaluation of expressions it is more difficult to keep track of.</p>
<p>In practice such variables may also be kept in processor registers.</p>
|
Large Text and Images In SQL <p>Is it a good idea to store large amounts of text (eg html pages) inside your SQL database? Or is it a better idea to store it as html files in the filesystem?</p>
<p>The same goes for images - is it a good idea to store image data in the database or better to put them on disk?</p>
<p>Will storing large amounts of data cause me performance problems for example? What are the pros and cons of each method of storage?</p>
<p>In terms of the size of data, in this case I am looking in the region of "a few pages" of HTML and images less than about 500kb in size (probably a lot smaller though). Enough to produce your average article/blog entry/etc scale web page.</p>
| <p>Storing binary data (documents, images etc) in the database has some advantages.</p>
<ul>
<li><p>You can commit the update of the document itself in the same transaction as the information (name, date etc) you want to store about the document. This means you don't have to worry about writing your own two-phase commit (although ISTR that SQL Server 2008 has a solution for this).</p></li>
<li><p>You can back up the whole lot (documents and metadata) at once, without worrying about having to synchronise the database with the file system</p></li>
<li><p>You can deliver documents very simply over .NET web services, since they come straight out into DataTables, and are serialised effortlessly just by putting the DataTables into a DataSet and passing it.</p></li>
<li><p>You can apply database security to the objects, as to the rest of your data, and not have to worry about network file permissions.</p></li>
</ul>
<p>It does have some disadvantages too:</p>
<ul>
<li><p>Backups can get very large</p></li>
<li><p>The size of the binary object in the database can be quite a bit larger than the file it originally came from, and therefore in a client-server environment, it can increase the time taken to open them across the network.</p></li>
<li><p>Depending on the application, you might need to consider the load on the database server if it has to serve up a lot of large documents.</p></li>
</ul>
<p>All that said, it's a technique I use extensively, and it works very well.</p>
|
Pathname.rb error on running a minitest testcase <p>I'm running Ruby 1.8.6. </p>
<p>I installed the minitest 1.3.1 gem, which is the new defacto replacement for the Test::Unit framework in Ruby 1.9 The API is supposed to be the same.</p>
<p>I wrote a small test to get things rolling:</p>
<pre><code>require 'rubygems'
gem 'minitest'
require 'minitest/unit'
MiniTest::Unit.autorun
class CategoryMiniTest < MiniTest::Unit::TestCase
def test_twoCategoriesCannotHaveSameName
assert_equals(2,2)
end
end
</code></pre>
<p>Which leads to:</p>
<pre><code>>ruby test\unit\category_mini_test.rb
l:/ruby_home/lib/ruby/1.8/pathname.rb:709:in `relative_path_from': different prefix: "l:/" and "L:/Gishu/Ruby/Rails/ShowMeTheMoney" (ArgumentError)
from l:/ruby_home/lib/ruby/gems/1.8/gems/minitest-1.3.1/lib/minitest/unit.rb:17
</code></pre>
<p>What gives?</p>
| <p>I can't see anything wrong with your code. It looks almost exactly the same as the Ruby 1.8.6 & MiniTest example in my blog post: <a href="http://blog.floehopper.org/articles/2009/02/02/test-unit-and-minitest-with-different-ruby-versions" rel="nofollow">Test::Unit and MiniTest with different Ruby versions</a>.</p>
<p>So I wonder if it is:</p>
<ol>
<li>something to do with your environment,</li>
<li>something to do with how you are running the test, or</li>
<li>a bug in MiniTest.</li>
</ol>
<p>Looking at the error message, I wonder whether the problem is with case-sensitivity - the upper-case and lower-case <code>L</code> drive letters may not match.</p>
|
Should I use Java applets or Flash to make webpage-embeddable physics simulations? <p>I want to start working on some simple physics simulations that I can embed onto my website. I have a lot of experience with web programming with languages like PHP and javascript, a fair amount of experience with python and some experience with C++.</p>
<p>Should I use Java applets, Flash or something else?</p>
<p>Also, could you please recommend a good IDE and point me in the direction of some tutorials?</p>
| <p>I have a fair amount in pyhsics and java applet and flash.</p>
<p>I strongly recommend doing it in flash. First of all is the flash player much better distributed than the java runtime. Second is it since flash player 9 (10 is current) and actionscript3 much faster and less ressource hungry.</p>
<p>There are some pyhsics frameworks:</p>
<ul>
<li><a href="http://www.cove.org/ape/" rel="nofollow">http://www.cove.org/ape/</a></li>
<li><a href="http://box2dflash.sourceforge.net/" rel="nofollow">http://box2dflash.sourceforge.net/</a></li>
</ul>
<p>There are allready 3d pyhsic engines for flash. but they are still very young:</p>
<ul>
<li><a href="http://drawlogic.com/2009/01/12/as3-flashflex-3d-physics-engine-jiglibflash-based-on-jiglib-c-3d-physics-engine/" rel="nofollow">http://drawlogic.com/2009/01/12/as3-flashflex-3d-physics-engine-jiglibflash-based-on-jiglib-c-3d-physics-engine/</a></li>
<li><a href="http://seraf.mediabox.fr/wow-engine/as3-3d-physics-engine-wow-engine/" rel="nofollow">http://seraf.mediabox.fr/wow-engine/as3-3d-physics-engine-wow-engine/</a></li>
</ul>
<p>For the IDEs I recommend the following:</p>
<ul>
<li>Opensource: <a href="http://www.flashdevelop.org/community/" rel="nofollow">http://www.flashdevelop.org/community/</a></li>
<li>Best AS2 & 3 editor: <a href="http://fdt.powerflasher.com/" rel="nofollow">http://fdt.powerflasher.com/</a></li>
<li>Standard & Proprietary: <a href="http://www.adobe.com/products/flex/" rel="nofollow">http://www.adobe.com/products/flex/</a></li>
</ul>
<p>The Flex SDK (compiler for as3 + flex) is free and / or opensource:</p>
<ul>
<li><a href="http://www.adobe.com/products/flex/flexdownloads/index.html" rel="nofollow">http://www.adobe.com/products/flex/flexdownloads/index.html</a></li>
</ul>
<p>I think you will find alot of tutorials on the sites for the frameworks. Have fun and share your results :D</p>
|
Bind POCO to UserControl <p>Hi I am in the process of writing my first .net gui. I am wondering if there is some specific way I need to apply to my poco objects for them to be bindable to a usercontrol. I have a few objects but I seem to be unable to bind them to my usercontrol. </p>
<p>I read somewhere that they need to implement IBindable but I can't shake the feeling that someone already has eliminated all that duplicate code I would have to input into all my classes. Is there a way to easily bind these or would I have to use datasets or the like to be easily get this binding working. I have an extreme distaste for datasets to please present some other decent options ;-)</p>
<p>I am trying to bind to usercontrols from the devexpress toolkit.</p>
| <p>Which architecture?</p>
<p>For 1-way binding, you don't need anything other than public properties - and maybe some <code>TypeConverter</code> implementations for any bespoke data types (<code>struct</code>s etc)</p>
<p>For full 2-way binding, you'll need an eventing implementation - any of:</p>
<ul>
<li>a "public event EventHandler FooChanged" for every property "Foo"</li>
<li>an `INotifyPropertyChanged implementation</li>
<li>a bespoke component-model (don't go there - overkill)</li>
</ul>
<p>For an example of a <code>INotifyPropertyChanged</code> implementation (note you might want to move some of the code for re-use) :</p>
<pre><code>public class Foo : INotifyPropertyChanged
{
private string bar;
public string Bar
{
get { return bar; }
set { UpdateField(ref bar, value, "Bar"); }
}
// other properties...
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null) PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
protected bool UpdateField<T>(ref T field, T value,
string propertyName)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
OnPropertyChanged(propertyName);
return true;
}
return false;
}
}
</code></pre>
<p>To bind <em>sets</em> of data (grids etc), the easiest thing is to use generics; basically, the <em>minumum</em> is <code>IList</code> - but you get extra metadata from a <code>public T this[int index]</code> indexer - which <code>List<T></code>, <code>Collection<T></code> etc all have. More - <code>BindingList<T></code> implements <code>IBindingList</code> allowing collection-based notification events (but only to <code>INotifyPropertyChanged</code> - not to the <code>FooChanged</code> pattern).</p>
|
HQL "Contains" statement howto? <p>I have an entity that has a string property called Tags. I would like to query this entity based upon if a certain string is located in Tags property.</p>
<p>So for example, I would have a function IList GetEntityByTag(string tag), this would return all Entity's that have the value of tag in their 'Tags' property.</p>
<p>I tried going through the ICriteria approach... Expression.In(PropertyName, Value) but this is the exact opposite. I need something like Expression.In(Value, PropertyName).</p>
<p>Perhaps IQuery would be a better strategy but I have not been able to find any type of HQL statment for Property CONTAINS 'abc'.</p>
<p>Any help or point of direction would be great thanks!</p>
| <p>If you want to know if a tag is a substring in your Tags property, you might want to consider these tips:</p>
<ul>
<li>You might want to convert both the string you are searching in and searching for to lowercase first. Expression.ilike does this for you. Score.</li>
<li>To find out if your search term is anywhere in the field, you can set the MatchMode parameter in the ilike function to MatchMode.ANYWHERE. </li>
</ul>
<p>If, as you commented earlier, </p>
<blockquote>
<p>let's say my property, 'Tags' =
a;b;c;d;e. I want to know if 'a'
exists in tags. Will
Expression.Like("Tags", "a") return
true?</p>
</blockquote>
<p>If 'a;b;c;d;e' is a string, Expression.ilike( "Tags", "a", MatchMode.ANYWHERE ) will return true.</p>
|
JSP -- default value for EL functions arguments <p>Is there a way to have default values for EL functions arguments (e.g., optional arguments)?</p>
| <p>you can make your own tags, which supply these values that will wrap the functions you are trying to call. JSP2.1 has .tag files that are basically jsp files, and it would be VERY easy to define default values using those.</p>
|
How to add background images to Delphi forms <p>How can I add a background image to my delphi form? I added a TImage, but now the labels aren't visible any more, and the texts of my checkboxes are in a blue "box" (blue is the background color i chose). This blue doesn't look very good on the background image, and the hidden labels also don't look good. How do I fix these problems?</p>
| <p>For the labels: make sure that they are transparent (Transparent property in the Object Inspector), and that they are on top of the TImage in the Z-order of controls. To correct this you can execute the "Send to back" command on the TImage component in design mode, it will make all other non-windowed controls appear on top of it.</p>
<p>For the checkboxes I don't know what the problem in your case is, in Delphi 2007 checkboxes appear properly transparent when put over a TImage. Maybe you use an earlier Delphi version? If so it would be good to mention this in the question. There may also be a different behaviour depending on whether themes are active. Again, hard to say without further information.</p>
|
Linq-to-entities: How to create objects (new Xyz() vs CreateXyz())? <p>What is the best way of adding a new object in the entity framework. The designer adds all these create methods, but to me it makes more sense to call new on an object. The generated CreateCustomer method e.g. could be called like this:</p>
<pre><code>Customer c = context.CreateCustomer(System.Guid.NewGuid(), "Name"));
context.AddToCustomer(c);
</code></pre>
<p>where to me it would make more sense to do:</p>
<pre><code>Customer c = new Customer {
Id = System.Guid.NewGuid(),
Name = "Name"
};
context.AddToCustomer(c);
</code></pre>
<p>The latter is much more explicit since the properties that are being set at construction are named. I assume that the designer adds the create methods on purpose. Why should I use those? </p>
| <p>As Andrew says (up-voted), it's quite acceptable to use regular constructors. As for why the "Create" methods exist, I <em>believe</em> the intention is to make explicit which properties are required. If you use such methods, you can be assured that you have not forgotten to set any property which will throw an exception when you SaveChanges. However, the code generator for the Entity Framework doesn't quite get this right; it includes server-generated auto increment properties, as well. These are technically "required", but you don't need to specify them.</p>
|
Byte order with a large array of characters in C <p>Hey guys, question from a C/Networking newbie...</p>
<p>I'm doing some socket programming in C and trying to wrestle with byte order problems. My request (send) is fine but when I receive data my bytes are all out of order. I start with something like this...</p>
<pre><code>char * aResponse= (char *)malloc(512);
int total = recv(sock, aResponse, 511, 0);
</code></pre>
<p>When dealing with this response, each 16bit word seems to have it's bytes reversed (I'm using UDP). I tried to fix that by doing something like this...</p>
<pre><code> unsigned short * _netOrder= (unsigned short *)aResponse;
unsigned short * newhostOrder= (unsigned short *)malloc(total);
for (i = 0; i < total; ++i)
{
newhostOrder[i] = ntohs(_netOrder[i]);
}
</code></pre>
<p>This works ok when I'm treating the data as a short, however if I cast the pointer to a char again the bytes are reversed. What am I doing wrong?</p>
<p>Thanks!</p>
| <p>Ok, there seems to be problems with what you are doing on two different levels. Part of the confusion here seems to stem for your use of pointers, what type of objects they point to, and then the interpretation of the encoding of the values in the memory pointed to by the pointer(s).</p>
<p>The encoding of multi-byte entities in memory is what is referred to as endianess. The two common encodings are referred to as <strong><em>Little Endian</em></strong> (LE) and <strong>Big Endian</strong> (BE). With LE, a 16-bit quantity like a short is encoded least significant byte (LSB) first. Under BE, the most significant byte (MSB) is encoded first.</p>
<p>By convention, network protocols normally encode things into what we call "network byte order" (NBO) which also happens to be the same as BE. If you are sending and receiving memory buffers on big endian platforms, then you will not run into conversion problems. However, your code would then be platform dependent on the BE convention. If you want to write portable code that works correctly on both LE and BE platforms, you should not assume the platform's endianess.</p>
<p>Achieving endian portability is the purpose of routines like <strong><em>ntohs()</em></strong>, <strong><em>ntohl()</em></strong>, <strong><em>htons()</em></strong>, and <strong><em>htonl()</em></strong>. These functions/macros are defined on a given platform to do the necessary conversions at the sending and receiving ends:</p>
<ul>
<li><em><strong>htons()</em></strong> - Convert short value from host order to network order (for sending)</li>
<li><em><strong>htonl()</em></strong> - Convert long value from host order to network order (for sending)</li>
<li><em><strong>ntohs()</em></strong> - Convert short value from network order to host order (after receive)</li>
<li><em><strong>ntohl()</em></strong> - Convert long value from network order to host order (after receive)</li>
</ul>
<p>Understand that your comment about accessing the memory when cast back to characters has no affect on the actual order of entities in memory. That is, if you access the buffer as a series of bytes, you will see the bytes in whatever order they were actually encoded into memory as, whether you have a BE or LE machine. So if you are looking at a NBO encoded buffer after receive, the MSB is going to be first - always. If you look at the output buffer after your have converted back to host order, if you have BE machine, the byte order will be unchanged. Conversely, on a LE machine, the bytes will all now be reversed in the converted buffer.</p>
<p>Finally, in your conversion loop, the variable <code>total</code> refers to bytes. However, you are accessing the buffer as <code>shorts</code>. Your loop guard should not be <code>total</code>, but should be:</p>
<p><code>total / sizeof( unsigned short )</code></p>
<p>to account for the double byte nature of each <code>short</code>.</p>
|
Handling overflow when casting doubles to integers in C <p>Today, I noticed that when I cast a double that is greater than the maximum possible integer to an integer, I get -2147483648. Similarly, when I cast a double that is less than the minimum possible integer, I also get -2147483648. </p>
<p>Is this behavior defined for all platforms?<br />
What is the best way to detect this under/overflow? Is putting if statements for min and max int before the cast the best solution?</p>
| <p><code>limits.h</code> has constants for max and min possible values for integer data types, you can check your double variable before casting, like</p>
<pre><code>if (my_double > nextafter(INT_MAX, 0) || my_double < nextafter(INT_MIN, 0))
printf("Overflow!");
else
my_int = (int)my_double;
</code></pre>
<p>EDIT: <code>nextafter()</code> will solve the problem mentioned by nwellnhof</p>
|
Present tabular data on webpage so the user can directly copy it into Excel <p>On my webpage I want to able to present tabular data and give the user the possibility to copy it directly into excel. This however doesn't work, all of the data is pasted in one cell:</p>
<pre><code><table>
<tr><td>Column 1</td><td>Column 2</td></tr>
<tr><td>Data 1.1</td><td>Data 2.1</td></tr>
<tr><td>Data 1.2</td><td>Data 2.2</td></tr>
</table>
</code></pre>
<p>How to present this data so it can be copied directly into excel.</p>
| <p>I just thought of the solution while typing out the question. You need to specify the table body:</p>
<pre><code><table>
<tbody>
<tr><td>Column 1</td><td>Column 2</td></tr>
<tr><td>Data 1.1</td><td>Data 2.1</td></tr>
<tr><td>Data 1.2</td><td>Data 2.2</td></tr>
</tbody>
</table>
</code></pre>
|
@@DBTS in MySql <p>Hey guys, I want to ask if there is an equivalent to the @@DBTS TSQL global variable in MySql (I need to access the timestamp of the last row that has been accessed in the whole database, not just one table).</p>
<p>I need this because I'm trying to use Microsoft Sync Framework and MySql for bi-directional syncing.</p>
<p>Any help will be much appreciated. Thanks.</p>
| <p>The closest you can get, as far as I know, is a query like this:</p>
<pre><code>USE INFORMATION_SCHEMA;
SELECT MAX(UPDATE_TIME) FROM TABLES WHERE UPDATE_TIME < NOW();
</code></pre>
<p>The <code>INFORMATION_SCHEMA</code> database holds several tables of attributes of all tables in the database. The reason for the <code>WHERE UPDATE_TIME < NOW()</code> clause is that simply by running that query, you cause MySQL to update some of the tables in <code>INFORMATION_SCHEMA</code>, so without the <code>WHERE</code> clause you'd always just get the current time.</p>
<p>Obviously, if your MySQL database is really busy, so that all tables are updated basically every second, this query won't work, but in that case you might as well just sync as often as possible because you know there'll be modifications.</p>
|
Embed Flash Object by bypassing rules? <p>Hi there
i want to embed a youtube video to a profile page, but the social system does not allow embedding flash objects</p>
<p>now i wonder if theres a possibility to bypass this rule, the first thing i was thinking of was embedding an iframe to a page that links the object.</p>
<p>sadly the social network also disallows iframes.</p>
<p>do you have any idea?</p>
<p>Thanks in advance</p>
| <p>Have you tried using javascript to generate the flash object?</p>
<p>I use swfobject (<a href="http://blog.deconcept.com/swfobject/" rel="nofollow">http://blog.deconcept.com/swfobject/</a>)</p>
<h2>Html</h2>
<pre><code><div id="youTubVideo">
Loading You Tube Video
</div>
</code></pre>
<h2>Script</h2>
<pre><code><script type="text/javascript" src="swfobject.js>
</script>
<script type="text/javascript">
var youTubeClip = new SWFObject("http://www.youtube.com/v/G3NueKXS6dk&hl=en&fs=1", "youTubVideo", "425", "344", "8", "#ffffff");
youTubeClip.addParam("allowFullScreen", "true");
youTubeClip.write("youTubVideo");
</script>
</code></pre>
|
Tool for distributed HTTP benchmarking? <p>I would like to benchmark a website that our company is developing. It will consist of multiple web- and backend-servers. </p>
<p>To be able to properly simulate a large amount of request, I was thinking about using our dev machines (approx 15 Xp/Vista) and a few spare Red Hat servers as benchmarking clients.</p>
<p>Is there any tool that would let me set up these machines as slaves/clients, and then control them into performing a combined benchmark and get aggregated results?</p>
<p>The benchmark would consist of simulating a normal user logging in and surfing a few pages.</p>
| <p><a href="http://jmeter.apache.org/" rel="nofollow">Apache JMeter</a> is a reference in this domain.
You will setup on JMeter as controller and as many slaves as you need for your load depending on available memory and cpu.</p>
<p>In you case it's better to use non gui testing
for better performances results.</p>
|
Standard behavior of tellp on empty ostringstream <p>I have a question on the standard behavior of calling <code>tellp</code> on an empty <code>ostringstream</code>. I have a function foo which calls <code>tellp</code> the first thing:</p>
<pre><code>void foo(std::ostream& os)
{
std::ostream::pos_type pos = os.tellp();
// do some stuff.
}
int main()
{
std::ostringstream os;
foo(os);
}
</code></pre>
<p>In Visual Studio 2005, calling this function with a newly created and empty <code>ostringstream</code> results in the <code>pos</code> variable to be set to an invalid <code>pos_type</code>, which in Visual Studio 2005 is set to <code>pos_type(_BADOFF)</code>.</p>
<p><code>ofstream</code> does not have the same behavior, where <code>tellp</code> returns <code>pos_type(0)</code>, which is a valid <code>pos_type</code>.</p>
<p>Is this standard conforming behavior? Is this behavior consistent with other compilers?</p>
| <p>27.6.2.4:</p>
<pre><code>pos_type tellp();
</code></pre>
<blockquote>
<p>Returns: if fail() != false, returns
pos_type(-1) to indicate failure.
Otherwise, returns
rdbuf()->pubseekoff(0, <em>cur</em>, <em>out</em>).</p>
</blockquote>
<p>And <em>pubseekoff</em> returns -1 on fail. But am not sure why this happens for you in the case of <em>ostringstream</em>, maybe was too tired to find the words about <em>undefined</em> or <em>implementation-dependent</em>. Using my common sense I would say that for <em>ostringstream</em> this should give 0, for default constructed ostream -1, and for ostream with freshly opened file 0.</p>
|
Html.Checkbox does not preserve its state in ASP.net MVC <p>I have this annoying issue with the checkbox created using the <code>Html.Checkbox</code> extension method. Apparently the state of the checkbox is not saved in case of a postback (due to a form validation error). Delving into the MVC code itself (<code>System.Web.Mvc.Html.InputExtensions</code>) I found out that the 'checked' property is determined by calling <code>htmlHelper.EvalBoolean(name)</code>. </p>
<p>This method looks for the key (specified in the name argument) of the ViewData itself. The problem is that the value of the checkbox is actually located in the ModelState. Calling
<code>htmlHelper.GetModelStateValue(name, typeof(bool))</code> would return the expected result.</p>
<p>Is this a flaw in the checkbox implementation ? </p>
| <p>This issue was posted on <a href="http://www.codeplex.com/aspnet/WorkItem/View.aspx?WorkItemId=3136" rel="nofollow">codeplex</a> and will be fixed/supported in the MVC RTM. In the meantime, this is a nice <a href="http://174.129.228.43/archive/2009/02/09/4.aspx" rel="nofollow">workaround</a>.</p>
|
How to calculate the number of operations that occur during the execution of a for loop? <p>I had an exam a couple of days ago and today the Instructor gave us the key answer of the exam.</p>
<p>One of the questions was</p>
<blockquote>
<pre><code>for ( j = 9; j >= 1; j-- )
</code></pre>
<p>Count the Number of operations</p>
</blockquote>
<p>The result was 20.</p>
<p>Can anyone explain how he gets 20 operations from that?</p>
| <p>20 operations:</p>
<pre><code>set j = 9
check if j(9) >= 1
set j to 8
check if j(8) >= 1
set j to 7
check if j(7) >= 1
set j to 6
check if j(6) >= 1
set j to 5
check if j(5) >= 1
set j to 4
check if j(4) >= 1
set j to 3
check if j(3) >= 1
set j to 2
check if j(2) >= 1
set j to 1
check if j(1)>=1
set j to 0
check if j(0)>=1
</code></pre>
<p>for( j=n ; j>=0 ; j-- )</p>
<p>Ok, you start with two operations:</p>
<ul>
<li>(j=n)</li>
<li>check (j>=0). </li>
</ul>
<p>For all n<0 it stops there.</p>
<p>If n=0, you get an aditional:</p>
<ul>
<li>j--</li>
<li>check (j>=0).</li>
</ul>
<p>For n=1, you get another set of those.</p>
<p>So the number of operations is 2 for n<0 and 2n+4 for n>=0.</p>
<p>These things are not that hard. You just need to think like a computer and carefully note any change to the state (set of variables).</p>
|
How to represent a call being made in a loop in a sequence diagram? <p>I'm creating a sequence diagram, and one of the classes is being observed by another class. The observed class is calling update in the observer every 5 seconds in a loop. I need to show this in the sequence diagram. Is there a way to show it looping indefinitely out of sequence as it were?</p>
<p>Or does it not make sense in the context of a sequence diagram; should I not include it? Or should I include it in a different type of diagram?</p>
| <p>A box enclosing the message send arrow (and whatever else is inside the same repetitive construct).</p>
<p>See <a href="http://www.ibm.com/developerworks/rational/library/3101.html">this tutorial</a> for an example.</p>
<p><img src="http://i.stack.imgur.com/I3ZdK.jpg" alt="sequence diagram with loop">
<a href="http://www.ibm.com/developerworks/rational/library/content/RationalEdge/feb04/3101_figure10.html">link to larger image</a></p>
|
What's the best way to implement a counter field in MySQL <p>I want to start counting the numbers of times a webpage is viewed and hence need some kind of simple counter. What is the best scalable method of doing this?</p>
<p>Suppose I have a table Frobs where each row corresponds to a page - some obvious options are:</p>
<ol>
<li><p>Have an unsigned int NumViews field
in the Frobs table which gets
updated upon each view using <code>UPDATE
Frobs SET NumViews = NumViews + 1</code>. Simple but not so good at scaling as I understand it.</p></li>
<li><p>Have a separate table FrobViews
where a new row is inserted for each view. To display the
number of views, you then need to do a simple <code>SELECT COUNT(*) AS NumViews FROM FrobViews WHERE FrobId = '%d' GROUP BY FrobId</code>. This doesn't involve any updates so can avoid table locking in MyISAM tables - however, the read performance will suffer if you want to display the number of views on each page.</p></li>
</ol>
<p>How do you do it?</p>
<p>There's some good advice here:
<a href="http://www.mysqlperformanceblog.com/2007/07/01/implementing-efficient-counters-with-mysql/">http://www.mysqlperformanceblog.com/2007/07/01/implementing-efficient-counters-with-mysql/</a>
but I'd like to hear the views of the SO community.</p>
<p>I'm using InnoDb at the moment, but am interested in answers for both InnoDb and MyISAM.</p>
| <p>Inserting into a Database is not something you want to do on page views. You are likely to run into problems with updating your slave databases with all of the inserts since replication is single threaded on MySQL.</p>
<p>At my company we serve 25M page views a day and we have taken a tiered approach.</p>
<p>The view counter is stored in a separate table with 2 columns (profileId, viewCounter) both are unsigned integers.</p>
<p>For items that are infrequently viewed we update the table on page view.
For frequently viewed items we update MySQL about 1/10 of the time. For both types we update Memcache on every hit.<br>
<code>int Memcache::increment ( string $key [, int $value = 1 ] )</code></p>
<p><code>if (pageViews < 10000) { UPDATE page_view SET viewCounter=viewCounter+1 WHERE profileId = :? }</code></p>
<p><code>else if ((int)rand(10) == 1) { //UPDATE page_view SET viewCounter= ?:cache_value WHERE profileId = :? }</code></p>
<p>doing count(*) is very inefficient in InnoDB (MyISAM keeps count stats in the index), but MyISAM will lock the table on reads reducing concurrency. doing a count() for 50,000 or 100,000 rows is going to take a long time. Doing a select on a PK will be very fast.</p>
<p>If you require more scalability, you might want to look at <a href="http://redis.io/" rel="nofollow">redis</a></p>
|
C programming: How to program for Unicode? <p>What prerequisites are needed to do strict Unicode programming?</p>
<p>Does this imply that my code should not use <code>char</code> types anywhere and that functions need to be used that can deal with <code>wint_t</code> and <code>wchar_t</code>?</p>
<p>And what is the role played by multibyte character sequences in this scenario? </p>
| <p>The C standard (C99) provides for wide characters and multi-byte characters, but since there is no guarantee about what those wide characters can hold, their value is somewhat limited. For a given implementation, they provide useful support, but if your code must be able to move between implementations, there is insufficient guarantee that they will be useful.</p>
<p>Consequently, the approach suggested by Hans van Eck (which is to write a wrapper around the ICU - International Components for Unicode - library) is sound, IMO.</p>
<p>The UTF-8 encoding has many merits, one of which is that if you do not mess with the data (by truncating it, for example), then it can be copied by functions that are not fully aware of the intricacies of UTF-8 encoding. This is categorically not the case with <code>wchar_t</code>.</p>
<p>Unicode in full is a 21-bit format. That is, Unicode reserves code points from U+0000 to U+10FFFF.</p>
<p>One of the useful things about the UTF-8, UTF-16 and UTF-32 formats (where UTF stands for Unicode Transformation Format - see <a href="http://unicode.org/">Unicode</a>) is that you can convert between the three representations without loss of information. Each can represent anything the others can represent. Both UTF-8 and UTF-16 are multi-byte formats.</p>
<p>UTF-8 is well known to be a multi-byte format, with a careful structure that makes it possible to find the start of characters in a string reliably, starting at any point in the string. Single-byte characters have the high-bit set to zero. Multi-byte characters have the first character starting with one of the bit patterns 110, 1110 or 11110 (for 2-byte, 3-byte or 4-byte characters), with subsequent bytes always starting 10. The continuation characters are always in the range 0x80 .. 0xBF. There are rules that UTF-8 characters must be represented in the minimum possible format. One consequence of these rules is that the bytes 0xC0 and 0xC1 (also 0xF8..0xFF) cannot appear in valid UTF-8 data.</p>
<pre><code> U+0000 .. U+007F 1 byte 0xxx xxxx
U+0080 .. U+07FF 2 bytes 110x xxxx 10xx xxxx
U+0800 .. U+FFFF 3 bytes 1110 xxxx 10xx xxxx 10xx xxxx
U+10000 .. U+10FFFF 4 bytes 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
</code></pre>
<p>Originally, it was hoped that Unicode would be a 16-bit code set and everything would fit into a 16-bit code space. Unfortunately, the real world is more complex, and it had to be expanded to the current 21-bit encoding.</p>
<p>UTF-16 thus is a single unit (16-bit word) code set for the 'Basic Multilingual Plane', meaning the characters with Unicode code points U+0000 .. U+FFFF, but uses two units (32-bits) for characters outside this range. Thus, code that works with the UTF-16 encoding must be able to handle variable width encodings, just like UTF-8 must. The codes for the double-unit characters are called surrogates.</p>
<blockquote>
<p>Surrogates are code points from two special ranges of Unicode values, reserved for use as the leading, and trailing values of paired code units in UTF-16. Leading, also called high, surrogates are from U+D800 to U+DBFF, and trailing, or low, surrogates are from U+DC00 to U+DFFF. They are called surrogates, since they do not represent characters directly, but only as a pair.</p>
</blockquote>
<p>UTF-32, of course, can encode any Unicode code point in a single unit of storage. It is efficient for computation but not for storage.</p>
<p>You can find a lot more information at the <a href="http://icu-project.org/">ICU</a> and Unicode web sites.</p>
|
AutoIncrement fields on databases without autoincrement field <p>In MS Sql Server is easy create autoincrement fields. In my systems I stopped to use autoincrement fields for primary keys, and now I use Guid's. It was awesome, I've got a lot of advantages with that change. But in another non-primary key fields, I really was needing implement a "soft autoincrement". It's because my system is DB independent, so I create the autoinc value programatically in c#. </p>
<p>I would like about solutions for autoincrement fields on databases without autoincrement, what the solution that your use and why? There is some Sql Ansi statement about this? and generating directly from my c#, is a better solution?</p>
<p>PS: I know that <em>select max(id)+1 from table</em> it's not really concurrent friendly...</p>
| <p>The mechanism to generate unique id values <strong>must not</strong> be subject to transaction isolation. This is required for the database to generate a distinct value for each client, better than the trick of <code>SELECT MAX(id)+1 FROM table</code>, which results in a race condition if two clients try to allocate new <code>id</code> values concurrently.</p>
<p>You can't simulate this operation using standard SQL queries (unless you use table locks or <em>serializable</em> transactions). It has to be a mechanism built into the database engine.</p>
<p>ANSI SQL did not describe an operation to generate unique values for surrogate keys until SQL:2003. Before that, there was no standard for auto-incrementing columns, so nearly every brand of RDBMS provided some proprietary solution. Naturally they vary a lot, and there's no way to use them in a simple, database-independent manner.</p>
<ul>
<li>MySQL has the <code>AUTO_INCREMENT</code> column option, or <code>SERIAL</code> pseudo-datatype which is equivalent to <code>BIGINT UNSIGNED AUTO_INCREMENT</code>;</li>
<li>Microsoft SQL Server has the <code>IDENTITY</code> column option and <code>NEWSEQUENTIALID()</code> which is something between auto-increment and GUID;</li>
<li>Oracle has a <code>SEQUENCE</code> object;</li>
<li>PostgreSQL has a <code>SEQUENCE</code> object, or <code>SERIAL</code> pseudo-datatype which implicitly creates a sequence object according to a naming convention;</li>
<li>InterBase/Firebird has a <code>GENERATOR</code> object which is pretty much like a <code>SEQUENCE</code> in Oracle; Firebird 2.1 supports <code>SEQUENCE</code> too;</li>
<li>SQLite treats any integer declared as your primary key as implicitly auto-incrementing;</li>
<li>DB2 UDB has just about everything: <code>SEQUENCE</code> objects, or you can declare columns with the "<code>GEN_ID</code>" option.</li>
</ul>
<p>All these mechanisms operate outside transaction isolation, ensuring that concurrent clients get unique values. Also in all cases there is a way to query the most recently generated value <em>for your current session</em>. There has to be, so you can use it to insert rows in a child table.</p>
|
How to create backBarButtomItem with custom view for a UINavigationController <p>I have a <code>UINavigationController</code> into which I push several views. Inside <code>viewDidLoad</code> for one of these views I want to set the <code>self.navigationItem.backBarButtonItem</code> to a custom view (based on a custom image). I don't know why, but it doesn't seem to work. Instead, I get the standard "back" button.</p>
<pre><code>UIButton *backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 63, 30)];
[backButton setImage:[UIImage imageNamed:@"back_OFF.png"] forState:UIControlStateNormal];
[backButton setImage:[UIImage imageNamed:@"back_ON.png"] forState:UIControlStateSelected];
UIBarButtonItem *backButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
self.navigationItem.backBarButtonItem = backButtonItem;
[backButtonItem release];
[backButton release];
</code></pre>
<p>I tested with a standard title and it worked. What is wrong with the above code ?</p>
<pre><code>self.navigationItem.backBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Prout" style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
</code></pre>
<p>Thanks for any help on this.</p>
| <p>As of iOS5 we have an <em>excellent new way of customizing the appearance</em> of almost any control using the <a href="http://developer.apple.com/library/ios/#documentation/uikit/reference/UIAppearance_Protocol/Reference/Reference.html">UIAppearance protocol</a>, i.e. <code>[UIBarButtonItem appearance]</code>. The appearance proxy allows you to create application wide changes to the look of controls. Below is an example of a custom back button created with the appearance proxy.</p>
<p><img src="http://i.stack.imgur.com/O1s5j.png" alt="enter image description here"></p>
<p>Use the example code below to create a back button with custom images for normal and highlighted states. Call the following method from you appDelegate's <code>application:didFinishLaunchingWithOptions:</code> </p>
<pre><code>- (void) customizeAppearance {
UIImage *i1 = [[UIImage imageNamed:@"custom_backButton_30px"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 6)];
UIImage *i2 = [[UIImage imageNamed:@"custom_backButton_24px"]
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 15, 0, 6)];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:i1
forState:UIControlStateNormal
barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:i2
forState:UIControlStateNormal
barMetrics:UIBarMetricsLandscapePhone];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:i1
forState:UIControlStateHighlighted
barMetrics:UIBarMetricsDefault];
[[UIBarButtonItem appearance] setBackButtonBackgroundImage:i2
forState:UIControlStateHighlighted
barMetrics:UIBarMetricsLandscapePhone];
}
</code></pre>
<p>This is just a quick example. Normally you would want to have separate images for normal and highlighted (pressed) state.</p>
<p>If you are interested in customizing the appearance of other controls, some good examples can be found here: <a href="http://ios.biomsoft.com/2011/10/13/user-interface-customization-in-ios-5/">http://ios.biomsoft.com/2011/10/13/user-interface-customization-in-ios-5/</a></p>
|
Entity Framework: Loading Many to One entity <p>Say I have a role entity and a site entity. Now there are many roles to one site, so on the Role class there is a Site property that represents that relationship. If I wanted the roles for a site I would do this:</p>
<pre><code>Site.Roles.Load()
</code></pre>
<p>Problems is, since the Site property on the Role class isn't a collection but just a single entity, there is no Load method:</p>
<pre><code>currentRole.Site //????
</code></pre>
<p>So that when a role is loaded, the Site is null and there is no way to get the site other than say a query on the role collection to get the SiteID, getting the Site from the site collection, and finally setting that to currentRole's site property. </p>
<p>There has to be a better way? Do I have to force some kind of join in the query? Seems like this would be generated by code just like the Load method behaves.</p>
| <p>Actually, accessing it will not automatically load it. You can include the related entity in a single query using the Include method, but you can also use a Load method with references just like you can with collections--it's just not on the CLR reference property but on an EntityReference property parallel to the CLR reference on the entity. It's name is the same as the CLR reference but with the word "reference" tacked on. So you can say:</p>
<pre><code>currentRole.SiteReference.Load();
</code></pre>
<p>For what it's worth, in the VS 2010 / .net 4.0 release of the EF, it will also be possible to set a property on the ObjectContext which will turn on implicit lazy loading so that accessing the clr reference will automatically just load it if it hasn't been loaded already.</p>
<p>Danny</p>
|
How do I find the position of a cursor in a text box? C# <p>I have a standard WinForms TextBox and I want to insert text at the cursor's position in the text. How can I get the cursor's position?</p>
<p>Thanks</p>
| <p>Regardless of whether any text is selected, the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.selectionstart.aspx">SelectionStart</a> property represents the index into the text where you caret sits. So you can use <a href="http://msdn.microsoft.com/en-us/library/system.string.insert.aspx">String.Insert</a> to inject some text, like this:</p>
<pre><code>myTextBox.Text = myTextBox.Text.Insert(myTextBox.SelectionStart, "Hello world");
</code></pre>
|
Just started C++: Undefined Symbol error on Compile <p>Here's the situation:</p>
<p>I just started my first C++ class. I know nothing about C++ and despite this being the an intro to C++ class, the teacher has taught pretty much NO syntax for the language, just logic that we already know.</p>
<p>Now he gave us a program description and said, "write it, lol." I understand the logic fine, but as I said before, I know nothing about C++. Thus I wrote it first in java (which I do know), and then once I got it working in java, I tried to code it over to C++.</p>
<p>However now I am getting the following error when I compile</p>
<pre><code>uxb3% g++ -o Race race.cc
Undefined first referenced
symbol in file
main /usr/local/gcc-4.1.1/bin/../lib/gcc/sparc-sun-solaris2.10/4.1.1/crt1.o
ld: fatal: Symbol referencing errors. No output written to Race
collect2: ld returned 1 exit status
</code></pre>
<p>Can someone please help me with this?</p>
<p>Here is my code in a .txt file:
<a href="http://rapidshare.com/files/195742284/race.txt.html" rel="nofollow">http://rapidshare.com/files/195742284/race.txt.html</a></p>
<p>and here it is in a copy paste:</p>
<pre><code>#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
class Race
{
void main()
{
executeRace();
}
int randomMove()
{
srand(time(NULL));
int randomInt = rand() % 100 + 1;
return randomInt;
}
void executeRace()
{
int rabbitPosition = 1;
int turtlePosition = 1;
cout << "BANG!!!" << endl << "AND THEY'RE OFF!!!";
while (rabbitPosition <=70 && turtlePosition <=70)
{
printPositions(rabbitPosition, turtlePosition);
turtlePosition = turtleMoveSquares(turtlePosition);
rabbitPosition = rabbitMoveSquares(rabbitPosition);
}
printWinner(rabbitPosition, turtlePosition);
tie(rabbitPosition, turtlePosition);
}
int turtleMoveSquares(int tPosition)
{
int turtleMove = randomMove();
if(turtleMove >=1 && turtleMove <= 40)
tPosition = tPosition + 4;
if(turtleMove >= 41 && turtleMove <= 50 )
tPosition = tPosition - 2;
if(turtleMove >=51 && turtleMove <=100)
tPosition = tPosition + 2;
if(tPosition < 1)
tPosition = 1;
return tPosition;
}
int rabbitMoveSquares(int rabbitPosition)
{
int rabbitMove = randomMove();
if(rabbitMove >=1 && rabbitMove <= 25)
rabbitPosition = rabbitPosition;
if(rabbitMove >=26 && rabbitMove <= 55)
rabbitPosition = rabbitPosition + 10;
if(rabbitMove >=56 && rabbitMove <=60)
rabbitPosition = rabbitPosition - 15;
if(rabbitMove >=61 && rabbitMove <= 90)
rabbitPosition = rabbitPosition + 5;
if(rabbitMove >=90 && rabbitMove <=100)
rabbitPosition = rabbitPosition - 3;
if(rabbitPosition < 1)
rabbitPosition = 1;
return rabbitPosition;
}
void printPositions(int rabbitPositions, int turtlePositions)
{
int turtleCount;
int rabbitCount;
int endCount;
if(rabbitPositions == turtlePositions && rabbitPositions != 1)
{
turtleCount = 1;
while(turtleCount < turtlePositions)
{
cout << "-";
turtleCount = turtleCount+1;
}
cout << "OUCH!";
}
else
{
turtleCount = 1;
rabbitCount = 1;
endCount=1;
if(turtlePositions < rabbitPositions)
{
while(turtleCount < turtlePositions)
{
cout << "-";
turtleCount = turtleCount+1;
}
cout << "T";
while(rabbitCount < (rabbitPositions - turtlePositions))
{
cout << "-";
rabbitCount = rabbitCount+1;
}
cout << "H";
}
if(rabbitPositions < turtlePositions)
{
while(rabbitCount < rabbitPositions)
{
cout << "-";
rabbitCount = rabbitCount+1;
}
cout << "H";
while(turtleCount < (turtlePositions - rabbitPositions))
{
cout << "-";
turtleCount = turtleCount+1;
}
cout << "T";
cout << "\n";
}
}
}
void printWinner(int rabbitPosition, int turtlePosition)
{
if(turtlePosition >= 70 && rabbitPosition < 70)
{
cout << "TORTOISE WINS!!! YAY!!!\n";
}
else if(rabbitPosition >=70 && turtlePosition < 70)
{
cout << "Hare wins. Yuch.\n";
}
else if(rabbitPosition >=70 && turtlePosition >=70)
{
cout << "It's a tie\n";
}
}
void tie(int turtlePosition, int rabbitPosition)
{
if(rabbitPosition >=70 && turtlePosition >=70)
executeRace();
}
};
</code></pre>
| <p>It's complaining about <code>main</code> being undefined, and it's right. C and C++ require a <em>standalone</em> function named <code>main</code> which returns <code>int</code>. It is not sufficient to have a <em>class</em> with a method named <code>main</code>; the compiler only cares about the standalone one.</p>
<p>Another thing to remember is that the default visibility for members in a <code>class</code> type is <em>private</em>. Either change your class to use <code>struct</code> â that's pretty much the only difference between the two â or specify public visibility:</p>
<pre><code>class Race {
public:
void main() { ... }
};
</code></pre>
<p>Then you can call the <code>main</code> function from your class:</p>
<pre><code>int main() {
Race race;
race.main();
return EXIT_SUCCESS;
}
</code></pre>
|
VS2008 files and "start debugging" <p>This may sound like a newbie question - and it is. I'm relatively new to vs, we started using it a few months ago, and I still haven't "mentally" made the change from the command line. So, if you could help me with 2 things:</p>
<ol>
<li>I create a new project (not a solution). He puts the files in some directory. After putting my code inside it, I click on the little green triangle (Debug, it says), and he compiles it, builds it and runs it. It works ok. Now, sometimes, I have to change only a tiny bit of code and I don't feel like getting the whole VS up just for that. How can I do that Debug thing from the command line, with the assumption I didn't change anything else.</li>
<li>Where do I tell him not to create a "Debug" subdirectory, not to create a HTML Build log, an object file ... and so on, generally, where can I find the settings which will help me to get as little files ... apart from my original source, and the .exe resultant one ?</li>
</ol>
| <blockquote>
<p>I have to change only a tiny bit of code and I don't feel like getting the whole VS up just for that. How can I do that Debug thing from the command line, with the assumption I didn't change anything else.</p>
</blockquote>
<p>I think what you want here is not debugging but a rebuild of your project.</p>
<blockquote>
<p>Where do I tell him not to create a "Debug" subdirectory, not to create a HTML Build log, an object file ... and so on, generally, where can I find the settings which will help me to get as little files ... apart from my original source, and the .exe resultant one ?</p>
</blockquote>
<p>The answer to both these questions is to use the command line! You can make VS emit a make file from the loaded project. Use NMAKE to build this make file after you have made your desired modifications. The ".obj" files are created as an intermediate step between compilation and linking phase this is how the C++ <a href="http://www.cs.cf.ac.uk/Dave/C/node3.html" rel="nofollow">compilation model</a> works. Why do insist on not generating them?</p>
|
Best OpenId API for ASP.NET MVC application <p>I am developing an ASP.NET MVC application and I want to use OpenId.</p>
<p>What is the best option? </p>
<ul>
<li>DotNetOpenId</li>
<li>RPX</li>
<li>Other???</li>
</ul>
<p>Does anyone know what StackOverflow uses? Is the Login UI custom-developed, or provided by an API/service?</p>
| <p>We use the excellent DotNetOpenId library here on Stack Overflow:</p>
<blockquote>
<p><a href="http://code.google.com/p/dotnetopenid/">http://code.google.com/p/dotnetopenid/</a></p>
</blockquote>
<p>now moved to:</p>
<blockquote>
<p><a href="http://www.dotnetopenauth.net/">http://www.dotnetopenauth.net/</a></p>
</blockquote>
<p>Our <em>original</em> login UI was provided by <a href="http://www.idselector.com/">ID Selector</a>, but we've since rolled our own minimalist version.</p>
|
F# naming convention <p>Is there an "official" naming / casing convention for F#?</p>
<p>I'm always in doubt of using C# style or not: </p>
<pre><code>Class.MyFunctionName or Module.my_function_name
</code></pre>
<p>In F# you're meant to mix BCL classes and F# library ones: they have different casing and the code looks very ugly.</p>
| <p>Yes, there is confusion, because F# has morphed from OCaml to .Net over the years. Basically, the naming conventions are a "breaking change" - old code is inconsistent with new code.</p>
<p>However, the May 2009 CTP has settled the issue.</p>
<p>The <a href="http://blogs.msdn.com/dsyme/archive/2009/05/20/detailed-release-notes-for-the-f-may-2009-ctp-update-and-visual-studio-2010-beta1-releases.aspx">Release Notes</a> say...</p>
<p><strong>Standard Library Naming Conventions</strong></p>
<blockquote>
<p>The naming conventions adopted for the F# library are as follows:</p>
<ul>
<li><p>All .NET and F# OO code uses PascalCase according to existing .NET guidelines</p></li>
<li><p>The F# functional programming operators such as List.map are for use in F# internal implementation code. This kind of code uses camelCase for operator names</p></li>
<li><p>Underscores should not be used. </p></li>
</ul>
</blockquote>
<p><strong>So, your question...</strong></p>
<pre><code>Class.MyFunctionName or Module.my_function_name
</code></pre>
<p>The answer is </p>
<blockquote>
<p>Class.MyFunctionName and Module.MyFunctionName </p>
</blockquote>
<p>(applying rule 1 above). </p>
<p>There is still some confusion by comparision with the F# programming operators (eg. List.averageBy), but production F# code should use CamelCase, and thus look like everyone else's .Net code. If in doubt, check the <a href="http://code.msdn.microsoft.com/fsharpsamples/Release/ProjectReleases.aspx?ReleaseId=2705">sample code</a> for the CTP.</p>
<p>(I personally like_the_caml_style, but I'll have to GetOverThat)</p>
|
XML Documentation: <see> tag with multiple generic type parameters <p>I'm trying to use XML documentation on the members of a class, and in a certain case I would like to reference a generic type using a tag. The problem here is that a warning is generated when multiple generic type parameters are specified. It was easy enough to find how to reference a generic type with a single parameter, as such:</p>
<pre><code><see cref="Func{int}" />
</code></pre>
<p>However, trying something like this generates the warning:</p>
<pre><code><see cref="Func{int, bool}" />
</code></pre>
<p>It seems that I am either using the wrong syntax for references with more than one type parameter, or such references are not currently supported in XML docs for C#. Strangely enough, I can't seem to find any information about this on MSDN or in the Sandcastle docs (which I'm using to compile the documentation, and also complains about the syntax). Any clarification here would be appreciated.</p>
| <p>Use the .NET names, not the C# aliases:</p>
<pre><code><see cref="Func{Int32, Boolean}" />
</code></pre>
|
Book recommendations: PHP/MySQL and Dreamweaver? <p>I need a book that discusses PHP, mySql and Dreamweaver as I have a project and i don't know either of these technologies, so i need something to give me a headstart.</p>
| <p>I don't think any book on PHP and MySQL is restricted to any single IDE like Dreamweaver. For a quick introduction to both together I can recommend <a href="http://www.dmcinsights.com/phpmysql/" rel="nofollow">PHP and MySQL for Dynamic Web Sites: Visual QuickPro Guide</a>. You can search the book from that site, or take a look at the table of contents to see if it has what you need.</p>
<p><img src="http://www.dmcinsights.com/images/phpmysql.gif" alt="PHP and MySQL" /></p>
|
How to Implement Closures Using SpiderMonkey API? <p>I've been working with the SpiderMonkey C API and would like to implement a closure in C using their API. The one I would like to implement is fairly complex, but I can't even figure out how to do a simple one such as:</p>
<pre><code>function x() {
var i = 0;
return function() { i++; print(i); };
}
var y = x();
y(); //1
y(); //2
y(); //3
</code></pre>
<p>I was wondering if anyone knows how I might do this. I found the JS_NewFunction method, but I don't actually know if that is a step in the right direction. Any help will be appreciated, thanks!</p>
| <p>I don't know if there's a pure C way of doing closures or not. I would reccomend though, if you can, to just implement the functionality you need in javascript, and simply evaluate the javascript text in JSAPI. From there, use JSAPI to grab whatever handles/variables you need to implement your host functionality. It's really onerous to do javascripty things using JSAPI, avoid it if you can.</p>
|
Java POI - anyone been able to extract numbers from formula cells? <p>I've been using Java POI for some time now, but have encountered a new problem, and I'm wondering if anyone has found a solution.</p>
<p>When you read a spreadsheet, you need to know the type of cell in order to use the proper read method.</p>
<p>So you get the cell type, then call the appropriate read method to get the cell's contents.</p>
<p>This works for all cells except for the FORMULA cell, where the value is a number. If it's text, you can read it just fine. But if the resulting value is a number, then all you get from the cell is a blank string.</p>
<p>I've been through the javadocs for POI, and am using the correct data type (HSSFRichTextString), but still no joy.</p>
<p>Anyone have a solution?</p>
<p>P.S. this behavior of POI does bug me as there should be a default cell.toString() method that would return the string representation of ANY cell type, say defaulting to the cell's value property. (sort of like the paste-special where you can choose "value").</p>
<p>PPS: As asked - I'm using Java 6 (1.6.0_06) and poi-3.0.2-FINAL-20080204.jar</p>
| <pre><code> FileInputStream fis = new FileInputStream("c:/temp/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("c:/temp/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
</code></pre>
<p>Copied shamelessly from <a href="http://poi.apache.org/spreadsheet/eval.html" rel="nofollow">here</a> </p>
|
Selecting a date on a mobile web site <p>I'm working on a web site that includes creating appointments on the mobile site. I have to make it work on IE Mobile.</p>
<p>The biggest challenge is to come up with a way to do date selection on a mobile site that:</p>
<ul>
<li>Is compact enough to not take forever to load on the limited-bandwidth cell network.</li>
<li>Will work on Windows Mobile 6 </li>
<li>Prevents the user from inputing any values (free-form text box is out of the question)</li>
</ul>
<p>The options I've come up with so far are:</p>
<ul>
<li>Drop-down lists for year, month, day (and client or server validation to ensure the validity of the selections, i.e. don't allow Feb. 31st)</li>
<li>Use a jQuery plugin & hope jQuery can run on every device I'm targeting (IE Mobile, Blackberry, iPhone)</li>
<li>Write some sort of elaborate IFrame AJAX lightbox that contains a basic calendar selector (that is, not reliant on jQuery), similar to what Google does on its mobile calendar site.</li>
</ul>
<p>Since I can't seem to come up with any really solid ideas I wanted to see what the SO community could come up with as a decent solution for mobile date entry.</p>
| <p>Have you thought about masking input? I'm not sure how well it will meet your needs, but it's worth a shot. Here's a jQuery implementation:</p>
<p><a href="http://digitalbush.com/projects/masked-input-plugin/" rel="nofollow">http://digitalbush.com/projects/masked-input-plugin/</a></p>
<p>Edit: After thinking about this some more, I would probably go with either the lightbox calendar idea you had or dropdowns. The benefit of dropdowns would be that you could enhance the input method for users that have better Javascript support. For example, you could hide the dropdowns and provide a dummy pop-out calendar that, when used, popluates values into the dropdowns.</p>
<p>Keep in mind you should ALWAYS do validation at the server. If you can do it at the client as well (or at least keep input limited) then that is a bonus feature to increase usability.</p>
|
help in reading nested xml using xmlreader in php <pre><code><root>
<thing>
<specs>
<spec1 />
<spec3 />
<spec2 />
</specs>
<details />
<more_info>
<info1 />
<info2 />
</more_info>
</thing>
</root>
</code></pre>
<p><br>
okeee so i got this sample xml and the problem is i cant seem to get the values of the innerxml, <br>when i use <code>$reader->readInnerXML()</code> it returns the whole string though im sure that my xml is valid<br>
what i wanted was to get the values of spec1, spec2, spec3 separately</p>
<p>the code is pretty long so i posted it <a href="http://pastebin.com/f48b9bd38" rel="nofollow">here</a>
<br> i've been stuck with this for 3days now T_T poor me, i'd gladly accept any corrections</p>
| <p>It depends what you mean by "value". If you have something like </p>
<pre><code><spec3 />Value</spec3>
</code></pre>
<p>Then readInnerXML should be giving you your value. </p>
<p>If your value is in an attribute, </p>
<pre><code><spec1 foo="my attribute" />
</code></pre>
<p>You'll need to use the getAttribute method of the XMLReader object, or explicitly tell the reader to start parsing attributes. See the code example below for a few ways to accomplish this.</p>
<p>Finally, if the node contains more nested XML, </p>
<pre><code><spec2><foo><baz thing="la de da">Value</baz></foo></spec2>
</code></pre>
<p>There's no direct way at that moment in time for the reader to understand values/elements inside of it. You'd need to do one of the following</p>
<ol>
<li>Change you reader parsing code to hook into elements at those depths</li>
<li>Take the XML chunk from readInnerXML and start parsing it with a second XMLReader instance, </li>
<li>Take the XML chunk from readInnerXML and start parsing it with a another XML parsing library.</li>
</ol>
<p>Here's some example code for parsing attributes</p>
<pre><code>$reader = new XMLReader();
$reader->xml(trim('
<root>
<thing>
<specs>
<spec1 foo="my attribute">Value</spec1>
<spec3>
My Text
</spec3>
<spec2 foo="foo again" bar="another attribute" baz="yet another attribute" />
</specs>
<details />
<more_info>
<info1 />
<info2 />
</more_info>
</thing>
</root>
'));
$last_node_at_depth = array();
$already_processed = array();
while($reader->read()){
$last_node_at_depth[$reader->depth] = $reader->localName;
if(
$reader->depth > 0 &&
$reader->localName != '#text' &&
$last_node_at_depth[($reader->depth-1)] == 'specs' &&
!in_array ($reader->localName,$already_processed)
){
echo "\n".'Processing ' . $reader->localName . "\n";
$already_processed[] = $reader->localName;
echo '--------------------------------------------------'."\n";
echo 'The Value for the inner node ';
echo ' is [';
echo trim($reader->readInnerXML());
echo ']'."\n";
if($reader->attributeCount > 0){
echo 'This node has attributes, lets process them' . "\n";
//grab attribute by name
echo ' Value of attribute foo: ' . $reader->getAttribute('foo') . "\n";
//or use the reader to itterate through all the attributes
$length = $reader->attributeCount;
for($i=0;$i<$length;$i++){
//now the reader is pointing at attributes instead of nodes
$reader->moveToAttributeNo($i);
echo ' Value of attribute ' . $reader->localName;
echo ': ';
echo $reader->value;
echo "\n";
}
}
//echo $reader->localName . "\n";
}
}
</code></pre>
|
How to call Inline Table Function with output parameter from scalar function? <p>I would like to know if it's possible to call a inline function with an output parameter from a scalar function?</p>
<p>For example:
My inline function is called test_1(input parameter format bigint), the following example works great:<br><br>
<b>SELECT * FROM MM.test_1(4679)</b></p>
<p>But now I would like to use it with an output parameter from a scalar function called dbo.test_2(output parameter format bigint) to make it more dynamically, but it don't works?<br><br>
<b>SELECT (SELECT * FROM MM.test_1(dbo.test_2(kp.id)))
FROM kp kp
WHERE id = 4679</b></p>
<p>I receive the following error message:<br><b>
"Error in list of function arguments: '.' not recognized.
Incomplete parameters list.
Missing FROM clause.
Unable to parse query text."</b></p>
<p>Any suggestions?</p>
<p>Any help will be appreciated! </p>
<p>Thx forward,
Best Regards Andreas</p>
| <p>I can interpret what you're trying to do in two different ways.</p>
<h3>Scenario 1:</h3>
<p>You want to get a <strong>single value</strong> out of your <strong>kp</strong> table first, then run it through the static function, then feed the result to the inline function and get a table.</p>
<p>In this case, you can do something like:</p>
<pre><code>declare @foo int;
set @foo = (select kp.id from kp where blahblahblah);
select * from MM.test_1(dbo.test_2(@foo))
</code></pre>
<h3>Scenario 2:</h3>
<p>More likely, for <strong>each record</strong> in your <strong>kp</strong> table, you want to do all those nasty things to its id and <strong>union</strong> the resulting tables.</p>
<p>In this case, the best I can suggest would be some dynamic SQL that goes through your id values, using a <strong>cursor</strong>, computes the partial results, then UNIONs it all together. Google for using cursors to loop through tables and you'll find enough to get you going (like <a href="http://justgeeks.blogspot.com/2008/08/using-t-sql-cursor-in-sql-server.html" rel="nofollow">this post</a>). You must think of your table-valued function like a (surprise...) table. You cannot use it as a column in a SELECT statement in the same way you could use a static function and also you cannot feed the fields of a query back to themselves.</p>
<p>If you are calling this SQL from an application you should seriously think about doing this in code instead.</p>
<p>Good luck!</p>
|
Obtaining an IntialContext from Weblogic without using clear text password <p>I can obtain the Weblogic InitialContext from a JNDI Client using the following
properties as the Environment parameters for InitialContext</p>
<pre><code>Hashtable jndiProps = new Hashtable();
jndiProps.put("java.naming.factory.initial", "t3://localhost:7001");
jndiProps.put("java.naming.provider.url", "weblogic.jndi.WLInitialContextFactory");
jndiProps.put("java.naming.security.principal", "weblogic");
jndiProps.put("java.naming.security.credentials", "weblogic");
InitialContext ctx = new InitialContext(jndiProps);
</code></pre>
<p>The question is, is there a way to obtain the InitialContext without specifying the security.credentials as cleartext but maybe as a hashed value?</p>
| <p>You could use symmetric encryption, encrypt the password value and store this in the properties file. Then before creating the initial context read the property value, decrypt it and update the property before passing the jndiProps object to the InitialContext constructor.</p>
<p>The encryption key would still be on the client but it's going to stop someone casually reading the property file to find out the password.</p>
<p>Using SSL is also a good idea for protecting the password as it is transmitted between the client and the server.</p>
|
input and thread problem, python <p>I am doing something like this in python</p>
<pre><code>class MyThread ( threading.Thread ):
def run (s):
try:
s.wantQuit = 0
while(not s.wantQuit):
button = raw_input()
if button == "q":
s.wantQuit=1
except KeyboardInterrupt:
s.wantQuit = 1
myThread = MyThread ()
myThread.start()
a=5
while not myThread.wantQuit:
print "hey"
if (a == 0):
break;
a = a-1;
time.sleep(1)
#"""
sys.exit()
</code></pre>
<p>What happens is my app locks up for 5 seconds printing "hey" (5 times) THEN i get the raw_input dialog. How can i have the dialog show up so i can quit anytime instead of when my loop runs out?</p>
| <p>You mean the while loop runs before the thread? Well, you can't predict this unless you synchronize it. No one guarantees you that the thread will run before or after that while loop. But if it's being blocked for 5 seconds that's akward - the thread should have been pre-empted by then.</p>
<p>Also, since you're first use of wantToQuit is in the run() method, no one assures you that the thread has been started when you're checking for it's wantToQuit attribute in <code>while not myThread.wantToQuit</code> .</p>
|
Read Cookies Using xcode in iphone app <p>My application needs to be able to read cookies stored by a page loaded in the UIWebView. I need to be able to read the cookies using xcode so that I can store some values in application settings.
Does anyone know if its possible to read cookies using xcode?
Your help is much appreciated.
Stuck on this for ages.
Tony </p>
| <p>You can use <a href="http://developer.apple.com/iphone/library/documentation/Cocoa/Reference/Foundation/Classes/NSHTTPCookieStorage_Class/" rel="nofollow">NSHTTPCookieStorage</a> to read/modify cookies. <code>UIWebView</code> is using this storage.</p>
|
Open source Application demonstrating layer Architcture <p>Many of u will agree that learning from open source project is another way of improving programming skills .Can me make list of open source applications that best demonstrates the use of layer architecture. </p>
| <p>I guess <a href="http://www.jboss.com/products/jbossas/architecture" rel="nofollow">JBoss</a> is a good example of multiple layers Architecture...</p>
<p><img src="http://www.jboss.com/images/appInstrumentation.gif" alt="alt text" /></p>
|
Type exists in two libraries <p>I'm trying to incorporate <a href="http://www.codeplex.com/linqtolucene" rel="nofollow">Linq to Lucene</a> in my Asp.net-mvc project.<br />
As with most web projects, I use the <a href="http://www.squaredroot.com/post/2008/07/08/PagedList-Strikes-Back.aspx" rel="nofollow">PagedList</a> type I put in my personal helper library and use it all over the place.<br />
But so did Linq to Lucene...
Since both my library and the L2L library want to add the PagedList type to System.Collections.Generic namespace, I get a conflict message.</p>
<p>Is there a way to resolve this conflict without either having to rewrite my projects or the L2L project?</p>
| <p>It's generally a bad idea to add types to .NET BCL namespaces since it gives you no benefits whatsoever and causes major troubles in the long run. So the advice might be to move your helper class out of <code>System.Collections.Generic</code> namespace.</p>
|
How to deploy a Python application with libraries as source with no further dependencies? <p><strong>Background</strong>: I have a small Python application that makes life for developers releasing software in our company a bit easier. I build an executable for Windows using py2exe. The application as well as the binary are checked into Subversion. Distribution happens by people just checking out the directory from SVN. The program has about 6 different Python library dependencies (e.g. ElementTree, Mako)</p>
<p><strong>The situation</strong>: Developers want to hack on the source of this tool and then run it without having to build the binary. Currently this means that they need a python 2.6 interpreter (which is fine) and also have the 6 libraries installed locally using easy_install.</p>
<p><strong>The Problem</strong></p>
<ul>
<li>This is not a public, classical open source environment: I'm inside a corporate network, the tool will never leave the "walled garden" and we have seriously inconvenient barriers to getting to the outside internet (NTLM authenticating proxies and/or machines without direct internet access).</li>
<li>I want the hurdles to starting to hack on this tool to be minimal: nobody should have to hunt for the right dependency in the right version, they should have to execute as little setup as possible. Optimally the prerequisites would be having a Python installation and just checking out the program from Subversion.</li>
</ul>
<p><strong>Anecdote</strong>: The more self-contained the process is the easier it is to repeat it. I had my machine swapped out for a new one and went through the unpleasant process of having to reverse engineer the dependencies, reinstall distutils, hunting down the libraries online and getting them to install (see corporate internet restrictions above). </p>
| <p>Just use <a href="http://pypi.python.org/pypi/virtualenv">virtualenv</a> - it is a tool to create isolated Python environments. You can create a set-up script and distribute the whole bunch if you want.</p>
|
What's the best practice for developing a PHP data import framework? <p>During our work as web developer for a meteorological company, we are faced with the same task over and over again: Get some files from somewhere (FTP/Web/directory/mail) and import the contained data to a database.</p>
<p>Of course the file format is never the same, the databases are always designed differently, countless special cases have to be handled, etc, etc.</p>
<p>So now I'm planning an importing framework for exactly this kind of work. Since we're all experienced PHP developers and the current scripts are either PHP or Perl, we'll stick with PHP as scripting language.</p>
<ul>
<li>A data getter will fetch the file from the source, open it and store the content into a string variable. (Don't worry, PHP will get enough memory from us.)</li>
<li>The data handler will do the complicated work to convert the string into some kind of array.</li>
<li>The array will be saved to the database or written to a new file or whatever we're supposed to do with it.</li>
</ul>
<p>Along with this functionality there will be some common error handling, log writing and email reporting.</p>
<p>The idea is to use a collection of classes (Some getter-classes, a lot of specialised handlers, some writer classes).</p>
<p><strong>My question:</strong> How do I practically organize these classes in a working script? Do I invent some kind of meta language which will be interpreted and the the classes are called accordingly? Or just provide some simple interfaces these classes have to implement and the my users (like I said: Experienced PHP developers) will write small PHP scripts loading these classes?</p>
<p>The second version almost certainly offers the biggest flexiblity and extensibility. </p>
<p>Do you have any other ideas concerning such an undertaking?</p>
| <p>I suggest borrowing concepts from <a href="http://en.wikipedia.org/wiki/Data_Transformation_Services" rel="nofollow">Data Transformation Services</a> (DTS). You could have data sources and data sinks, import tasks, transformation tasks and so on.</p>
|
How can I create a PFX file from a Java Keystore? <p>I have a Java keystore (.jks file) holding a single certificate. How can I create a .pfx file from this keystore?</p>
| <p>From Java 6 onwards, <code>keytool</code> has an <code>-importkeystore</code> option, which should be able to convert a JKS store into a PKCS#12 store (.p12/.pfx):</p>
<pre><code>keytool -importkeystore -srckeystore thekeystore.jks \
-srcstoretype JKS \
-destkeystore thekeystore.pfx \
-deststoretype PKCS12
</code></pre>
|
What is a good desktop programming language to learn for a web developer? <p>I'm want to learn a desktop programming language, preferably C, C++ or C#. I'm a PHP/HTML/CSS programmer and I would like to get into desktop applications. I need something pretty powerful and I would like to be able to create applications with Windows GUI's. </p>
<p>What would the Stack Overflow community recommend? Is there any knowledge I should have before diving into these languages?</p>
| <p>edit:</p>
<p>A <strong>web programmer</strong> wants to create <strong>Windows applications</strong> and you recommend C? <h2>What's wrong with you people?!</h2></p>
<p>/edit</p>
<h3>Obviously C#.</h3>
<p>C# will be easier to get into and will let you build Windows applications using WinForms or WPF and all the new Microsoft toys in .NET. If you know your way around PHP, you should already be familiar with the syntax, object oriented concepts, exception handling, etc. </p>
<p>I suggest you don't complicate your life with C and definitely not with C++ if all you want is to create Windows GUIs. They do provide a good educational experience and they are useful for more advanced things (cross platform development using other toolkits for instance) but at the price of a steeper learning curve and reduced productivity.</p>
<p>Also, if you are a <strong>web developer</strong>, C# is the <strong>only</strong> language among the 3 options that you can (realistically, heh) use for the web. ASP.NET is not a bad framework and might be worth investigating too.</p>
|
Is .NET already the right way to go for small app development? <p>I am developing a small windows app, but have some trouble deciding whether to use .NET or not. As a coder I would like to make use of the .NET libraries. On the other hand, requiring my users to download the gargantuan .NET runtime seems like a horrible decision.</p>
<p>A 100 meg prerequisite might be alright for software in the scale of Visual Studio, but I feel like it would be a deal breaker for quick lightweight tools (think, for example, Notepad++). In the future, the .NET runtimes will likely become widespread enough to eradicate the problem, but in the short run, I feel uneasy.</p>
<p>In your opinion/experience, is 2009 too early for a small app to go .NET? Should I wait for the bigger players to pave the way?</p>
<p><em>Edit: Which versions, if any, come by default with XP SP2 and Vista?</em></p>
| <p>.NET is shipped with any recent version of Windows, so I doubt that you will be severely limited by using .NET. </p>
<p>Do you need to support Windows 2000? If you're happy with 2003 and Vista, you should have no problem. </p>
<p>Keep in mind that not everyone will be on .NET 3.5 (SP1) tough, but if you're not using any of that it is no problem. </p>
<p>EDIT: It seems like I was mistaken regarding XP SP2. .NET 2.0 is not included in service pack 2 for XP. According to <a href="http://en.wikipedia.org/wiki/.NET_Framework" rel="nofollow">wikipedia</a> W2003R2 was the first release to include .NET 2.0.</p>
|
Calculate a Ratio in C# <p>I thought this would be simple, but searching Google didn't seem to help.</p>
<p>I'm basically trying to write a function which will return a ratio as a string (eg 4:3) when supplies with two integers (eg 800 and 600).</p>
<pre><code>string GetRatio(Int A, Int B) {
// Code I'm looking for
return Ratio;
}
</code></pre>
| <p>I don't have a ready made code but it should be fairly simple. Namely, determine the <a href="http://en.wikipedia.org/wiki/Greatest_common_divisor">GCD</a> and work with it:</p>
<pre><code>var gcd = GCD(A, B);
return string.Format("{0}:{1}", A / gcd, B / gcd)
</code></pre>
<p>And a very basic function for calculating the GCD, using the <a href="http://en.wikipedia.org/wiki/Euclidean_algorithm">Euclidean algorithm</a>:</p>
<pre><code>static int GCD(int a, int b) {
return b == 0 ? a : GCD(b, a % b);
}
</code></pre>
|
Simply Div Opacity Fade on Focus using mootools <p>I've got a couple of divs in a page which hold simple HTML & images. The divs each have unique ids.</p>
<p>I'd like it so that when the page loads the contents of the div are say, 60% but on mouseover the fade in at 100%. On mouseout they would go back to 60%.</p>
<p>The site is built in <strong>Joomla 1.5.x</strong> so already loads the <strong>mootools 1.11</strong> library. I was looking for example code on the net and found lots of references for fading the opacity of images with jQuery but not all that much for mootools.</p>
<p>Any pointers would be appreciated :)</p>
| <p>You may be able to wrap the image into a div and use something like this to fade?</p>
<pre><code>Fx.Style("div1", "opacity").start(1.0);
</code></pre>
|
Using the Euro symbol in JavaScript and PHP <p>I using the price in <a href="http://en.wikipedia.org/wiki/Euro" rel="nofollow">Euro</a> in JavaScript:</p>
<pre><code>var currency = '\u20AC';
Total Sum = Sum in Euro
</code></pre>
<p>When I try to use in PHP mail, the Euro symbol appears differently. I used the following command:</p>
<pre><code>$mail_body_reply=Sum from Javascript
mail($email, $subject_reply, $mail_body_reply, $header_reply);
</code></pre>
<p>What is the way to make it act the same in PHP and JavaScript?</p>
| <p>You have to add encoding to the mail header, like described in <a href="http://www.php.net/manual/en/book.mail.php#86537" rel="nofollow">a comment to documentation for function mail()</a>.</p>
<p>The right encoding is probably <a href="http://en.wikipedia.org/wiki/ISO/IEC_8859-15" rel="nofollow">ISO/IEC 8859-15</a>.</p>
|
How to make 'always-on-bottom'-window <p>Does anybody know how to make a 'always-on-bottom'-windows, or a window pinned to the desktop? It should receive focus and mouseclicks, but should stay at the bottom of the Z-order. It would also be great if it could stay on the desktop even when user do a minimize all or show desktop operation.</p>
<p>Both delphi and c# solutions (or partial solutions/hints) would be great.</p>
| <p><strong>Warning</strong> It was suggested that you can accomplish this by calling SetParent and setting the window to be a child of the Desktop. If you do this, you cause the Win32 Window Manager to combine the input queue of the Desktop to your child window, this is a <em>bad thing</em> - <a href="http://blogs.msdn.com/oldnewthing/archive/2004/02/24/79212.aspx">Raymond Chen explains why.</a></p>
<p>Also, keep in mind that calling SetWindowPos with HWND_BOTTOM is incomplete. You need to do this whenever your window is changing zorder. Handle the WM_WINDOWPOSCHANGING event, look at SWP_NOZORDER for more info.</p>
|
Query question related to retrieving the most recent entry from a table? <p>Hi I'm not good in framing questions. I will try my best. I'm creating a website and my question is related to the queries related to the site.This is the current query that I have. </p>
<pre><code>SELECT
GPS_modem.vehicle_no,
vehicle_log.longitude,
vehicle_log.latitude,
vehicle_log.timestamp
FROM
vehicle_log,
GPS_modem
WHERE
GPS_modem.modem_ID = vehicle_log.modem_ID
ORDER BY
timestamp desc
</code></pre>
<p>What I want to display is the entry with the most recent timestamp from the <code>vehicle_log</code> table where the <code>modem_ID</code> from the <code>GPS_modem</code> table matches with the <code>modem_ID</code> from <code>vehicle_log</code> table. </p>
<p>I tried using <code>DISTINCT</code> but I didn't work. I was getting errors when I tried using <code>MAX</code> function. Hope you are able to understand my question, if then please help me. Thanking you in advance.</p>
| <p>You can use correlated sub-query:</p>
<pre><code>SELECT
m.vehicle_no,
l.longitude,
l.latitude,
l.timestamp
FROM
vehicle_log AS l,
GPS_modem AS m
WHERE
m.modem_ID = l.modem_ID
AND l.timestamp = (
SELECT MAX(timestamp) FROM vehicle_log WHERE modem_ID = l.modem_ID
)
</code></pre>
<p><hr /></p>
<p>EDIT: In revision #1 of my answer, I had the query seen above. Then something made me think I should change it to the one below. The one below works but is unnecessary complicated, very probably performing worse. Having slept on it, I recommend against this approach. ;-)</p>
<pre><code>SELECT
m.vehicle_no,
latest.longitude,
latest.latitude,
latest.timestamp
FROM
GPS_modem AS m,
(
SELECT
modem_ID,
longitude,
latitude,
timestamp
FROM
vehicle_log AS l
WHERE
timestamp = (
SELECT MAX(timestamp) FROM vehicle_log WHERE modem_ID = l.modem_ID
)
) AS latest
WHERE
m.modem_ID = latest.modem_ID
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.