input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Can I ignore delegate parameters with lambda syntax? <p>I am curious why C# allows me to ignore delegate parameters in some cases but not others.</p>
<p>For instance this is permitted:</p>
<pre><code>Action<int> action = delegate { Console.WriteLine("delegate"); };
</code></pre>
<p>but this is not:</p>
<pre><code>Action<int> action = () => Console.WriteLine("lambda");
</code></pre>
<p>Is there a way to initialize a delegate and ignore the parameters using a lambda? I know that I can add a single parameter to the lambda and fix the previous line but this is more of an academic question pertaining to the compiler and why or how this works.</p>
| <p>I believe that your first sample actually creates an anonymous function that is able to take on many different signatures whose body is the single statement <code>Console.WriteLine...</code>. Because it can match different signatures, it does not cause a problem. In the second sample, the lambda syntax itself defines a function that takes no parameters with the same body. Obviously the latter is not consistent with the defined Action so you get the error.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/0yw3tz5k.aspx">C# Anonymous Method Reference</a></p>
<blockquote>
<p>There is one case in which an
anonymous method provides
functionality not found in lambda
expressions. Anonymous methods enable
you to omit the parameter list, and
this means that an anonymous method
can be converted to delegates with a
variety of signatures. This is not
possible with lambda expressions.</p>
</blockquote>
|
What do you mean Ruby on Rails is not thread safe? <p>I was just reading up on ROR (haven't dived into it yet), and I hear that it isn't thread safe. Obviously, this doesn't mean that more than one person can't access your site at one time, so what exactly does it mean? Where do threads come into play in ROR? Do they just mean the request handling?</p>
| <p>Your information is out of date.
It is thread safe as of <a href="http://guides.rubyonrails.org/2_2_release_notes.html" rel="nofollow">2.2.2</a></p>
<p>Keep in mind <a href="http://en.wikipedia.org/wiki/Ruby_MRI" rel="nofollow">Ruby MRI 1.8.x</a>, the most widely used implementation of Ruby uses <a href="http://en.wikipedia.org/wiki/Green_threads" rel="nofollow">Green Threads</a>, so with 1.8.x if you create 100 threads they all run on the same CPU. Therefore when hosting Rails websites using MRI, you probably want as many instances of Ruby running as you have CPUS. Stuff like <a href="http://www.modrails.com/" rel="nofollow">passenger</a> takes care of this for you. </p>
<p>This used to be a big problem for <a href="http://jruby.codehaus.org/" rel="nofollow">JRuby</a>, because JRuby has Native threads, and juggling processes seems superfluous. Anyway, its sorted out now. </p>
<p>On an aside, Iron Ruby, the .Net Ruby interpreter runs native threads. </p>
<p>Note: Ruby 1.9.1 uses native threads, but there is still a global interpreter lock in place.</p>
|
Difference between -Wconversion between gcc and g++ <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="http://stackoverflow.com/questions/310108/can-i-make-gcc-warn-on-passing-too-wide-types-to-functions">Can I make GCC warn on passing too-wide types to functions?</a> </p>
</blockquote>
<p>Consider the following test program:</p>
<pre><code>static void func(int a)
{
}
int main()
{
unsigned int b = 42;
func(b);
return 0;
}
</code></pre>
<p>Compiling it with gcc:</p>
<pre>
lol@mac:~/projects$ gcc -Wconversion testit.c
testit.c: In function âmainâ:
testit.c:11: warning: passing argument 1 of âfuncâ as signed due to prototype
lol@mac:~/projects$
</pre>
<p>But, in g++ there is no warning!:</p>
<pre>
lol@mac:~/projects$ g++ -Wconversion testit.c
lol@mac:~/projects$
</pre>
<p>What is the reason for this and is there any way to get the same warning when compiling C++ code?</p>
| <p>From <a href="http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/Warning-Options.html" rel="nofollow">the documentation</a> for <code>-Wconversion</code>:</p>
<blockquote>
<p>Warnings about conversions between signed and unsigned integers are disabled by default in C++ unless -Wsign-conversion is explicitly enabled.</p>
</blockquote>
<p>Seems that you'll need a sufficiently new version of GCC, too. I have version 4.0.1, and it doesn't recognize <code>-Wsign-conversion</code>.</p>
|
Asynchronous SQLCommand and CCR <p>I have been playing with the demo code from this msdn article by <a href="http://msdn.microsoft.com/en-au/magazine/cc163556.aspx" rel="nofollow">Jeffrey Richter</a>. </p>
<p>I have added a new function to his ApmToCcrAdapters to handle the SqlCommand.BeginExecuteReader. Only it is closing the reader before I can read it.</p>
<p>The following code is used to provide a FromIteratorHandler:</p>
<pre><code> private static IEnumerator<ITask> AsyncReaderDemoHandler()
{
SqlDataReader reader = null;
SqlConnection connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=BizData;Integrated Security=True;Async=True;");
string query = "SELECT * FROM Account;";
SqlCommand command = new SqlCommand(query,connection);
connection.Open();
yield return Arbiter.Choice(ApmToCcrAdapters.GetReader(command),
delegate(SqlDataReader r) { Msg("Got SQL data"); reader = r; },
delegate(Exception e) { Msg("Failed to get SQL data"); });
connection.Close();
if (reader == null) yield break;
//This is where the code fails: Reader is Closed!
while (reader.Read())
{
Console.WriteLine(reader["Account"]);
}
}
</code></pre>
<p>Which in turn calls the following code:</p>
<pre><code> /// <summary>
/// Gets the Reader, requires connection to be managed
/// </summary>
public static PortSet<SqlDataReader, Exception> GetReader(SqlCommand sqlCommand)
{
Port<SqlDataReader> portResponse = null;
Port<Exception> portException = null;
GetReaderResponse(sqlCommand, ref portResponse, ref portException);
return new PortSet<SqlDataReader, Exception>(portResponse, portException);
}
// Wrapper for SqlCommand's GetResponse
public static void GetReaderResponse(SqlCommand sqlCom,
ref Port<SqlDataReader> portResponse, ref Port<Exception> portException)
{
EnsurePortsExist(ref portResponse, ref portException);
sqlCom.BeginExecuteReader(ApmResultToCcrResultFactory.Create(
portResponse, portException,
delegate(IAsyncResult ar) { return sqlCom.EndExecuteReader(ar); }), null);
}
</code></pre>
| <p>The connection must remain open for the Reader to work. I believe closing the connection is your problem. Leave the connection open and call dispose on the reader when done and I think that should clean up the connection.</p>
|
Javascript on page is not executing before AJAX onComplete event is called <p>I have a form that makes an Ajax POST request to insert a widget into my database. In the form, I have a select box where you can select from the widgets. After the db insert is made, I must update the select box. I actually just replace the entire form for now. </p>
<p>Because the select box has the widgets, I must have a copy of the objects in javascript. I call this var widget_objects. When the form is replaced during the update event, I print the ruby variable <%= @widget_objects %> and I can see the newly created object. However, when I try to access the javascript var "widget_objects" in the onComplete event, the new object does not exist. I create the javascript widget_objects with this line of code on the page:
widget_objects = <%= @widget_objects %>;</p>
<p>So it seems that the line of code above is not executed before Ajax request's onComplete event. However, I thought the onComplete event occurs after the page has been loaded, and I would assume after scripts are eval'd....any ideas?</p>
<pre><code><%= submit_to_remote(
"save_widget",
"Save Widget & Generate Embed Code",
{
:url => widgets_url(:user_id => @user.id),
:update => "widget_form",
:method => :POST,
:html => { :id => "save_widget_button",
:onclick => "this.value='Saving...'; this.disabled = 'true';",
:style => "width: 220px;"
},
:complete =>"
$('save_widget_button').disabled='';
$('save_widget_button').value='Save Widget & Generate Embed Code';
var last_id = $j('select#widget_id').children(':last').attr('value');
alert( widget_objects[last_id] );
",
:success => "reportMessage('success', request.headerJSON.success, 'save_widget_status'); $('band_form').reset();",
:failure => "reportMessage('failure', request.headerJSON.errors, 'save_widget_status');"
}) %>
</code></pre>
| <p>Setting EvalScripts to true must work.</p>
<p>else you can try loading the script using </p>
<pre><code>> <script> function window.onload(){
> alert('I am loaded as the page
> completes loading') } </script>
</code></pre>
<p>if this does not help then you can call function :loading in ajax calls while the response is received the function will be called.</p>
|
JavaScript 64 bit numeric precision <p>Is there a way to represent a number with higher than 53-bit precision in JavaScript? In other words, is there a way to represent 64-bit precision number?</p>
<p>I am trying to implement some logic in which each bit of a 64-bit number represents something. I lose the lower significant bits when I try to set bits higher than 2^53.</p>
<pre><code>Math.pow(2,53) + Math.pow(2,0) == Math.pow(2,53)
</code></pre>
<p>Is there a way to implement a custom library or something to achieve this?</p>
| <p>Google's Closure library has <a href="http://docs.closure-library.googlecode.com/git/class_goog_math_Long.html" rel="nofollow">goog.math.Long</a> for this purpose.</p>
|
Create history of states in Java <p>I need to save a history of states over a few actions in a Java application, which I can later reload in order to restore the state at a certain action. In other words I have a screen which has a state associated with it and I need to store it as well as any changes in a history so that I can restore the state of the screen at any time. This is kind of like 'undo' but not exactly as the difference between two state can be very large and there are no well-defined actions that changes the states.</p>
<p>Let me explain with an example:
A very basic screen state might just contain a single Map. In state A this Map contains a reference to "Object1" with key "Key1" and "Object2" with key "Key2". In state B the Map still contains the reference to "Object1", but "Object2" has been modified and an "Object3" has been added. I now need to be able to return to state A, which would involve "dropping" Object3 and restoring Object2 to its previous state. I cannot define any custom "undo actions" as I do not know what changes were made to Object2 or even what the type of Object2 is. Further, because the reference remains the same for Object2 in state A and B, those changes are reflected in state A so Object2 isn't the same as it was.</p>
<p>I realize the best solution is to implement clone methods, but as I need to support all types of Objects (including primitives and standard collections) this isn't feasible. I thought about using serializable, where I would serialize the Map as soon as a state transition happens and then deserialize it when it is needed again, but it seems like a very ugly solution.</p>
<p>Does anybody have any other ideas?
Thank you,
Ristretto</p>
| <p>Have you tried looking into the <a href="http://en.wikipedia.org/wiki/Memento_pattern">Memento Design Pattern</a>? It seems particularly well defined for your problem. From Wikipedia:</p>
<blockquote>
<p>The memento pattern is a software
design pattern that provides the
ability to restore an object to its
previous state (undo via rollback).</p>
</blockquote>
<p>The same page also has a section with a <a href="http://en.wikipedia.org/wiki/Memento_pattern#Java">Java implementation</a> since you mentioned this is in Java.</p>
|
DynamicArray throws OutOfBounds exception <p>I know this may sound strange, but yes, it's 2009 and I need to write small application using BCB5 :) </p>
<p>The problem is that DynamicArray throws OutOfBound exception when trying to expand it from within worker thread.</p>
<p>I have global variable, let's say </p>
<pre><code>DynamicArray<double> X;
</code></pre>
<p>In main thread I check the length of array and I get 0, which is OK (length wasn't set)</p>
<pre><code>Application->MessageBox(itoa(X.Length,str , 10), "", MB_OK);
</code></pre>
<p>Below is my worker thread class</p>
<pre><code>class ArrayModifierThread : public TThread
{
private:
DynamicArray<double> __thread X;
protected:
void __fastcall Execute();
public:
__fastcall ArrayModifierThread(bool CreateSuspended);
void setX(DynamicArray<double> &a);
};
</code></pre>
<p>So far so good. Next I create new thread:</p>
<pre><code>ArrayModifierThread *t = new ArrayModifierThread(true);
t->setX(X); // Pass reference to my global DynamicArray
t->Resume();
</code></pre>
<p>Here the Execute() method gets executed:</p>
<pre><code>void __fastcall ArrayModifierThread::Execute()
{
X.Length = 10;
X[5] = 45.5;
}
</code></pre>
<p>What I'd expect is that global array is expanded and 6th element gets value of 45.5.</p>
<p>But closer investigation from within main thread gives Length = 0 and ArrayOfBounds Exception:</p>
<pre><code> Application->MessageBox(itoa(__X.Length,str , 10), "", MB_OK);
Application->MessageBox(itoa(__X[5],str , 10), "", MB_OK);
</code></pre>
<p>Could anybody tell me what I've missed? </p>
| <p>In your <code>Execute</code> method you're modifying the <em>thread's</em> <code>X</code> field, not the global <code>X</code> variable. Although the <code>setX</code> method receives its argument by reference, the member variable is not a reference. It stores a <em>copy</em> of the <code>DynamicArray</code> value, and changing the <code>Length</code> property ensures that it refers to a unique array.</p>
<p>The <code>setX</code> function <em>receives</em> a reference to the global variable, as you correctly observe in your "answer," but it doesn't <em>keep</em> a reference to it. It instead makes a copy of it when it assigns the object's <code>X</code> field.</p>
<p>Perhaps you intended to declare <code>X</code> as a reference as well:</p>
<pre><code>private:
DynamicArray<double>& X;
</code></pre>
<p>That could work. Your <code>setX</code> function wouldn't work anymore since you're not allowed to "re-seat" a reference after it's been initialized. Instead, you'd need to initialize it in the thread's constructor:</p>
<pre><code>ArrayModifierThread(DynamicArray<double>& a): X(a) { ... }
</code></pre>
<p>You could also store a <em>pointer</em> to the array instead of a reference:</p>
<pre><code>private:
DynamicArray<double>* X;
public:
void setX(DynamicArray<double>& a) {
X = &a;
}
protected:
void Execute() {
X->Length = 10;
(*X)[5] = 45.5;
}
</code></pre>
<p>Something else you need to be aware of is that your code is not thread-safe. (Neither is mine here.) You have multiple threads modifying the same shared resource (the array) without any protection, such as a critical section. That's beyond the scope of this question, though. Search Stack Overflow and the rest of the Web first, and then come back to ask a <em>new question</em> if you need help with that issue.</p>
|
Excel import returns blank cells <p>I have had this problem forever and never managed to figure it out. </p>
<p>I am importing an excel (.xls) file into an asp recordset. Most of the time this works great. </p>
<p>I have column with the following values</p>
<pre><code>4
4
5,6
3
</code></pre>
<p>Asp reads those values in except for the 5,6. I have tried formatting the cells and this makes no difference. It appears that asp (or excel) are trying to determine the type of the cell by examining the value. For whatever reason it then throws this hiccup if some of the cells aren't the same format as the majority of the other are. </p>
| <p>The problem is that ADO scans the first 8 rows and based on the data it finds in each column it sets the column type. So if your first 8 rows contain numbers then it sets that column to numeric and returns null for any other values, for example if the ninth row contains text or a comma. See <a href="http://blog.lab49.com/archives/196" rel="nofollow">http://blog.lab49.com/archives/196</a> for some suggestions on how to avoid this.</p>
|
What are the performance implications of getElementsByTagName("*")? <p>Let me start out by saying that I'm not a JavaScript developer so this question may be rather basic.</p>
<p>When simulating IE's nonstandard <a href="http://msdn.microsoft.com/en-us/library/aa752281(VS.85).aspx" rel="nofollow"><code>all</code></a> property I'm using <code>getElementsByTagName("*")</code>, is there a significant performance difference between both methods?</p>
| <p>For Interest, you may find this lecture by John Resig interesting. Its relevant to new and experienced users alike when using dom methods like you are. </p>
<ul>
<li><a href="http://ejohn.org/blog/the-dom-is-a-mess/" rel="nofollow">http://ejohn.org/blog/the-dom-is-a-mess/</a></li>
</ul>
<p>It discusses many lovely caveats of dom methods in many browsers. </p>
<p>One such, is that <code>getElementsByTagName(â*â)</code> will return <strong>no</strong> elements in IE5, and does <a href="http://webbugtrack.blogspot.com/2007/09/bug-204-getelementsbytagname-doesnt.html" rel="nofollow">weird things</a> with Objects + <code>getElementsByTagName("*")</code> under IE7, and according to the talk, it makes this: </p>
<pre><code> <a id="length"></a>
</code></pre>
<p>Perform as if somebody had done: </p>
<pre><code> var a = getElementsByTagName("a");
a.length = ""; # This overrides the arrays length attribute :/
</code></pre>
<p>So that you can't iterate the array. </p>
<p>I don't know which javascript libraries circumvent this flaw, but you really should use one to avoid cross-browser headaches. </p>
|
Caching system like memcached but where I need to list what is in the cache <p>What's the best caching system/daemon that supports get, put, delete and list (memcached, I think, doesn't support list)</p>
<p>An example </p>
<p>I would like to use memcached for my caching solution but I'm stuck with the application design that I currently have which is that I cache the following 3 URLs I need to always have different cache keys. That stops me from just declaring a list of URL params with which I could generate a cache item for.</p>
<ul>
<li>/badappdesign?iod=3</li>
<li>/badappdesign?iod=3&h=23</li>
<li>/badappdesign?iod=3&dsfj=435&dasv=342</li>
</ul>
<p>In this instance iod=3 has changed so I need to clear all the keys that contain iod=3</p>
<p>I currently cache to a db and have to do a fairly expensive like '%iod=3%'</p>
<p>what can help?</p>
| <p>You can check <a href="http://stackoverflow.com/questions/109480/caching-paginated-results-purging-on-update-how-to-solve">Caching paginated results, purging on update - how to solve?</a></p>
|
selenium-maven-plugin <p>i'm trying to set up the selenium-maven-plugin and having some difficulties i hope somebody can help me. My configuration looks like this:</p>
<pre><code><plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>selenium-maven-plugin</artifactId>
<executions>
<execution>
<phase>pre-integration-test</phase>
<goals>
<goal>start-server</goal>
<goal>selenese</goal>
</goals>
<configuration>
<background>true</background>
<browser>*firefox</browser>
<results>src/test/resources/selenium/result.html</results>
<startURL>http://localhost/MyProject</startURL>
<suite>src\test\resources\selenium\Testsuite.html</suite>
</configuration>
</execution>
</executions>
</plugin>
</code></pre>
<p>I have cargo setup as well which works perfectly. However the start-server goal runs without problems but when maven tries to execute the selenium:selenese goal i get this exception: Could not find matching constructor for: org.openqa.selenium.server.SeleniumServer(java.lang.Integer, java.lang.Boolean, java.lang.Boolean)</p>
<p>An suggestions? Thanks in advance for your help.</p>
| <p>It's a bug in selenium, which can be fixed by downloading a new version.</p>
|
How we can show UIViewController and UIView by using Cocos2d? <p>I am trying to build an iPhone app by using Cocos2d.But i have used four types of classes
like bellow-</p>
<pre><code>@interface MenuScene : Scene {}
@end
@interface FlipView : UIImageView
{
CGPoint startTouchPosition;
NSString *dirString;
UIImageView *firstPieceView;
UIImageView *secondPieceView;
}
@end
@interface HelloController : UIViewController
@end
@interface MenuLayer: Layer{
Todo *todo;
Menu * menu;
sqlite3 *database;
NSMutableArray *todos;
NSString *dirString;
CGPoint startTouchPosition;
}
@property (nonatomic, retain) NSMutableArray *todos;
-(void) button1: (id)sender;
-(void) button2: (id)sender;
-(void) black_jack: (id)sender;
@end
</code></pre>
<p>but how can i show FlipView and HelloController class through MenuLayer class.</p>
| <p>If you are asking how to attach UIKit views and such to a cocos2d-iphone project, you just have to do it like:</p>
<pre><code>[[[Director sharedDirector] window] addSubview:myView];
</code></pre>
<p>Updated to cocos 0.7 and now this is:</p>
<pre><code>[[[Director sharedDirector] openGLView] addSubview:myView];
</code></pre>
<p>And in Cocos 0.99:</p>
<pre><code>[[[CCDirector sharedDirector] openGLView] addSubview:myView];
</code></pre>
<p>And in Cocos 2.0</p>
<pre><code>[[[CCDirector sharedDirector] view] addSubview:myView];
</code></pre>
|
Simulate build provider in ASP.NET Web Application (.Net 2.0) <p>I am working with .Net 2.0 ASP.NET Web Application.</p>
<p>I am programmatically creating an assembly containing namespace and classes specified within xml file in the web application.
I have created a separate library that does that, I get the assembly and that's fine.</p>
<p>But I don't want to reference this as a precompiled component.</p>
<p>I want to create it on the fly, so when I run the build of the web application, the assembly is built, the reference to the assembly added and then the web application code can use it further. Plus, I can have the intellisense.</p>
<p>Now this is exactly the scenario for the build providers, but the problem is that the build providers don't work with this type of application.</p>
<p>I have managed to run the assembly generation tool like so:</p>
<pre><code><Target Name="BeforeBuild">
<Exec Command="CreateAssembly.exe config.xml"/>
</Target>
</code></pre>
<p>But no luck with dynamically referencing the generated assembly..</p>
| <p>The class you are looking for is the Assembly class within the System.Reflection namespace.</p>
<h2>Example</h2>
<pre><code>Assembly.Load(AssemblyPath)
</code></pre>
<p>or</p>
<pre><code>Assembly.LoadFrom(AssemblyPath)
</code></pre>
<p>These methods can be used to load a non-referenced assembly into your app-domain.</p>
<p>There are various conditions and restrictions so I would read up on them both.</p>
<h2>Links</h2>
<p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.load.aspx" rel="nofollow">Assembly.Load</a> (MSDN)</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.loadfrom.aspx" rel="nofollow">Assembly.LoadFrom</a> (MSDN)</p>
<p><a href="http://support.microsoft.com/kb/837908" rel="nofollow">Useful MS KB Article</a></p>
<p>Have fun!</p>
|
Object must be locked to be used? <p>I was pondering language features and I was wondering if the following feature had been implemented in any languages.</p>
<p>A way of declaring that an object may only be accessed within a Mutex. SO for example in java you would only be able to access an object if it was in a synchrnoised block and in C# a Lock.</p>
<p>A compiler error would ensue if the object was used outside of a Mutex block.</p>
<p>Any thoughts?</p>
<p><strong>UPDATE</strong></p>
<p>I think some people have misunderstood the question, I'm not asking if you can lock objects, I'm asking if there is a mechanism to state at declaration of an object that it may only be accessed from within a lock/synchronised statement.</p>
| <p>There are two ways to do that.</p>
<p>Your program either refuses to <strong>run</strong> a method unless the protecting mutex is locked by the calling thread (that's a <code>runtime check</code>); or it refuses to <strong>compile</strong> (that's a <code>compile time check</code>).</p>
<p>First way is what <code>C# lock</code> does.</p>
<p>Second method requires a compiler able to evaluate every execution path possible. It's hardly feasible.</p>
|
MySQL sorting the result using a field of a different table <p>I have 3 tables of the following structure</p>
<pre><code> products
{
pid
pname
plocation...
}
services
{
s_id
s_name
s_location...
}
txn
{
tid
pid...
}
</code></pre>
<p>I am using the following query to get the values I require.</p>
<pre><code> $dbquery = "SELECT DISTINCT products.pid AS id,
products.pname AS name,
products.p_desc AS description,
products.p_loc AS location,
products.category AS category,
products.p_uid AS userid,
products.add_date AS dateadded,
products.isaproduct AS whatisit
FROM products
WHERE products.pname
LIKE '%".$keyword."%'
AND category = '".$refine_value."'
UNION
SELECT DISTINCT services.s_id AS id,
services.s_name AS name,
services.s_desc AS description,
services.s_category AS category,
services.s_uid AS userid,
services.s_location AS location,
services.date_added AS dateadded,
services.isaservice AS whatisit
FROM services
WHERE services.s_name
LIKE '%".$keyword."%'
AND s_category = '".$refine_value."'
</code></pre>
<p>I need to order the values I select by getting the count of pid in txn table which I get in the query above.</p>
<p>How can I do this?</p>
| <p>First of all, use parameterized queries instead of building a query string like that. It bothers me.</p>
<p>But it looks like all you're really needing to do is to group by the pid column in the txn table.</p>
<p>Define a view like</p>
<pre><code>SELECT pid, COUNT(tid) tid_count
FROM txn
GROUP BY pid
</code></pre>
<p>And join it into your query, then order by tid_count.</p>
|
Writing standards for unit testing <p>I plan to introduce a set of standards for writing unit tests into my team. But what to include?</p>
<p>These two posts (<a href="http://stackoverflow.com/questions/155436/unit-test-naming-best-practices">Unit test naming best practices</a> and <a href="http://stackoverflow.com/questions/377423/best-practices-for-file-system-dependencies-in-unit-integration-tests">Best practices for file system dependencies in unit/integration tests</a>) have given me some food for thought already.</p>
<p>Other domains that should be covered in my standards should be how test classes are set up and how to organize them. For example if you have class called OrderLineProcessor there should be a test class called OrderLineProcessorTest. If there's a method called Process() on that class then there should be a test called ProcessTest (maybe more to test different states).</p>
<p>Any other things to include?</p>
<p>Does your company have standards for unit testing?</p>
<p>EDIT: I'm using Visual Studio Team System 2008 and I develop in C#.Net</p>
| <p>Have a look at <a href="http://www.artima.com/weblogs/viewpost.jsp?thread=126923" rel="nofollow">Michael Feathers on what is a unit test</a> (or what makes unit tests bad unit tests)</p>
<p>Have a look at the idea of "Arrange, Act, Assert", i.e. the idea that a test does only three things, in a fixed order:</p>
<ul>
<li><strong>Arrange</strong> any input data and processing classes needed for the test</li>
<li>Perform the <strong>action</strong> under test </li>
<li>Test the results with one or more <strong>asserts</strong>. Yes, it can be more than one assert, so long as they all work to test the action that was performed.</li>
</ul>
<p>Have a Look at <a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development" rel="nofollow">Behaviour Driven Development</a> for a way to align test cases with requirements.</p>
<p>Also, my opinion of standard documents today is that you shouldn't write them unless you have to - there are lots of resources available already written. Link to them rather than rehashing their content. Provide a reading list for developers who want to know more.</p>
|
Publishing my ASP.NET site ruins the Subversion files <p>I've been trying to use SVN to deploy my asp.net site to production. My workflow is:</p>
<p>Setup:
Publish Site to FolderX,
Import FolderX to SVN,
Update web server production folder with the repository for FolderX.</p>
<p>Everyday:
Publish updated site to FolderX,
Commit Changes,
Update remote server with changes.</p>
<p>That's the theory, but when I publish the site again to FolderX, it destroys the .svn folders that are inside all the site subfolders.</p>
<p>How can prevent that from happening?</p>
| <p>Well, a couple of things:</p>
<p>First, why does it matter if the .svn folders within the website are ruined? Surely you're not committing FROM your production environment back into SVN? I suspect the problem you're having is later updates. You can solve that particular problem by deleting the entire site before you update into it.</p>
<p>Second, why are you trying to use SVN for deployment? That's not really what it's for, and all it would take is about 5 lines of batch code to deploy your entire tree to the production location.</p>
|
Message / confirm dialog <p>I have a need for a confirm message box from a button click, but only on some conditions. I am cheking two values on the aspx.page, and if one is higher than another, I need a confirmation from the user. Are there any ( simple) way of doing this ? I have been reading about javascript and alert messages, but I cant seem to figure out this one....
I am using RadStudio 2007, .net application.</p>
<p>Any help are appriciated.
Anja</p>
| <p>JavaScript provides what you need with the confirm function. This displays a confirmation box allowing the user to 'OK' or 'Cancel'.
An example function based on what you require:</p>
<pre><code>function FormSubmit(){
var value1 = document.getElementById("Textbox1").value;
var value2 = document.getElementById("Textbox2").value;
if(value1 > value2){
if(confirm("Are you sure?")) {return true;} else {return false;}
}
}
</code></pre>
<p>This function can now be added to the buttons onclick method</p>
<pre><code><input type="Button" value="Submit" onclick="return FormSubmit()" />
</code></pre>
|
How do I use a Checkbox on a form to add a record into a subform in Microsoft Office Access? <p>I have a database for a carpet company. I have a form which enables the user to make a quote, including choosing the customer, etc. There is a also subform dealing with the products and extras, with quantities and unit prices. To state whether the user requires fitting there is a checkbox. When ticked I would like fitting to be added in the subform as one of the products. Products are normally manually chosen using a dropdown.</p>
<p>Important properties are:<br />
Form name: <strong>Orders</strong><br />
Subform name: <strong>Order Details Subform</strong><br />
Checkbox name: <strong>Fitting</strong><br />
Field name for products: <strong>Product ID</strong><br />
Subform linked to table: <strong>Order Details</strong><br />
Form linked to table: <strong>Orders</strong></p>
<p>I'm assuming VBA is needed, or the macro builder.</p>
<p>Anyway thanks in advance!!</p>
| <p>I think the easiest way is to use an append query.</p>
<pre><code>If Me.Fitting Then
strSQL="INSERT INTO [Order Details] (ProductID,OtherTextField) Values ("
& Me.ProductID & ",'" & Me.OtherTextField & "')"
CurrentDB.Execute strSQL, dbFailOnError
Me.[Subform control name here].Form.Requery
End If
</code></pre>
|
The while language <p>For my theory of computing languages class, we got a homework assignment to implement a piece of code in a language that only has while statements for flow control (no if statements). This is mainly to prove that you can write a Turing-complete language with only a while loop.</p>
<p>For those of you who can understand language grammars, here are the language rules:</p>
<pre><code>S -> S;S | while C do S od | id := E
E -> E + T | T | E - T
T -> T * F | F | F / T
F -> id | cons | (E)
C -> E = E | E > E | E < E | E >= E | E <= E | E != E | C and C | C or C | not(C)
</code></pre>
<p>This is copied from my class notes, so don't blame me if something is missing or incorrect!</p>
<p>The piece of code to implement is this:</p>
<pre><code>if d = 0 do
x := 1
else
x := a / d
</code></pre>
<p>At any rate, if you want to go ahead and write that using the language rules above, go ahead. Otherwise, go ahead and write it in whatever language you're most comfortable in. But there are a few caveats!</p>
<ul>
<li>No if statements or any other kind of flow control other than while loops.</li>
<li>No cheating: the grammar above doesn't include any break statements, return statements, or exceptions. Don't use them.</li>
</ul>
<p>I've got my piece of code written for this (which I'll post just to prove this isn't a show me teh codez post). I'm kinda curious what anyone else can come up with though.</p>
| <p>Here's my code:</p>
<pre><code>continue := True
while d = 0 and continue do
x := 1
continue := False
od
while d != 0 and continue do
x := a/d
continue := False
od
</code></pre>
|
Button image too far from top of button; too close to bottom of button <p>I'm working on a Windows Form in VB.NET 2005 and I would like to have some buttons with images (I'm talking about the plain, vanilla System.Windows.Forms.Button). I have everything set up the way I want it but the images are displaying too low on the button, such that the bottom of the icon is almost right on the bottom of the button and there is a lot of space above the image. </p>
<p>Here is a screenshot:<br />
<img src="http://www.freeimagehosting.net/uploads/b28a5c63b8.jpg" alt="Button Screenshot" /></p>
<p>See how the corner of the icon is brushing up against the bottom of the button?</p>
<p>My button is 23 pixels high and the image is a 16 x 16 icon (converted to a bitmap so that it can be assigned to the button's Image property).</p>
<p>I've tried setting the button's Margin.All property to 0, and verified that the Padding.All property is 0. I've also tried changing the button's ImageAlign to TopLeft, MiddleLeft, and BottomLeft, but none of those settings seem to have any affect. </p>
<p>Does anyone know how I can position the image to be of equal distance from the top and bottom edges of the button? I can resize the button or the image if necessary but they are at my preferred size and I would like to keep them that way if possible. </p>
| <p>I just encountered a similar problem, which I was able to solve by thinking really hard. (Ain't those situations great?)</p>
<p>First it's important to understand that ImageAlign does NOT mean where on the button do you want the image. It means what point (pixel) on the image should be used for positioning. So if you pick "TopLeft", then the top-left-most pixel of the image will be vertically CENTERED on the button.</p>
<p>The problem comes in when you have a button with a centered image, whose ImageAlign is set vertically to "center", and whose dimensions are of an even number of pixels. Your image is 16x16 pixels- 16 is an even number. The middle pixel would theoretically be somewhere between pixel 8 and pixel 9. Since there is no pixel 8.5, VB rounds down to 8, thereby using pixel 8 as your positioning pixel. This the root cause of your unwanted upper margin.</p>
<p>Your button has an odd pixel height (23px) which means it has a true center pixel- pixel 12. VB tries to position the image's center pixel (8) on top of the button's center pixel (12). This puts 8 of the image's pixels BELOW center, and 7 pixels ABOVE center. To even things out, a 1-pixel margin appears above the image.</p>
<p>Here's the solution: Pad the image with 1 extra row of pixels on the bottom. The image now has a height that's odd (17 px), giving the image a true center pixel which can line up perfectly with the button's center pixel.</p>
<p>That's how I solved the problem for myself. However, a simpler possible solution just occurred to me. You could probably achieve the same result by assigning the image a bottom margin of 1px. I have not tested this solution but it seems theoretically equivalent to the first solution.</p>
<p>Additional note: Two objects of EVEN dimensions should theoretically be able to center-align perfectly. But strangely enough, the alignment problem occurs even if the button AND the image BOTH have even dimensions. (Apparently the compiler is not consistent in the way it determines the center pixel of one control vs another.) Nonetheless, in this case, the same solution applies.</p>
|
SQL Server 2005 Reporting Services - Pros and Cons <p>I am developing a web application using ASP .NET 2.0, VS 2008 and SQL Server 2005. I would like to Use SSRS 2005 for the various reports I need to build for this web application. I would like to convince the team that we should adopt SSRS as the main reporting platform for most internal and external web applications we have. </p>
<p>What are the pros and cons of Reporting Services? I can see many pros like tight integration with IIS, SQL Server and Visual Studio, rich presentation features and export functionality, subscription etc so I am mainly interested in negatives of SSRS.</p>
<p>EDIT: I understand that if I am not using VS 2005 for my application development, I will be using different Visual Studio versions for application and report development. However, I am more interested in negatives (or not so good aspects) of SSRS itself.</p>
| <p>I know you said 2005, but I will put in notes around 2008 as well.</p>
<p>SRS Pros:<br />
- It is free (provided you have the SQL server license)<br />
- Tight data integration with SQL Server, but it handles anything .NET can (Oracle, ODBC etc...) just fine. (<code>2008 has native support for Terradata too</code>)<br />
- Components for Visual Studio, SharePoint and PerformancePoint all exist to make it easy to leverage it. It is just a web app though so integration into any web page or app that can talk to a web server is easy too.<br />
- Built in tools to do subscriptions (i.e. emails that get sent out on a regular basis to a list of people with the report on them). The list of recipients can be static people or a sharepoint site or a dynamic list of people (pulled from a DB) (<code>08 adds support for dynamic to sharepoint too</code>)<br />
- 3rd party vendors exist to enhance the product<br />
- Export to a variety of formats (XML, CSV, Excel, PDF etc...)<br />
- Ability to design templates which power users can use to build reports without knowing SQL (since the SQL is contained in the template). Power users use a special report builder tool which is delivered via click once.<br />
- Works differently to Crystal reports (I don't like Crystal thats why this is a pro for me)</p>
<p>SRS Cons:<br />
- Charting controls look like Excel 2003 and are limited. (<code>2008 has the Dundas controls in by default so they are much more powerful, more varied and better looking</code>)<br />
- Kerberos issues due to it being a web app can cause annoying problems (<code>2008 removes that as it is no longer an IIS web app. It runs it's own web server based off the IIS core but is closer to a stand alone app - so the security issues aren't a problem</code>)<br />
- Designer support is a pain. 2000 Reports must be developed in VS 2003, 2005 reports must be developed in VS 2005, 2008 reports must be developed in VS 2008. By Visual Studio I mean the normal one or the thin downed version you get with the SQL Management tools.<br />
- Compatibility. Each version of reporting services can run only the current version and one version back of the reports.<br />
- Security is limited to Integrated Windows or Anonymous (<code>2008 has added support for forms based security and for custom providers, like you get with ASP.NET</code>)</p>
|
Load Balancing, Spring Security, ConcurrentSessionFilter <p>I have a Spring 2.5.6/Flex application setup and running with Spring Security 2.0.4. Recently a load balancer (A Foundry ServerIron 4g <a href="http://www.foundrynet.com/products/a...ems/si-4g.html" rel="nofollow">http://www.foundrynet.com/products/a...ems/si-4g.html</a>) was put into place and now I am getting cross domain errors. Basically the load balancer is firing off a request to myloadbalancer.abc.com and myrealserver1.abc.com is being returned as the domain name. Spring security is forwarding the request to the real server somehow. How can I get around this?</p>
<p>Also the ConcurrentSessionFilter is no longer working. The application is set up to disable concurrent logons, but this functionality stopped after the application was put behind the load balancer. I believe there are multiple Oracle Application Servers being clustered together as well. I have never dealt with clustering or load balancers before and I wasn't aware that the software had to be written differently in certain areas.</p>
<p>These sound like separate issues to me, but I need help for both.</p>
| <p>Concerning your second problem:</p>
<p>If the ConcurrentSessionFilter stopped working (i.e. does not prevent concurrent sessions anymore), that could be due to clustered application containers with sticky sessions.</p>
<p>In such a setup, each of the cluster's nodes works independently and doesn't share state with other nodes. Instead, the load balancer makes sure that existing sessions will always be served by the same node.</p>
<p>Now Spring Security's <code>ConcurrentSessionController</code> works by mapping sessions to principals. The controller itself relies on the <code>HttpSessionEventPublisher</code> sending <code>ApplicationEvents</code> on start and termination of user sessions.</p>
<p>Everything is will work fine if someone intending to open more than one session ends up on the same node he already has a session opened. <code>HttpSessionEventPublisher</code> informs the concurrent session mechanism of the session's creation and authentication will fail because there is already a session associated with this user. On a different node however, there is no session for that user yet, so <code>ConcurrentSessionController</code> does not complain and login succeeds.</p>
<p>Fortunately, solving the problem should be easy: Implement your own <code>SessionRegistry</code> and use a shared data store for all nodes (e.g. the application's database).</p>
|
Does IEnumerable<TSource> Concat<TSource> preserve the order of elements? <p>Assume two lists, A and B so that A = (1,2,3) and B = (4,5,6). Will A.Concat(B) preserve the order so that the result is (1,2,3,4,5,6)? </p>
| <p>Yes. IEnumerable.Concat will simply turn two list into a single list by attaching one to the end of the other. Order within each list will be preserved.</p>
|
How do I get the Localizable property and support in my own design tool? <h3>Overview</h3>
<p>In another question, I asked about <a href="http://stackoverflow.com/questions/205138/globalizing-runtime-generated-assemblies">deploying localizations for some runtime compiled <code>UserControl</code>'s</a>. However, before I can get to deploying the localizations, I need a way of localizing the controls.</p>
<h3>Background</h3>
<p>The controls are created by our own WinForms-style designer (using .NET's support for design surfaces, etc.) and saved as a binary format that combines the <code>CodeCompileUnit</code>, resource resx, and user source into one file. These files are then compiled into an assembly as appropriate at runtime by another tool.</p>
<p>In order to localize these, we need to tell the designer and serialization that localizable property values are to be stored in the resources. The VisualStudio WinForms designer does this using an extension property called <code>Localizable</code> and an associated property for specifying the default culture. We need this property in our custom designer, if possible.</p>
<h3>Constraints</h3>
<p>We need our standalone designer tool that is easy to use for non-developer types as well as restricting certain actions so using a free edition of Visual Studio (i.e. C# Express) is not going to work (I've already pitched it and failed); therefore, any solution to how we localize these UserControl's needs to compensate for this.</p>
<h3>Question</h3>
<p>Can we get the Localizable support into our custom WinForms designer?</p>
<ul>
<li>If yes, how?</li>
<li>If no, what alternatives are there to localizing our <code>UserControl</code>'s? e.g. post-processing somehow, different file format, etc.</li>
</ul>
| <p>I'm not sure if I understood your question correctly.</p>
<p>Just check for the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.localizableattribute.aspx" rel="nofollow">System.ComponentModel.LocalizableAttribute</a> on all properties to (de-)serialize if your control is Localizable.</p>
<pre><code>// Gets the attributes for the property.
AttributeCollection attributes =
TypeDescriptor.GetProperties(this)["MyProperty"].Attributes;
// Checks to see if the property needs to be localized.
LocalizableAttribute myAttribute =
(LocalizableAttribute)attributes[typeof(LocalizableAttribute)];
if(myAttribute.IsLocalizable) {
// Insert code for handling resource files here.
}
</code></pre>
<p>Since you decided to write your own designer you have to do this yourself.</p>
|
Adding resource file to VC6 dll <p>I have a number of VC 6.0 projects (dsps) which build into dlls which don't have resource files. Any idea how to add resources into an existing project?</p>
<p>The project is due for a major release shortly and I want to add a fileversion to those dlls currently lacking one. The dlls will be recompilied before release so I'm just trying to make these dsps like all the others I've inherited with this project (that do have a file and product version etc so that we can easily tell exactly what is running on a customer's machine.</p>
<p>One answer : Create an *.rc and resource.h file (copy from another project?) and add it to the source folder of ypur project in VC6 file view. The resource view is automatically created. Thanks for your help guys, gave me the pointers I needed.</p>
| <p>Just add a VERSIONINFO block to the resource file for the DLL. </p>
<p>Open the .rc file, and use "Insert/Resource.../Version" and you'll get a new VERSIONINFO resource with a bunch of defaults. If the project does not already have a resource file, you can add one using "File/New.../Resource Script".</p>
<p>If you want to roll your own, an example <code>VERSIONINFO</code> block is given on the <a href="http://msdn.microsoft.com/en-us/library/aa381058.aspx" rel="nofollow">MSDN page for VERSIONINFO</a>:</p>
<pre><code>#define VER_FILEVERSION 3,10,349,0
#define VER_FILEVERSION_STR "3.10.349.0\0"
#define VER_PRODUCTVERSION 3,10,0,0
#define VER_PRODUCTVERSION_STR "3.10\0"
#ifndef DEBUG
#define VER_DEBUG 0
#else
#define VER_DEBUG VS_FF_DEBUG
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VER_FILEVERSION
PRODUCTVERSION VER_PRODUCTVERSION
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
FILEFLAGS (VER_PRIVATEBUILD|VER_PRERELEASE|VER_DEBUG)
FILEOS VOS__WINDOWS32
FILETYPE VFT_DLL
FILESUBTYPE VFT2_UNKNOWN
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904E4"
BEGIN
VALUE "CompanyName", VER_COMPANYNAME_STR
VALUE "FileDescription", VER_FILEDESCRIPTION_STR
VALUE "FileVersion", VER_FILEVERSION_STR
VALUE "InternalName", VER_INTERNALNAME_STR
VALUE "LegalCopyright", VER_LEGALCOPYRIGHT_STR
VALUE "LegalTrademarks1", VER_LEGALTRADEMARKS1_STR
VALUE "LegalTrademarks2", VER_LEGALTRADEMARKS2_STR
VALUE "OriginalFilename", VER_ORIGINALFILENAME_STR
VALUE "ProductName", VER_PRODUCTNAME_STR
VALUE "ProductVersion", VER_PRODUCTVERSION_STR
END
END
BLOCK "VarFileInfo"
BEGIN
/* The following line should only be modified for localized versions. */
/* It consists of any number of WORD,WORD pairs, with each pair */
/* describing a language,codepage combination supported by the file. */
/* */
/* For example, a file might have values "0x409,1252" indicating that it */
/* supports English language (0x409) in the Windows ANSI codepage (1252). */
VALUE "Translation", 0x409, 1252
END
END
</code></pre>
|
SharePoint: Back up single page <p>I need to back up a sharepoint web page which containts web parts and other html tweaks. I would like to keep a back up of the page itself with the web parts in the appropriate places, is this possible? Right now I just opened SharePoint designer, opened my page and saved as to my hard drive. Is there another way? Is this a complete back up of the page? Thanks.</p>
| <p>I do the same for small changes and it has worked fine for me up to now. That said the only offical way to do it is use Microsoft's Data Protection Manager software which will let you backup/restore individual pages.</p>
|
Reporting Services - Rendering to Excel in C# WinForm <p>I have a WinForms application that can call for and display a number of reporting services reports. I can call the </p>
<pre><code>LocalReport.Render("Excel", null, out mimeType, out encoding, out filenameExtension, out streamids, out warnings);
</code></pre>
<p>method - writing to a byte[] array, but it throws an exception </p>
<blockquote>
<p>The source of the report definition has not been specified. </p>
</blockquote>
<p>Does anyone know how to solve this?</p>
| <p>Use the following param for the 2nd parameter. </p>
<pre><code><DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>
</code></pre>
<p>And you need to setup the report with something like:</p>
<pre><code>var MyInfo = MyRS.LoadReport("/" + reportPath, null);
var ReportDeviceInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
String ExtensionValue = String.Empty;
String EncodingValue = String.Empty;
String MimeTypeValue = String.Empty;
Warning[] WarningValue = null;
String[] StreamIDsValue = null;
var Result = MyRS.Render("Excel", ReportDeviceInfo, out ExtensionValue, out EncodingValue, out MimeTypeValue, out WarningValue, out StreamIDsValue);
</code></pre>
|
Problem with FTPClient class in java <p>I'm using org.apache.commons.net.ftp.FTPClient and seeing behavior that is, well... perplexing.</p>
<p>The method beneath intends to go through an FTPFile list, read them in and then do something with the contents. That's all working. What is not (really) working is that the FTPClient object does the following...</p>
<pre><code>1) Properly retrieves and stores the FIRST file in the list
2) List item evaluates to NULL for x number of successive iterations of the loop (x varies on successive attempts
3) manages to retrieve exactly 1 more file in the list
4) reports that it is null for exactly 1 more file in the list
5) hangs indefinitely, reporting no further activity.
public static String mergeXMLFiles(List<FTPFile> files, String rootElementNodeName, FTPClient ftp){
String ret = null;
String fileAsString = null;
//InputStream inStream;
int c;
if(files == null || rootElementNodeName == null)
return null;
try {
System.out.println("GETTING " + files.size() + " files");
for (FTPFile file : files) {
fileAsString = "";
InputStream inStream = ftp.retrieveFileStream(file.getName());
if(inStream == null){
System.out.println("FtpUtil.mergeXMLFiles() couldn't initialize inStream for file:" + file.getName());
continue;//THIS IS THE PART THAT I SEE FOR files [1 - arbitrary number (usually around 20)] and then 1 more time for [x + 2] after [x + 1] passes successfully.
}
while((c = inStream.read()) != -1){
fileAsString += Character.valueOf((char)c);
}
inStream.close();
System.out.println("FILE:" + file.getName() + "\n" + fileAsString);
}
} catch (Exception e) {
System.out.println("FtpUtil.mergeXMLFiles() failed:" + e);
}
return ret;
}
</code></pre>
<p>has anyone seen anything like this? I'm new to FTPClient, am I doing something wrong with it?</p>
| <p>According to the API for <a href="http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#retrieveFileStream(java.lang.String)"><code>FTPClient.retrieveFileStream()</code></a>, the method returns <code>null</code> when it cannot open the data connection, in which case you should check the reply code (e.g. <a href="http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTP.html#getReplyCode()"><code>getReplyCode()</code></a>, <a href="http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTP.html#getReplyString()"><code>getReplyString()</code></a>, <a href="http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTP.html#getReplyStrings()"><code>getReplyStrings()</code></a>) to see why it failed. Also, you are suppose to finalize file transfers by calling <a href="http://commons.apache.org/net/api/org/apache/commons/net/ftp/FTPClient.html#completePendingCommand()"><code>completePendingCommand()</code></a> and verifying that the transfer was indeed successful.</p>
|
What are the pros and cons of running IIS as 32bit vs 64bit on a 64bit OS? <p>Possibly better suited for "Rack Overflow", but from a developer's point of view, what are the advantages and disadvantages of running IIS (serving both legacy classic ASP and .NET) as a 32bit process instead of a 64bit process on a 64bit windows host? </p>
<p>The main advantage of 32/64 (iis/server) over 32/32 seems to be the ability to go up to 4gb in memory per IIS process. </p>
<p>The advantages I expect of 32/64 over 64/64 appear to be that it's easier to access legacy 32-bit in-process DLLs (of which we still have one from a partner vendor we can't move away from immediately) and perhaps a smaller memory footprint for the same code given smaller memory pointers. </p>
<p>Are there any performance benefits of 64/64 over 32/64 or anything else that would warrant a full switch now? Have I made any false assumptions here?</p>
| <p>The only perf advantage to running IIS on 64bit vevrsus 32-bit is to allow access to a much larger memory address space. </p>
<p>If you are doing normal ASPX page processing, then it's likely you don't need to address more than 4gb from any single process. Suppose you run in 32-bit mode with a web-garden with multiple worker processes on the same machine. In that case each process can address up to 4gb. </p>
<p>The big advantage can come when you perform caching. A 64-bit process can maintain a huge in-memory cache (assuming you have the 32GB or more of RAM to support it) to allow you to cache complex page content or data, on the web server. This allows perf gains when the data is more expensive to generate than it is to retrieve - for example if the data is an elaborated form (let's say the result of a monte carlo simulation), or if the data resides off-box and the network IO time is much more expensive than cache-retrieval time. </p>
<p>If you do not use caching, then 64-bit IIS is not going to help you. It will require 64-bit pointers for every lookup, which will make everything a little slower.</p>
<p>64-bit servers are much more effective when used for databases like SQL Server, or other data management servers (let's say, an enterprise email server like Exchange), than for processing servers, such as IIS or the worker processes it manages. With a 64-bit address space, servers that need to manage data can keep much more of that data in memory, along with indexes and other caches. This saves disk IO time and elaboration time when a query comes in. Most Web apps don't need to address more than 4gb from a single process.</p>
<hr>
<p>Maybe a useful analogy: In transport, an large SUV is like a 64-bit machine, while a regular, compact passenger car is like a 32-bit server. You can carry much more stuff in a large SUV, and it has a larger towing capacity, seating for 8 people, and <a href="http://autos.msn.com/research/vip/spec_engines.aspx?year=2005&make=Ford&model=Excursion">a GVWR of 8600 lbs</a>. But with all that, you pay. The truck is heavier. It uses more fuel. If you are only carting around 2 people and one duffel bag, you don't need an SUV. You'll be better off with the smaller vehicle. It can be speedier and more efficient. </p>
|
Is it possible to refresh a CSS sheet with an AJAX postback? <p>I have been learning how to create dynamic images and dynamic stylesheets using ASP.NET 3.5. My reasoning behind this is I have a web page that I want to change the header background image (set with css) automatically. Check below for my test script:</p>
<p><hr /></p>
<pre><code><%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<%
Response.Output.WriteLine("<link rel=""Stylesheet"" type=""text/css"" href=""style.aspx?t={0}&v={1}"" />", oType, oText)
%>
</head>
<body>
<form id="form1" runat="server" action="Default.aspx">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div class="testheader">&nbsp;</div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <%-- for testing --%>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="Button1" runat="server" Text="Button" />
</form>
</body>
</html>
</code></pre>
<p>So nothing special about the default form page above, it has an DIV styled to have the dynamic background image and a Label, which as the comment indicates is just to make sure my AsyncPostBack is functioning properly.</p>
<pre><code>Partial Class _Default
Inherits System.Web.UI.Page
Public oType As String = "m"
Public oText As String = "Genius on the Web"
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Select Case oType
Case "m"
oType = "c"
Case "c"
oType = "m"
End Select
Label1.Text = Now.ToString
End Sub
End Class
</code></pre>
<p>Again, nothing fancy. Just swaps the two values I have temporarily hard-coded into the program, and updates the Label text.</p>
<p>This is my dynamic stylesheet:</p>
<pre><code><%@ Page Language="VB" %>
<%
Response.ContentType = "text/css"
Dim qString As String = Request.QueryString("t")
Dim bText As String = Request.QueryString("v")
If String.IsNullOrEmpty(qString) Then qString = "blank"
If String.IsNullOrEmpty(bText) Then bText = "Placeholder"
Dim theColor, H1size, bannerImg As String
Select Case qString
Case "c"
theColor = "green"
H1size = 30
Case "m"
theColor = "blue"
H1size = 26
Case Else
theColor = "red"
End Select
bannerImg = String.Format("image.aspx?t={0}&p={1}", Server.UrlEncode(bText), qString)
%>
body { background-color: <%=theColor%>; }
.testheader { background: url(<%=bannerImg%>); background-repeat:no-repeat; height:120px; }
.testclass { font-size: <%=H1size%>px; border:1px solid yellow; margin-bottom:2em; }
</code></pre>
<p>Finally, here is my dynamic image script:</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Response.ContentType = "image/jpeg"
Response.Clear()
Response.BufferOutput = True
Try
Dim oText As String = Server.HtmlDecode(Request.QueryString("t"))
If String.IsNullOrEmpty(oText) Then oText = "Placeholder"
Dim oPType As String = Server.HtmlDecode(Request.QueryString("p"))
If String.IsNullOrEmpty(oPType) Then oPType = "none"
Dim imgPath As String = ""
Select Case oPType
Case "c"
imgPath = "img/banner_green.jpg"
Case "m"
imgPath = "img/banner_blue.jpg"
Case Else
Throw New Exception("no ptype")
End Select
Dim oBitmap As Bitmap = New Bitmap(Server.MapPath(imgPath))
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
Dim frontColorBrush As New SolidBrush(Color.White)
Dim oFont As New Font(FONT_NAME, 30)
Dim oInfo() As ImageCodecInfo = ImageCodecInfo.GetImageEncoders
Dim oEncoderParams As New EncoderParameters(1) 'jpeg
Dim xOffset As Single = Math.Round((oBitmap.Height - oFont.Height) / 2, MidpointRounding.ToEven)
Dim oPoint As New PointF(275.0F, xOffset + 10)
oEncoderParams.Param(0) = New EncoderParameter(Encoder.Quality, 100L)
oGraphic.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAlias
oGraphic.DrawString(oText, oFont, frontColorBrush, oPoint)
oBitmap.Save(Response.OutputStream, oInfo(1), oEncoderParams)
Response.Output.Write(oBitmap)
oBitmap.Dispose()
oGraphic.Dispose()
Response.Flush()
Catch ex As Exception
End Try
End Sub
</code></pre>
<p><hr /></p>
<p>So armed with this information, I want to know if it is possible for the AsyncPostBack refresh the CSS so that the image will change when I click Button2. I am open for suggestions and/or "thats the stupid/hard way to do this, try this..." type of feedback.</p>
<p>Thanks guys!</p>
| <p>Since you said you're open to suggestions... why are you set on doing this with the AsyncPostBack and CSS? Why not just have a javascript onclick event to dynamically change the image when you click Button2?</p>
<p>edit (in response to post below):</p>
<p>There would be no post back (if that's what you mean by flickering): you can still use the AsyncPostBack for whatever else you're doing, and then have an additional javascript function fired off onclick that would do something like</p>
<pre><code>document.getElementById('headerimg').src='2.jpg';
</code></pre>
<p>This would change the image to new source file without any page refresh.</p>
|
MySQL: SELECT from another server <p>I'm afraid that I already know the answer to my question, but I'll ask it anyway:</p>
<p>When there are two MySQL DB servers, can I access data that is stored on the other server? </p>
<p>In other words: Can I somehow do this:</p>
<pre><code>INSERT INTO table (x, y, z)
SELECT x, y, x+y
FROM [otherserver].[database].[table]
</code></pre>
<p>Is the answer really as short as "No"?</p>
| <p>You can set up federated tables in MySQL to accomplish what you're trying to do. There are some limitations.</p>
<p><a href="http://dev.mysql.com/doc/refman/en/federated-storage-engine.html" rel="nofollow">http://dev.mysql.com/doc/refman/en/federated-storage-engine.html</a>
<a href="http://dev.mysql.com/doc/refman/en/federated-usagenotes.html" rel="nofollow">http://dev.mysql.com/doc/refman/en/federated-usagenotes.html</a></p>
|
What is the shortest way to implement a proxy or decorator class in c#? <p>When you have a class car that implements IVehicle and you want to wrap it in a decorator that forwards all calls to car and counts them, how would you do it?</p>
<p>In Ruby I could just build a decorator without any methods and use method_missing to forward all calls to the car object.</p>
<p>In Java I could build a Proxy object that runs all code through one method and forwards it afterwards.</p>
<p>Is there any similiar thing i can do in C#?</p>
<p><hr /></p>
<p>update:</p>
<p>based on the answeres and what i´ve read about System.Reflection.Emit it should be possible to write a method similiar to this:</p>
<pre><code>Type proxyBuilder(Type someType, delagate functionToBeApplied, Object forward)
</code></pre>
<p>where type implements all interface of someType, executes functionToBeApplied and then forwards the method call to object while returning its return.</p>
<p>Is there some lib that does just that or would i have to write my own?</p>
| <p>For proxying you could look into "RealProxy" if you want to use standard types, it's a little bit of a hassle to use though (and it requires your classes inherit from MarshalByRefObject).</p>
<pre><code>public class TestProxy<T> : RealProxy where T : class
{
public T Instance { get { return (T)GetTransparentProxy(); } }
private readonly MarshalByRefObject refObject;
private readonly string uri;
public TestProxy() : base(typeof(T))
{
refObject = (MarshalByRefObject)Activator.CreateInstance(typeof(T));
var objRef = RemotingServices.Marshal(refObject);
uri = objRef.URI;
}
// You can find more info on what can be done in here off MSDN.
public override IMessage Invoke(IMessage message)
{
Console.WriteLine("Invoke!");
message.Properties["__Uri"] = uri;
return ChannelServices.SyncDispatchMessage(message);
}
}
</code></pre>
<p>Alternatively you could get "DynamicProxy" from Castle.. It works a bit better in my experience..</p>
<p>If you use one of those you won't neccessarily get great performance though, I use them primarily in calls that will likely be slow in the first place.. But you could try it out if you want.</p>
<p>Marc's solution will have better performance.</p>
|
ASP.NET MVC RC ajax onsubmit <p>The problem with onsubmit still continues when I even use preventDefault option. My problem is the same with <a href="http://stackoverflow.com/questions/237691/aspnet-mvc-beta-ajax-upgrade-problem">Asp.net mvc beta ajax problem</a></p>
<pre><code><% using (this.Ajax.BeginForm("den2",
"Deneme",
null,
new AjaxOptions {
UpdateTargetId = "panel1",
InsertionMode=InsertionMode.Replace
},
new { id = "panelOneForm" })) { } %>
<div class="panel" id="panel1">
<img src="/Content/ajax-loader.gif" />
</div>
<script type="text/javascript">
$get("panelOneForm").onsubmit({ preventDefault: function() { } });
</script>
</code></pre>
<p>This time I get the following error:</p>
<pre><code>e.type is undefined
var etype = this.type = e.type.toLowerCase();
</code></pre>
<p>When I debug it :</p>
<pre><code> var e = Function._validateParams(arguments, [
{name: "eventObject"} ]);
if (e) throw e;
var e = eventObject;
var etype = this.type = e.type.toLowerCase();
this.rawEvent = e;
...(function continues) at MicrosoftAjax.debug.js line 2862
</code></pre>
<p>Is there a way to solve it or should I pass each parameter property used in this method?</p>
<p>Thanks</p>
| <p>After some research, I found that was an issue with the RC version of MicrosoftAjax.js</p>
<p>It works fine if I use an older version of this file. Not a solution, but it will help temporarly.</p>
|
Delphi 2009 classes / components to read/write file permissions <p>Does anyone have a set of classes / components that will work with Delphi 2009 (Unicode) to read and write NTFS file permissions?</p>
<p>There was a thing called "NTSet" - but they stopped development at Delphi 2006 about 3 years ago :-(</p>
<p>Any other takers??</p>
<p>Thanks!
Marc</p>
| <p><a href="http://sourceforge.net/projects/jcl/" rel="nofollow">JCL</a> has units to deal with file permissions, and they claim D2009 compatibility.</p>
|
C# Large Tree Iteration <p>I have a large result set assembled in a parent/child relationship. I need to walk the tree and display the results to the user. </p>
<p>I've done this before using recursion, but because my result set may be large, I want to avoid the possibility of receiving a StackOverflowException.</p>
<p>I found the following <a href="http://msdn.microsoft.com/en-us/library/bb513869.aspx" rel="nofollow">example</a> on MSDN which uses a Stack. The problem I'm having is because a stack is last-in first-out, my data doesn't appear properly. I'd like it to look like the following:</p>
<pre><code>
LeveL 1
Level 1.1
Level 1.1.1
Level 1.1.2
Level 1.2
Level 1.2.1
Level 1.2.2
</code></pre>
<p>But it looks like:</p>
<pre><code>
LeveL 1
Level 1.2
Level 1.2.2
Level 1.2.1
Level 1.1
Level 1.1.2
Level 1.1.1
</code></pre>
<p>Any ideas?</p>
<p>Here is an example of my code. Assuming the <code>DataTable dt</code> has the following columns: ID, ParentID, and Text</p>
<pre><code> private struct Item
{
public string Text;
public int ID;
public int ParentID;
}
private void BuildView()
{
Stack<Item> itemTree = new Stack<Item>(40);
//Get All Parent Nodes
DataView dv = new DataView(dt);
dv.RowFilter = "ParentID = 0";
//Add the parent nodes to the stack
foreach (DataRowView drv in dv)
{
Item item = new Item();
item.Text = drv["Text"].ToString();
item.ID = drv["ID"].ToString();
item.ParentID = drv["ParentID"].ToString();
itemTree.Push(item);
}
//Go through the stack one node at a time
while (itemTree.Count > 0)
{
Item currentItem = itemTree.Pop();
Debug.WriteLine(currentItem.Text);
//Get children of current node
dv.RowFilter = String.Format("ParentID = {0}", currentItem.ID);
if (dv.Count > 0)
{
//Add child nodes to the stack
foreach (DataRowView drvChild in dv)
{
Item item = new Item();
item.Text = drvChild["Text"].ToString();
item.ID = drvChild["ID"].ToString();
item.ParentID = drvChild["ParentID"].ToString();
itemTree.Push(item);
}
}
}
}
</code></pre>
| <p>In the current algorithm you are going for the right child first.</p>
<p>Make it left child first. Thats all.</p>
<p>For example, in your code there may be something like:</p>
<pre><code>node = node.rightChild()
</code></pre>
<p>Change it to</p>
<pre><code>node = node.leftChild()
</code></pre>
<p>This is the general solution for this kind of issues.</p>
<p>Since the MSDN implementation does not expose this kind of code, I cannot comment on that.</p>
|
quaternion libraries in C/C++ <p>Any good libraries for <em>quaternion</em> calculations in C/C++ ? </p>
<p>Side note: any good tutorials/examples? I've google it and been to the first few pages but maybe you have have some demos/labs from compsci or math courses you could/would share? </p>
<p>Thanks</p>
| <p>I'm a fan of the Irrlicht quaternion class. It is zlib licensed and is fairly easy to extract from Irrlicht:</p>
<ul>
<li><a href="http://irrlicht.sourceforge.net/docu/classirr_1_1core_1_1quaternion.html">Irrlicht Quaternion Documentation</a></li>
<li><a href="https://irrlicht.svn.sourceforge.net/svnroot/irrlicht/trunk/include/quaternion.h">quaternion.h</a></li>
</ul>
|
Create XML Nodes based on XPath? <p>Does anyone know of an existing means of creating an XML hierarchy programatically from an XPath expression? </p>
<p>For example if I have an XML fragment such as:</p>
<pre><code><feed>
<entry>
<data></data>
<content></content>
</entry>
</feed>
</code></pre>
<p>Given the XPath expression /feed/entry/content/@source I would have:</p>
<pre><code><feed>
<entry>
<data></data>
<content @source=""></content>
</entry>
</feed>
</code></pre>
<p>I realize this is possible using XSLT but due to the dynamic nature of what I'm trying to accomplish a fixed transformation won't work.</p>
<p>I am working in C# but if someone has a solution using some other language please chime in.</p>
<p>Thanks for the help!</p>
| <p>In the example you present the only thing being created is the attribute ... </p>
<pre><code>XmlElement element = (XmlElement)doc.SelectSingleNode("/feed/entry/content");
if (element != null)
element.SetAttribute("source", "");
</code></pre>
<p>If what you really want is to be able to create the hierarchy where it doesn't exist then you could your own simple xpath parser. I don't know about keeping the attribute in the xpath though. I'd rather cast the node as an element and tack on a .SetAttribute as I've done here:</p>
<pre><code>
static private XmlNode makeXPath(XmlDocument doc, string xpath)
{
return makeXPath(doc, doc as XmlNode, xpath);
}
static private XmlNode makeXPath(XmlDocument doc, XmlNode parent, string xpath)
{
// grab the next node name in the xpath; or return parent if empty
string[] partsOfXPath = xpath.Trim('/').Split('/');
string nextNodeInXPath = partsOfXPath.First();
if (string.IsNullOrEmpty(nextNodeInXPath))
return parent;
// get or create the node from the name
XmlNode node = parent.SelectSingleNode(nextNodeInXPath);
if (node == null)
node = parent.AppendChild(doc.CreateElement(nextNodeInXPath));
// rejoin the remainder of the array as an xpath expression and recurse
string rest = String.Join("/", partsOfXPath.Skip(1).ToArray());
return makeXPath(doc, node, rest);
}
static void Main(string[] args)
{
XmlDocument doc = new XmlDocument();
doc.LoadXml("<feed />");
makeXPath(doc, "/feed/entry/data");
XmlElement contentElement = (XmlElement)makeXPath(doc, "/feed/entry/content");
contentElement.SetAttribute("source", "");
Console.WriteLine(doc.OuterXml);
}
</code></pre>
|
Callback and asp.net gridview <p>I have a following situation. I have a gridview and I need to dynamically add rows to it. All works fine and dandy. However, lately, I have been curious about making this process faster and more usable. I found a Callback feature in asp.net 2.0.</p>
<p>It seems to make sense for a case when the gridview is used ti display something. Adding a row programmatically however, requires to add a row to DataTable (that's gridview bound to). Since DataTable resides on the server, from what I understand it doesn't make sense here to use Callback....</p>
<p><a href="http://csharpfeeds.com/post/4287/Asynchronous_GridView_in_5_simple_steps.aspx" rel="nofollow">this</a> is a nice tutorial that outlines main things.</p>
<p>in step 5:</p>
<p>"To finish the asynchronous loading we have to implement the two methods that are defined by the ICallbackEventHandler interface we implemented in step 3. One of the methods binds a DataTable to the GridView and renders the control."</p>
<p>from that I gather that there is no way to make dynamically adding rows to gridview w/o postbacks....any thoughts?</p>
| <p>That's correct -- you can't dynamically add rows to a GridView without a postback. You can add rows to the html on the client side, but they won't be recognized after the next postback.</p>
<p>I generally do what you're describing with just a plain HTML table on the client side using jQuery, and making jQuery ajax calls where it's appropriate.</p>
|
Converting strings to enum in C++? <p><a href="http://stackoverflow.com/questions/16100/converting-a-string-to-an-enumeration-value-in-c">Strings to enum in C#</a>, how do you normally converting strings to enum in C++. Any helper function that you use, is it a good idea to do this.</p>
| <p>I reviewed this approach awhile ago - available via <a href="http://www.codeproject.com/KB/cpp/EnumBinder.aspx" rel="nofollow">Code Project</a></p>
|
Getting started in Unit Testing as a group in these economic times <p>We have a group of a few developers and some business analysts. We as developers would like to start adding unit testing as part of our coding practices so that we can deliver maintainable and extensible code, especially since we will also be the ones supporting and enhancing the application in the future. But in this economic downturn we are struggling with the push to get started because we are challenged to just deliver solutions as fast as possible, with quality not being the top priority. What can we do or say to show that we will be able to deliver faster and with higher quality, as well as preparing for future enhancements.</p>
<p>Basically we just need to get over the learning curve of incorporating unit testing into our daily work, but we cannot do that now because it is viewed as an unnecessary overhead that would delay our projects that the business needs now.</p>
<p>We as developers want to provide the highest value to the business, especially quickly, but we know that we will also need to do this 6 months from now and we need to plan for that as well, and we believe that unit testing will help us greatly down the line.</p>
<p><strong>EDIT</strong>
All awesome input, thank you. I personally know how to write unit test, but I don't have the experience in me to say whether or not that unit test is good. I have just ordered <a href="http://rads.stackoverflow.com/amzn/click/0321146530" rel="nofollow">Test Driven Development: By Example</a> and will take the initiative to get the ball rolling on incorporating unit testing in our group.</p>
| <p>You need to just start doing it, with or without permission. In the end it will make you more productive and increase your code quality. You can start small by including units for something critical and once you've shown the benefits, you're in.</p>
|
Open a file and write contents to a DIV, span, label, some kind of container <p>Iâd like to be able to open a text/html file and write its contents to a container, either an HTML div or an asp label would be fine.
How do I go about doing this in the C# codefile for the page in question?</p>
| <p>You just want to stream in the file and place the text into the Label.text field:</p>
<pre><code>lable1.text= System.IO.File.ReadAllText( path );
</code></pre>
|
How do you manage your time as a team leader? <p>Where I work, my role has been evolving from a pure development role to team leadership. I find that this suits me, and I'm generally enjoying it.</p>
<p>One aspect of the job that continually vexes me, though, is time management. My day used to be pure coding. Now, I still have a largely full plate of coding duties, but I'm expected to mentor other developers, work on requirements, make design decisions for other developers, evaluate bug reports from users, assign them to developers, and so on.</p>
<p>I find that my day has become one interruption after another and the prolonged periods of sustained concentration needed to get any actual quality coding done are becoming rarer and rarer. </p>
<p>Today, I finally grabbed my laptop and escaped to a coffee shop so I could get some actual work done. </p>
<p>How do the team leads here manage their day -- or manage their workplace -- so they don't let their administrative tasks overwhelm them?</p>
| <p>I've found that I have to change my perspective on what my job is.</p>
<p>As an individually-contributing developer, my job was to turn my own time in to software that the business could sell for a profit.</p>
<p>As a team lead, my job is to see that <em>the team</em> effectively turns their time in to software that the business could sell for a profit.</p>
<p>Some things fundamentally change when your perspective changes like that. These things have become much more important:</p>
<ul>
<li>Keeping other members of the team in a state that they can be productive</li>
<li>Delegating tasks to the least loaded team member</li>
<li>Strategically choosing which developer needs to learn which new skill to better load-balance the team, and investing some degree of my time in helping them learn that skill</li>
<li>Effectively communicating requirements</li>
</ul>
<p>Notice that "writing good code myself" is no longer on my list of top concerns. If the task of "develop this major new thing" falls on me, it's almost always for one of a few reasons:</p>
<ul>
<li>The new thing is a framework item that will enable the rest of the team to be more productive (thus keeping them in a productive state)</li>
<li>The thing I'm working on is super-critical for customer satisfaction (usually that means it has to be done quickly and with little risk of failure)</li>
<li>The thing I'm working on has poorly-understood requirements, requiring someone with a high degree of domain knowledge to make quality requirement decisions while simultaneously doing development (one could argue that in this case, my inability to adequately form the requirements is the real shortcoming.)</li>
<li>I haven't done the other jobs well (delegating, improving skillsets, or communicating)</li>
</ul>
<p>In the case of #2 above, it might very well be worth sequestering myself from the team to get the job done - but you have to keep in mind that doing that will hurt your primary goal: helping the team most efficiently and effectively turn your collective time in to software that the business can sell for a profit.</p>
|
Java equivalent of unsigned long long? <p>In C++, I enjoyed having access to a 64 bit unsigned integer, via <code>unsigned long long int</code>, or via <code>uint64_t</code>. Now, in Java longs are 64 bits, I know. However, they are signed.</p>
<p>Is there an unsigned long (long) available as a Java primitive? How do I use it?</p>
| <p>Starting Java 8, there is support for unsigned long (unsigned 64 bits). The way you can use it is:</p>
<pre><code>Long l1 = Long.parseUnsignedLong("17916881237904312345");
</code></pre>
<p>To print it, you can not simply print l1, but you have to first:</p>
<pre><code>String l1Str = Long.toUnsignedString(l1)
</code></pre>
<p>Then</p>
<pre><code>System.out.println(l1Str);
</code></pre>
|
Custom authentication at the URL level, use ISAPI still with .NET or is there a new way? <p>Is there a non-IIS way of authenticating users that is not with HTML?</p>
<p>I know I can create my own ISAPI filter for IIS, but I want to achieve the same thing, with .NET code and not integrate it with IIS.</p>
<p>Is there a way to do this now, with the latest .NET, or is ISAPI still the way to go?</p>
| <p>If you want to apply your custom authentication for all contents, an ISAPI extension is required for IIS 5/6/7.</p>
<p>Greg's way only works for ASP.NET content on IIS 5/6. However, if you understand the Integrated Pipeline feature of IIS 7 well, you can configure an ASP.NET HTTP module like Greg's to apply to all contents.</p>
<p>MSDN and IIS.net can provide me more details if you do a search further.</p>
|
MS CRM Custom Workflow to access Project Server web service <p>I am trying to create a custom workflow in ms crm 4 so that when a task is completed it will take some of the attributes of the task and add an entry in project server on a timesheet. I am able to access the project server web services (PSI) and create a time sheet entry from a c# console app and I can do other custom workflows in crm not related to project server. When using the Project Server web services (PSI) I have to reference and include 3 office project dll's but I am unsure how to get those registered in CRM when i do the custom workflow plugin registration. Any thoughts would be helpful.</p>
<p>Thanks</p>
| <p>In my experience, you're either going to have to deploy those DLL's to the Server\bin directory or merge them with your DLL using something like ILMerge and register it all as one big chunk.</p>
|
How to skip some section of text while speaking using SSML <p>Is there some SSML tags etc, to remove a particular line of text from speaking. Yes, I know I can remove this using string functions, before sending it to the speech synthesizer. But my question is, is there any way to mark or tag some text, so that it won't play. I am looking for some XML based solution for this issue.</p>
| <p>There are so many ways, you should clarify what you want to accomplish.</p>
<p>Maybe one of these will help you:</p>
<pre><code> 1. standard XML comment <!-- -->
2. <sub alias=" "> your text </sub>
3. <audio src='short_silence.wav'> your text </audio>
4. <prosody volume='silent'> your text </prosody>
</code></pre>
|
Virtual COM Ports in Windows - Fax emulator <p>I have a Windows application that utilizes a 3rd-party tool (<a href="http://data-tech.com/products/fax.aspx" rel="nofollow">FaxMan</a>) to send faxes via a COM port attached to the PC. In order to stress test my application I want to create some virtual COM ports that pretend to have fax modems attached. I then want to 'spoof' the sending of faxes, without physically sending anything. The virtual COM ports would need to respond to standard AT commands as if the fax was being sent. The ability to spoof failures would be an added bonus.</p>
<p>My first thoughts are using a virtual COM port driver to redirect to a telnet or other TCP session - I could then have a TCP server that pretends to go through the fax motions. However, I am happy to pay for a component if one exists.</p>
| <p>I worked on this problem for several years, developing a LAN fax product. I doubt you can do it well.</p>
<p>Developing a virtual COM driver means developing a kernel driver (unless you can buy one off the shelf): which is doable (I did it) but I'd guess it's far more trouble than it's worth (I'd be surprised if it's worth your while).</p>
<p>Another problem is that there are a variety of fax modems and fax modem standards (and you say you're hoping to emulate one well enough to fool FaxMan).</p>
<p>Another (essential) problem is that the simpler (non-error-correcting) fax protocols are a (hard) <strong>real-time</strong> protocol: there is some (more or less) buffering on the fax modem, but the PC attached to the fax modem cannot to afford to underrun when sending or to overrun when receiving ... which means that redirecting this traffic via telnet (with the TCP timers and buffers) either breaks the fax session at worst (FaxMan will time out) or at best mean that your testing isn't representative of what the real-world (non-emulated) performance will be.</p>
<p>What are you trying to stress-test anyway: your application, or the third-party FaxMan?</p>
<p>I suggest that the cheapest solution and the most realistic test would be using real hardware: real COM ports, real fax modems, and real (or, possibly, simulated) telephone lines.</p>
<hr>
<p><strong>Edit to answer the questions from the comments in Michael's answer</strong></p>
<blockquote>
<p>Assuming that the transport of the data is a small problem (e.g. because you can simply connect two serial ports back to back), is writing software which emulates a fax modem a small problem?</p>
</blockquote>
<p>It might be small: if your load test is merely "send fax data to the bit bucket" then your emulated modem mostly just needs to respond "OK" to every/anything that looks like an AT command, plus various other responses to the various fax-specific AT+F_whatever_ commands. But that's a pretty low-fidelity, not a very stringent, test.</p>
<blockquote>
<p>That would be pretty simple - but isn't there some protocol involved in the FAX data transmission? Or is the protocol just a variant of the AT command set, and spoofing an "OK" is all there is to it? I honestly don't know, but I assumed there would be a somewhat more complex protocol.</p>
</blockquote>
<p>The telephony protocols have names like "T.4" and "T.30". The PC-to-faxmodem protocol is usually a protocol called "class 1 fax" or "class 2 fax". The latter ("class 2" or "class 2.0") is the higher-level of the two: more ASCII and less binary data, not so timing-sensitive (class 1 is sensitive to 10s of msec iirc), because it encapsulates/wraps more of the underlying T.30 negotiation than class 1 does; it consists of extended AT commands (i.e. AT+F_something_ commands, and their responses) plus a dump of the binary-encoded fax image data.</p>
<p>Some of the responses are more than just "OK" (i.e. they represent the available/negotiated fax session parameters) but (in class 2 rather than class 1) they're ASCII-encoded rather than binary, so not too difficult really at all.</p>
<blockquote>
<p>There has to be some sort of handshaking, right? Otherwise a plain, old FAX machine would likely lose a bunch of data when it was loading a new page.</p>
</blockquote>
<p>Yes there's some handshaking ("May I send now?") <em>between</em> pages (i.e. before each page). A load-testing emulation which isn't testing the timing would just respond "yeah, go ahead (I'm only going to be dumping the data into the bit bucket anyway without even looking at it, so what do I care)" to the handshake enquiry.</p>
<p>The emulation would also have to watch the binary image data (which it's getting from the PC) for <code><DLE><ETX></code> and <code><DLE><DLE></code>, in order to respond OK at the end of the PC-dumps-image-data-to-the-modem.</p>
<p>I don't know what timers might be built into the FaxMan application (whether or not you might need to add artifical delays to your emulated responses, to prevent FaxMan's realising that the responses are abnormally quick): maybe not, but maybe.</p>
<p>There may or may not be any hand-shaking within the page:</p>
<ul>
<li>With older fax machines/fax protocols, there isn't: instead the devices negotiate 'fax session parameters', including the baud rate, before the page: they negotiate a synchronous baud rate which both ends are able to support. That (ability to handle a whole page-worth of data, synchronously) is part of why it's a hard-real-time protocol.</li>
<li>Newer fax machines / fax protocols support 'error correction' within each page: the page is sent in smaller (but still synchrnonous) chunks: and each chunk acknowledged, or NAKed and retransmitted.</li>
</ul>
|
How to bind nested objects, or master-detail-binding, in code? <p>I have a three nested classes, Show, Season and Episode, where a show has seasons, and seasons has episodes. </p>
<p>I want to bind two listboxes so that the first lists seasons, and the second lists episodes in that season.</p>
<p>How can I do this? I prefer to set this up in code, not xaml, but if you know how to do it with xaml, it's better than nothing..</p>
<p>A simplifyed xaml:</p>
<pre><code><Window>
<Label name="Showname" />
<ListBox name="Seasons" />
<ListBox name="Episodes" />
</Window>
</code></pre>
<p>and some relevant code:</p>
<pre><code>public partial class Window1 : Window
{
public Data.Show show { get; set; }
public Window1()
{
this.DataContex = show;
//Bind shows name to label
Binding bindName = new Binding("Name");
ShowName.SetBinding(Label.ContentProperty, bindName);
//Bind shows seasons to first listbox
Binding bindSeasons = new Binding("Seasons");
Seasons.SetBinding(ListBox.ItemsSourceProperty, bindSeasons);
Seasons.DisplayMemberPath = "SeasonNumber";
Seasons.IsSyncronizedWithCurrentItem = true;
//Bind current seasons episodes to second listbox
Binding bindEpisodes = new Binding("?????");
Episodes.SetBinding(ListBox.ItemsSourceProperty, bindEpisodes);
Episodes.DisplayMemberPath = "EpisodeTitle";
}
}
</code></pre>
<p>Anyone got any clues how to bind up the second listbox?</p>
| <p>Edit: adding a bit more details.</p>
<p>Ok, so let's say you have a Show object. This has a collection of Seasons. Each Season has a collection of Episodes. You can then have the DataContext for the entire control be the Show object.</p>
<ul>
<li>Bind your TextBlock to the show's Name. Text="{Binding Name"}</li>
<li>Bind the ItemsSource of the seasons
list box to the Seasons collection.
ItemsSource="{Binding Seasons}"
IsSynchronizedWithCurrentItem="True"</li>
<li>Bind the ItemsSource of the episodes
list box to the current Season's
Episodes collection.
ItemsSource="{Binding
Seasons/Episodes}".</li>
</ul>
<p>Assuming your Window's DataContext is the Show object, the XAML would be:</p>
<pre><code><Window>
<TextBlock Text="{Binding Name}" />
<ListBox ItemsSource="{Binding Seasons}" IsSynchronizedWithCurrentItem="True" />
<ListBox ItemsSource="{Binding Seasons/Episodes}" />
</Window>
</code></pre>
<p>So your UI elements don't really need names. Also, to translate this into code is pretty easy and you were on the right path. The main issue with your code was that you were naming the list boxes, when they don't really need it.</p>
<p>Assuming the Season object has a property called Episodes, which is a collection of Episode objects, I think it is:</p>
<pre><code> Binding bindEpisodes = new Binding("Seasons/Episodes");
</code></pre>
|
Add authentication to subfolders without creating a web application <p>We have an existing publicly accessible web application with user controls, data access libraries, graphics, etc. We want to create a new secure section of the site that accesses some of the already existing resources.</p>
<p>Initially we created the new section of the site as a virtual directory which (we hoped) would allow us to access the parent site's resources. We added the appropriate location information to the base web.config (authentication and authorization) but we continue to see the following error "Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS."</p>
<p>In response to that error we created the directory as a new application. This allows us to authenticate properly but has the drawback of not being able to access any of the resources in the parent directory (since it's outside the application scope).</p>
<p>Is there any way to secure the new section of the site while at the same time utilize the already existing resources?</p>
| <p>In your web.config file in the root of your site, if you add:</p>
<pre><code><location path="relativePathToDir">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
</code></pre>
<p>This is working for me using FormsAuthentication, the user gets redirected to the default login page if not authenticated</p>
|
What is a good pattern for inexact queries in the Google App Engine Datastore? <p>The Google App Engine Datastore querying language (gql) does not offer inexact operators like "LIKE" or even case insensitivity. One can get around the case sensitive issue by storing a lower-case version of a field. But what if I want to search for a person but I'm not sure of the spelling of the name? Is there an accepted pattern for dealing with this scenario?</p>
| <p>Quoting from the documentation:</p>
<p>Tip: Query filters do not have an explicit way to match just part of a string value, but you can fake a prefix match using inequality filters:</p>
<pre><code>db.GqlQuery("SELECT * FROM MyModel WHERE prop >= :1 AND prop < :2", "abc", u"abc" + u"\ufffd")
</code></pre>
<p>This matches every MyModel entity with a string property prop that begins with the characters abc. The unicode string u"\ufffd" represents the largest possible Unicode character. When the property values are sorted in an index, the values that fall in this range are all of the values that begin with the given prefix.</p>
<p><a href="http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html">http://code.google.com/appengine/docs/python/datastore/queriesandindexes.html</a></p>
<p>Another option is the SearchableModel, however, i dont believe it supports partial matches.</p>
<p><a href="http://billkatz.com/2008/8/A-SearchableModel-for-App-Engine">http://billkatz.com/2008/8/A-SearchableModel-for-App-Engine</a></p>
|
How to clear file path history from the file explorer? <p>Under Microsoft Vista, the windows file explorer keeps paths and occasionally files in its history. This history can be seen by selecting the pull-down from the box at the top that keeps lists the current directory. I'd like to clear out that list, but I don't see an easy way to do it.</p>
<p>To clarify, I am talking about the file explorer (explorer.exe), not Internet Explorer (iexplorer.exe).</p>
| <p>Well, even though you say you mean the file explorer and not internet explorer, you are almost on the right track there. If you delete your internet explorer history, it will also delete the file history in the explorer. </p>
<p>Bart</p>
|
WCF Self-hosted service, client clean-up on service stop <p>I'm curious to know how I would go about setting up my service to stop cleanly on the server the service will be installed on. For example when I have many clients connecting and doing operations every minute and I want to shut-down the service for maintenance, how can I do this in the "OnStop" event of the service to then let the main service host to deny any new client connections and let the current connections finish before it actually shuts down its services to the client, this will ensure data isn't corrupted on the server as the server shuts down.</p>
<p>Right now I'm not setup as a singleton because I need scalability in the service. So I would have to somehow get my service host to do this independently of knowing how many instances are created of the service class.</p>
| <p>You just have to call Dispose on the ServiceHost instance that you create. Once you do that, you will not accept any more clients and the service will continue to finish the operations for clients that are already connected.</p>
|
Clojure read-line function problem <p>I'm trying to get console input in my Clojure program, but when it gives me this error when it gets to that part of the program.</p>
<pre><code>Exception in thread "main" java.lang.ClassCastException:
clojure.lang.LineNumberingPushbackReader cannot be cast to java.io.BufferedReader
</code></pre>
<p>the 'read' function works, but it's not what I need. Here is the code I'm using.</p>
<pre><code>(defn prompt-read [prompt]
(print (format "%s: " prompt))
(flush )
(read-line))
</code></pre>
<p>EDIT:</p>
<p>It is obviously just the version I'm using. It's the version included in the current sample code of Programming Clojure, I'll test out the current release version and see if that is the problem.</p>
| <p>Hmm, it seems to work for me. What version of Clojure are you using and how are you calling prompt-read? Here's what I'm getting back (here <code>goo</code> is my response):</p>
<pre><code>user=> (defn prompt-read [prompt]
(print (format "%s: " prompt))
(flush )
(read-line))
#'user/prompt-read
user=> (prompt-read "foo")
foo: goo
"goo"
</code></pre>
|
How do you draw like a Crayon? <p><a href="http://www.crayonphysics.com/">Crayon Physics Deluxe</a> is a commercial game that came out recently. Watch the video on the main link to get an idea of what I'm talking about.</p>
<p>It allows you to draw shapes and have them react with proper physics. The goal is to move a ball to a star across the screen using contraptions and shapes you build.</p>
<p>While the game is basically a wrapper for the popular <a href="http://www.box2d.org/">Box2D Physics Engine</a>, it does have one feature that I'm curious about how it is implemented.</p>
<p>Its drawing looks <em>very</em> much like a Crayon. You can see the texture of the crayon and as it draws it varies in thickness and darkness just like an actual crayon drawing would look like.</p>
<p><img src="http://www.kloonigames.com/crayon/screenshots/crayon_small_01.jpg" alt="alt text"> <img src="http://www.kloonigames.com/crayon/screenshots/crayon_small_02.jpg" alt="alt text"></p>
<p>The background texture is freely available <a href="http://flickr.com/photos/felipeskroski/325477721/">here</a>.</p>
<p><img src="http://img267.imageshack.us/img267/1488/crayonmh7.png" alt="alt text"><br>
<em>Close up of crayon drawing - Note the varying darkness</em></p>
<p>What kind of algorithm would be used to render those lines in a way that looks like a Crayon? Is it a simple texture applied with a random thickness and darkness or is there something more going on?</p>
| <p>I remember reading (a long time ago) a short description of an algorithm to do so:</p>
<ul>
<li><p>for the general form of the line, you split the segment in two at a random point, and move this point slightly away from it's position (the variation depending on the distance of the point to the extremity). Repeat recursively/randomly. <strong>In this way, you lines are not "perfect" (straight line)</strong></p></li>
<li><p>for a given segment you can "overshoot" a little bit, by extending one extremity or the other (or both). <strong>In this way, you don't have perfect joints</strong>. If i remember well, the best was to extends the original extremities, but you can do this for the sub-segment if you want to visibly split them.</p></li>
<li><p>draw the lines with pattern/stamp</p></li>
<li><p>there was also the (already mentioned) possibility to drawn with different starting and ending opacity (to mimic the tendency to release the pen at the end of drawing)</p></li>
<li><p>You can use a different size for the stamp on the beginning and the end of the line (also to mimic the tendency to release the pen at the end of drawing). For the same effect, you can also draw the line twice, with a small variation for one of the extremity (be careful with the alpha in this case, as the line will be drawn twice)</p></li>
<li><p>Last, for a given line, you can do the previous modifications several times (ie draw the line twice, with different variations) : human tend to repeat a line if they make some mistakes.</p></li>
</ul>
<p>Regards</p>
|
ASP.NET: Password Recovery link on a LogIn control requires a user to login <p>I'm trying to test this out on my site but it doesn't quite work because I have to be logged in to go to this page.</p>
<p>Is there a configuration setting that I haven't set or set incorrectly? </p>
<p>EDIT: rm's answer led me to this <a href="http://msdn.microsoft.com/en-us/library/ms178335.aspx" rel="nofollow">link from Microsoft</a>.</p>
| <p>adding to Arjan's answer, the settings for page permissions are in your web.config file.</p>
<p>you should do something like this:</p>
<pre><code><configuration>
<location path="YourPage.aspx">
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>
</code></pre>
|
How do I change the description of input's displayed for an operation defined using a MXBean <p>I'm using a MXBean to instrument a certain feature, and I have a method that takes in 3 input arguments.</p>
<p>By default, on the jconsole, the arguments are displayed as p1, p2, p3 etc. I have @params describing each parameter. How do I make jConsole use those?</p>
<pre><code>public class Sample implements SampleMXBean {
/**
* method 1
*
* @param input1 Input One
* @param input2 Input Two
*/
public void getInput(int input1, int input2) {
...
...
}
}
</code></pre>
<p>I have registered the above MXBean , and when I launch, the panel for this operation, I get a button with "getInput" as the text, and 2 text boxes with names as p1 and p2, instead of "Input One" and "Input Two".</p>
<p>Are there any annotations that I need to use to achieve this?
(Btw I'm using jdk1.6)</p>
| <p>Are you using Spring? They have a <a href="http://static.springframework.org/spring/docs/2.5.x/reference/jmx.html" rel="nofollow">module</a> that does what you're describing with <em>@ManagedOperation</em> and <em>ManagedOperationParameter</em> annotations. Otherwise, you're on your own to create the appropriate <em>javax.management.modelmbean.ModelMBeanOperationInfo</em> class when you're registering your object in JMX.</p>
<p><a href="http://tech.puredanger.com/java7/#jsr255" rel="nofollow">JSR-255</a> might address this in the future though. See <a href="http://weblogs.java.net/blog/emcmanus/archive/2007/08/defining_mbeans.html" rel="nofollow">this blog post</a></p>
|
Can I use a CSV file like a (MSsql or mysql or BDE database) in C++ Builder? <p>I apologise in advance if this question isn't very specific.</p>
<p>Would it be possible to do the following.</p>
<p><strong>when the application loads</strong></p>
<p>read the contents of a CSV file into a dataset. </p>
<p><strong>while the application is running</strong></p>
<p>operate on that dataset exactly as if it were a mysql or mssql or bde database (run queries. insert records. delete records. alter records.)</p>
<p><strong>when the application closes</strong> - write the dataset back to the csv file.</p>
| <p>You could load the file into a TClientDataset, operate on the dataset and apply the changes back to a file.</p>
|
Multi-line PL/SQL command with .NET OracleCommand <p>I'm using System.Data.OracleClient.OracleCommand to create a table and fill it out with some data. The query I am using runs OK in PS/SQL Developer, however when I'm trying to execute it from within .NET application I'm getting this error:</p>
<pre><code>ORA-06550: line 1, column 20:
PLS-00103: Encountered the symbol "" when expecting one of the following:
begin function package pragma procedure subtype type use
<an identifier> <a double-quoted delimited-identifier> form
current cursor
</code></pre>
<p>Column 20 is exactly where first line ends. As soon as I remove line end characters (\r\n) from the command it all starts working.</p>
<p>I wonder is there some hidden configuration parameter to enable multi-line queries for Oracle? </p>
<p>Here is some code:</p>
<pre><code> var text = @"declare cnt number;
begin
select count(*) into cnt from all_tables
where table_name = 'TABLE_A';
if cnt = 1 then
begin
execute immediate 'truncate table TABLE_A';
execute immediate 'drop table TABLE_A';
end;
end if;
execute immediate 'create table TABLE_A as
(SELECT DISTINCT v.ID, g.ext_id FROM VIEW_A v
JOIN TABLE_B B ON v.id = B.Id
WHERE YEAR1 = ''2008'')';
end;");
var createTempTable = new OracleCommand(text, conn);
createTempTable.CommandType = CommandType.Text;
conn.Open();
try
{
createTempTable.ExecuteNonQuery();
}
catch(Exception ex)
{
throw;
}
finally
{
conn.Close();
}
</code></pre>
<p>Thanks for your help</p>
| <p>I think you need to lose just the '\r' characters.</p>
|
Help me understand this UI jargon <p>From an <a href="http://www.flashmagazine.com/community/detail/balsamiq_mockups_-_a_solid_case_for_air/" rel="nofollow">interview</a> with <a href="http://www.peldi.com/blog/" rel="nofollow">Peldi Guilizzoni</a>, the creator of <a href="http://www.balsamiq.com/" rel="nofollow">Balsamiq</a>--an Adobe AIR application for creating mockups:</p>
<blockquote>
<p><strong>And then you started working on the
first version Balsamiq Mockups. Was
there any hurdles in the development
process?</strong></p>
<p>Ha! There's always hurdles, it's part
of the fun of coding isn't it?</p>
<p>Let me think. I think I rewrote the
foundation classes (the Model, the
Input Manager, the base UI Component,
etc) a few times until I was happy
with them. First I started with each
UI control handle the mouse events for
moving and resizing itself, then moved
all the mouse handling to a
transparent InputManager canvas that
sits on top of the view (similar to
what I had done for Connect's
whiteboard). I also had to learn and
digest all the different options for
run-time skinning before I was able to
create a strategy that worked for my
tool, which took a while.</p>
</blockquote>
<ul>
<li>Is foundation classes a common term for the core classes in a framework?</li>
<li>Are "Model, UI Component, Input Manager" common themes in user interface development and what do they comprise of exactly?</li>
<li>What does he mean when he says he "moved the mouse handling to a transparent InputManager canvas on top of the view"? What is the view and the InputManager canvas.</li>
<li>Why does he do runtime skinning? Can't the skinning be done before hand? What other options are available that he could have explored?</li>
</ul>
<p>I am trying to get a handle on his design architecture.</p>
| <p>He is doing mock-ups. So for him, each UI Component is basically a rectangle (or other shape) that needs to be drawn and react to input. The input can come from different sources (mouse, keyboard, prepared for multi-touch?), so an Input Manager makes sense. In a mock-up, most components will have the same simple behavior, so extracting that to a separate object makes sense. In a mock-up it makes sense to change skins at run-time</p>
|
How to parse NULL value returned using YUI datasource <p>I am using YUI datatable and datasource to render data in one of my projects. The data returned happens to be NULL and YUI datasource is unable to parse it.</p>
<p>Below is the declaration code of datasource and datatable. For readability sake, I am seperating each of the declarations.</p>
<p><strong>Column Descriptions declaration</strong></p>
<pre><code> var columnDescription =
[
{key:'Requirements'},
{key:'abc'},
{key:'xyz'}
];
</code></pre>
<p>This columnDescription is set in the function below.</p>
<p><strong>DataSource Declaration</strong></p>
<pre><code>var dataSrcSample = new YAHOO.util.FunctionDataSource(getDataGrid);
myDataSource.connMethodPost = true;
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
myDataSource.responseSchema = {
fields:['Requirements',
{key:'abc',parser:YAHOO.util.DataSource.parseString},
{key:'xyz',parser:YAHOO.util.DataSource.parseString}]
};
</code></pre>
<p><strong>getDataGrid</strong> function makes the call to server side to get the data from the server.
Below is the table definition itself.</p>
<pre><code> YAHOO.example.sampleTable = function()
{
var columnDesc=columnDescription;
var myDataSource = dataSrcSample;
var oConfigs =
{
width:'100%'
};
var myDataTable = new YAHOO.widget.DataTable("tableContainerDiv",
columnDesc,
myDataSource,
oConfigs);
}();
</code></pre>
<p><strong>tableContainerDiv</strong> is declared in the html page. This is the container div.
The function that gets the JSON data from server.</p>
<pre><code>function getDataGrid()
{
//calls backend and gets the data
}
</code></pre>
<p>The function is returning json string that has some null values. Datasource constructor is complaining following problems.</p>
<ul>
<li>ERROR_DATAINVALID</li>
<li>ERROR_DATANULL</li>
</ul>
<p>I checked the yui <a href="http://developer.yahoo.com/yui/docs/YAHOO.util.DataSourceBase.html#method_DataSourceBase.parseString" rel="nofollow">documentation</a> and found that the string parser does not parse null values. I am wondering if there is any way to parse this data. Do I have to handleResponse parse the raw data? Any suggestions appreciated.</p>
| <p>First make sure that you need parser:YAHOO.util.DataSource.parseString for the fields. I haven't seen your JSON structure. So I cannot comment on this.</p>
<p>Other option is to use a custom formatter. Something like the following snippet will work.</p>
<pre><code>var customFormatter = function(elCell, oRecord, oColumn, sData) {
elCell.innerHTML = '';
try {
var strData = YAHOO.lang.JSON.parse(sData);
// set the elCell.innerHTML based on the strData
} catch {
// don't to anything
}
}
myDataSource.responseSchema = {fields:['Requirements', 'abc', 'xyz']};
var columnDescription =
[
{key:'Requirements'},
{key:'abc',
formatter: customFormatter
},
{key:'xyz',
formatter: customFormatter
}
];
</code></pre>
|
AJAX command-line interface in browser <p>I'm building a Web app to allow users to view and manipulate data, particularly numeric and geographic data. It's important that the output be clear and professional (data grids, Google Map overlays, etc.). But in terms of the user interface, I'd rather start with the flexibility of a command-line interface before building GUI-style forms.</p>
<p>Can you offer any tips, tricks, or suggestions to create an AJAX-based command-line interface that can drive the rest of the interface? Pointers to existing applications would be great, too.</p>
<p>The stack I'm using is Django/Python on the server side and ExtJS in the browser. If possible, I'd like to route commands to the Django shell and then just add some extra functions to output the results to a data grid, a map, etc.</p>
<p>Thanks!</p>
<p><strong>@Soviut</strong> Thanks for the quick response. I'm afraid I must not be making myself that clear. I want to use a shell to fire off commands on the server side that'll then feed back to output on the client side.</p>
<p>Here's an example I just found: <a href="http://shell.appspot.com/" rel="nofollow">http://shell.appspot.com/</a></p>
<p>It's just that I'd like to have that not just produce text output inside the shell but also produce output that will be picked up by other AJAX listeners for data grids and maps.</p>
| <p><a href="http://www.goosh.org/" rel="nofollow">goosh</a> is a great example of a command line web application. I had nothing to do with it's creation but I have used parts of it's design for something at work.</p>
|
What are valid characters for a DNS Zone file and how can I sanitize user input? <p>I'm working on an interface to allow our clients to update their DNS on their own.</p>
<p>I have 2 questions: </p>
<ol>
<li>What constitutes valid a valid host and target records? (A, CNAME, MX, TXT) i.e. if the user enters ........ for the host and target the DNS server won't like that.</li>
<li>Is there a regex I can use to sanitize user input?</li>
</ol>
<p>BTW it is BIND9 DNS and C# web app.</p>
<p>Thanks,</p>
<p>Kyle</p>
| <p>Domain name <em>labels</em> can technically contain any octet value, but <em>usually</em> they only contain alphanumerics and the hyphen and underscore characters. </p>
<p>This comes from recommendations in section 2.3.1 of <a href="http://www.ietf.org/rfc/rfc1035.txt" rel="nofollow">RFC 1035</a>:</p>
<blockquote>
<p>The labels must follow the rules for
ARPANET host names. They must start
with a letter, end with a letter or
digit, and have as interior characters
only letters, digits, and hyphen.
There are also some restrictions on
the length. Labels must be 63
characters or less.</p>
</blockquote>
<p>The underscore character is a more recent addition, typically used in the label portion of <code>SRV</code> records.</p>
<p>You could also permit the "<code>.</code>" character if you're going to let users create their own subdomains.</p>
<p>The <em>values</em> that are possible are:</p>
<ul>
<li><code>A</code> record - must be a dotted-quad IP address</li>
<li><code>CNAME</code> record - must be some other legal label</li>
<li><code>MX</code> record - 16-bit integer priority field, and a legal hostname. NB: some people put in labels which themselves point only to a <code>CNAME</code> record. This is frowned upon.</li>
<li><code>TXT</code> record - anything you like!</li>
</ul>
<p>Note that in every case, if you do allow any of the characters not in the normal set they would need to be escaped if they're being stored in a BIND format zone file.</p>
|
What data provider for a tclientdataset using a csv file? <p>I have a tclientdataset. It is used to get data to and from a csv file. The csv file may not exist until the application is run. I have the following code in a tbutton...</p>
<pre><code>ClientDataSet1->FileName = "c:\\testdata.csv";
ClientDataSet1->Open();
AddFiles(Edit1->Text);
ClientDataSet1->SaveToFile("c:\\testdata.csv");
</code></pre>
<p>When I run the application I get a "Missing data providor or data packet" error. I set the data provider to "Microsoft Text Driver (*.txt; *.csv)" and I still get the error.</p>
<p>What am I missing out or doing wrong? I REALLY don't want to have to create a dsn or do any manual pre-run work. I want the application to do all that. so I can move it to another computer and it just works.</p>
| <p>No answers so I'll answer and give an update. I have been able to use the clientdata set succesfully. I needed to create it with clientdataset->createdataset().</p>
<p>But it doesn't generate a CSV file. It generates some other type of file.</p>
<p>If I could get it to generate a CSV file that would be ideal but for now I can stick with it working as it does.</p>
|
How can you list the matches of Vim's search? <p>I would like to list the matches, when I hit:</p>
<pre><code>/example
</code></pre>
<p>so that I see where all matches are at once.</p>
| <pre><code>:g//p
</code></pre>
<p>In its longer form:</p>
<pre><code>:global/regular-expression/print
</code></pre>
<p>You can leave out the pattern/regex and Vim will re-use the previous search term.</p>
<p><em>Trivia:</em> The <a href="https://en.wikipedia.org/wiki/Grep">grep</a> tool was named after this command sequence.</p>
|
Python quotient vs remainder <p>The python 2.6 docs state that <code>x % y</code> is defined as the remainder of x / y (<a href="http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex" rel="nofollow">http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex</a>). I am not clear on what is really occurring though, as:</p>
<pre><code>for i in range(2, 11):
print 1.0 % i
</code></pre>
<p>prints "1.0" ten times, rather than "0.5, 0.333333, 0.25" etc. as I expected (1/2 = 0.5, etc). </p>
| <p>Modulo is performed in the integer context, not fractional (remainders are integers). Therefore:</p>
<pre><code>1 % 1 = 0 (1 times 1 plus 0)
1 % 2 = 1 (2 times 0 plus 1)
1 % 3 = 1 (3 times 0 plus 1)
6 % 3 = 0 (3 times 2 plus 0)
7 % 3 = 1 (3 times 2 plus 1)
8 % 3 = 2 (3 times 2 plus 2)
etc
</code></pre>
<blockquote>
<p><em>How do I get the actual remainder of x / y?</em></p>
</blockquote>
<p>By that I presume you mean doing a regular floating point division?</p>
<pre><code>for i in range(2, 11):
print 1.0 / i
</code></pre>
|
CGContext - is there a way to reset the current context <p>In my iPhone project, I've got a UIView where I implement the drawRect method:</p>
<pre><code>- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
</code></pre>
<p>Inside the method I do a whole bunch of drawing of lines, images and texts using this context. The problem is that when I re-use this view, the context does not get reset. Is there a method I can call to reset the context somehow?</p>
| <p>You might want to check out CGContextSaveGState(context) and CGContextRestoreGState(context). They will let you push and pop the current state of the context.</p>
<p>If your view is getting 'mangled', check your view's contentMode setting.</p>
|
Better Performance on Associations <p>Right now I have a table called Campaigns that has many Hits, if I call say:</p>
<pre>Campaign.find(30).hits</pre>
Which takes 4 seconds, or 4213 ms.
<br /><br />
If I call this instead:
<pre>
campaign = Campaign.find(30)
campaign.hits.count
</pre>
<p>Does it still load all of the hits, then count? Or does it see I am counting and avoids loading all of the hits? (Which is currently 300,000+ rows).<br /><br />
I am trying to figure out a smart way to load/count my hits. I am thinking about adding a method to my Campaign.rb model, like:</p>
<pre>
def self.total_hits
find :first, :select => 'COUNT(id) as hits', :conditions => ["campaign_id = ?", self.id]
end
</pre>
<p>I know that query won't load from the <code>hits</code> table, but that is just an example of counting it from a self made query, apposed to Ruby on Rails doing this for me.
<br /><br />
Would this memcache query be more effecient? (I have it running, but doesn't seem to be any better/faster/slower, just the same speed.)</p>
<pre>
def self.hits
Rails.cache.fetch("Campaign_Hits_#{self.campaign_id}", :expires_in => 40) {
find(:first, :select => 'COUNT(id) as hits', :conditions => ["campaign_id = ?", self.campaign_id]).hits
}
end
</pre>
<p>Any suggestions would be great!</p>
| <p>How about:</p>
<pre><code>Campaign.find(30).hits.count
</code></pre>
<p>You might also consider adding the following in <code>hit.rb</code> (assuming a one-to-many relationship between campaigns and hits).</p>
<pre><code>belongs_to :campaign, :counter_cache => true
</code></pre>
<p>You then need a column in the <code>campaigns</code> table called <code>hits_count</code>. This will avoid hitting <code>hits</code> altogether if you're only getting the count.</p>
<p>You can check the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html" rel="nofollow">API</a> for the full rundown.</p>
|
Testing IO.Stream interaction <p>I have a method in my business logic layer that accepts a stream, which in the GUI comes from a user uploading a file, and I am interested in which is an appropriate way to test that the method appropriately uses this stream to make decisions.</p>
<pre><code>public Sub Initialize(ByVal uploadStream As Stream)
''// Logic using uploadStream
End Sub
</code></pre>
<p>For testing purposes I wish to DI a mocked stream into this method, but I find a stiffling lack of abstraction whenever working with streams.</p>
<p>Intuition tells me that a need to create a Stream wrapper which would allow me to DI an interface of the wrapper to test interaction of my logic with the stream wapper.</p>
<p>What's the best way to proceed?</p>
| <p>If you just want a way to pass in a "fake" upload, you could construct a <a href="http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx" rel="nofollow">MemoryStream</a> in your test harness and pass that in.</p>
|
Optimize Hibernate entities saving? <p>Hi
Is there a way to reduce unnecessary/empty fields in SQL inserts and SQL updates?</p>
<p>For example, I have a single hibernate entity class mapped to a table that has 10 columns. The populating of data is actually done in two phases. When the user submit a request, I will insert the request information into the table with the hibernate entity, but populating only 7 fields. After some processing (wait for other users interaction for example), I will populate the remaining 3 fields (with the id given from the previous insert).</p>
<p>If I stick with a single entity class, for the second update, the steps I do is as follows:</p>
<p>1) Load the entity identified by id</p>
<p>2) Save the entity, which generates sql that seems to be sending all the fields over.</p>
<p>Alternatively, I created two entity class, and point to the same table and save them seperately.</p>
<p>Does anyone have a better suggestion?</p>
<p>Kent</p>
<p>Edit:</p>
<p>What I really like to achieve is something to the following effect:
insert t(id,field1,field2) (?,?,?)
update t set field3=? field4=? where id=?</p>
<p>The best I could achieve now with dynamicUpdate=true is
insert t(id,field1,field2) (?,?,?)
select field1,field2,field3,field4 from t where id=?
update t set field3=? field4=? where id=?</p>
<p>Is there a way to eliminate that select statement? The original persisted object is not stored anywhere in memory after the insert.</p>
<p>An additional note. The entity class is annotated with Hibernate validation. I am currently trying out to achieve the above desired effect, so I commented them out. But when I turn them back on, I get validation errors due to @NotNull and @NotEmpty.</p>
| <p>If you add the annotation:</p>
<pre><code>@org.hibernate.annotations.Entity(dynamicUpdate = true)
</code></pre>
<p>to the top of your entity only the fields that have changed will be sent to the database.</p>
|
Which API to use to draw 3D objects in C#? <p>I'd like to do some 3D programming in C# but I'm not sure where to start looking for an API. If I were doing this in C++ I know the options are OpenGL and DirectX, but I'm not sure what the options are for C#. I don't necessarily want to program a whole game, just manipulate a few objects.</p>
| <p>The out of the box option is WPF. Here's a nice series: <a href="http://www.ericsink.com/wpf3d/index.html">http://www.ericsink.com/wpf3d/index.html</a></p>
|
Exchanging of screens between two users <p>We have a web-based application with tech stack -
1. Java Struts based
2. Hibernate
3. DB - Oracle
4. App server - JBoss server</p>
<p>We are facing an issue related to concurrent usage of the application by two or more users. When I am doing an operation and I submit the changes, the next page or success message that comes up is of a different operation that another user is performing at the same time.</p>
<p>Users are logged in as different users and so are using different sessions. </p>
<p>We have no clue of where the problem is, so I am not sure what other details I can provide. </p>
<p>Has anyone else faced such an issue or any pointers? </p>
| <p>Are you using application context instead of session context? Moreover, as Eed3si9n said, beware of Singletons, that might be causing this.</p>
<p>"In addition check for the use of static fields. One app I was brought in to fix used a static string for error message. As soon as any user received an error they all did. Worked fine until there wasmore than one concurrent user." â <strong>Michael Rutherfurd (posted it as a comment)</strong></p>
|
What is so evil about a Flash based website? <p>I have the feeling that <a href="http://en.wikipedia.org/wiki/Adobe_Flash">Flash</a>-based ( or <a href="http://en.wikipedia.org/wiki/Microsoft_Silverlight">Silverlight</a>-based) websites are generally frowned upon, except when you are creating games or multimedia-content rich applications. Why this is so?</p>
| <p>Flash is infamous for its poor accessibility.</p>
<p>Keyboard navigation does not usually work, and Flash (up until recently) did not have search engine support.</p>
<p>Flash applications does not work in mobile phones and other portable devices.</p>
<p>Flash is not there in the iPhone!!!</p>
<p>Flash is controlled by a single company (Adobe) and so it is not following any well defined standards for the Internet.</p>
<p>The beauty of Internet lies in the fact that you can always view the source code of any website you are in. This way you can use the same programming/design techniques in your website or you can find security flaws in the web application. This is not possible in Flash. In Flash, source code is closed.</p>
<p>The big question is, why should you use Flash "except when you are creating games or multimedia-content rich applications"?</p>
<blockquote>
<p><a href="http://stackoverflow.com/users/657/jtyost2">jtyost2</a> says,
"I would also add that you can't directly link to any content inside of a Flash site, thus breaking one of the major factors that makes the Internet, the Internet, links."</p>
</blockquote>
|
Stubbing property getter prior to method on the same object - Rhino.Mocks 3.5 <p>I have a possible bug scenario for Rhino.Mocks 3.5 here: <a href="http://groups.google.com/group/RhinoMocks/browse_thread/thread/b38d09b276e66ec7" rel="nofollow">http://groups.google.com/group/RhinoMocks/browse_thread/thread/b38d09b276e66ec7</a>
Has anyone knows what's the issue?</p>
| <p>It looks like you've been answered on that thread. Did that help you and if so do you want to close this question?</p>
|
dojo: inheritance with default value - the mixin doesn't happen <p>I wish to declare a new dojo class inheriting from an existing dojo class, but with my own choice of default values for the class's properties. (The user can still override those values.)</p>
<p>I am declaring my own version of the <code>dijit.form.FilteringSelect</code> such that:</p>
<ul>
<li>the <code>hasDownArrow</code> property defaults to <code>false</code> (rather than the standard <code>true</code>) and</li>
<li>there's an extra possible property <code>storeUrl</code> which allows me to connect the <code>FilteringSelect</code> to the corresponding <code>QueryReadStore</code>.</li>
</ul>
<p>Here's what I did, without success:</p>
<pre><code>dojo.provide("my.FilteringSelect");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dojox.data.QueryReadStore");
dojo.declare(
"my.FilteringSelect",
[
dijit.form.FilteringSelect, /* base superclass */
{ hasDownArrow:false, storeUrl:"/" } /* mixin */
],
{
constructor: function(params, srcNodeRef){
console.debug("Constructing my.FilteringSelect with storeUrl "
+ this.storeUrl);
this.store = new dojox.data.QueryReadStore({url:this.storeUrl});
}
}
);
</code></pre>
<p>Say, I try to generate declaratively in the HTML such a version of <code>my.FilteringSelect</code>:</p>
<pre><code><input type="text" id="birthplace" name="birthplace"
promptMessage="Start typing, and choose among the suggestions"
storeUrl="/query/regions"
dojoType="my.FilteringSelect" />
</code></pre>
<p>This will indeed create a <code>FilteringSelect</code> with the desired <code>promptMessage</code> (which means that the superclass is properly getting the params), but <code>hasDownArrow</code> is <code>true</code> (contrary to my default mixin) and the <code>store</code> is <code>null</code> (and the Firebug console reports that <code>storeUrl</code> is "<code>undefined</code>").</p>
<p>What am I doing wrong?</p>
| <p>Oops! I really had things on their head. I found the right way around. The following works:</p>
<pre><code>dojo.provide("my.FilteringSelect");
dojo.require("dijit.form.FilteringSelect");
dojo.require("dojox.data.QueryReadStore");
dojo.declare(
"my.FilteringSelect",
dijit.form.FilteringSelect,
{
hasDownArrow : false,
storeUrl : "/",
constructor: function(params, srcNodeRef){
dojo.mixin(this, params);
console.debug("Constructing my.FilteringSelect with storeUrl "
+ this.storeUrl);
this.store = new dojox.data.QueryReadStore({url:this.storeUrl});
}
}
);
</code></pre>
|
Accessing crystal reports in an ASP.NET application? <p>I need to access a Crystal Report that is deployed on a Crystal Report server.</p>
<p>I want to display this report on my ASP.NET page. However, I don't want to include the report file in my project. I need to use the report file deployed on crystal report server.</p>
<p>Can you please guide me on how to do this?</p>
| <p>Try </p>
<pre><code>ReportDocument.Load(<filePath>, OpenReportMethod.OpenReportByTempCopy)
</code></pre>
|
The difference between the 'Local System' account and the 'Network Service' account? <p>I have written a Windows service that spawns a separate process. This process creates a COM object. If the service runs under the 'Local System' account everything works fine, but if the service runs under the 'Network Service' account, the external process starts up but it fails to create the COM object. The error returned from the COM object creation is not a standard COM error (I think it's specific to the COM object being created).</p>
<p>So, how do I determine how the two accounts, 'Local System' and 'Network Service' differ? These built-in accounts seem very mysterious and nobody seems to know much about them.</p>
| <p>Since there is so much confusion about functionality of standard service accounts, I'll try to give a quick run down.</p>
<p>First the actual accounts:</p>
<ul>
<li><p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684188%28v=vs.85%29.aspx"><strong>LocalService</strong> account</a> (preferred)</p>
<ul>
<li>Name: <code>NT AUTHORITY\LocalService</code></li>
<li>the account has no password (any password information you provide is ignored)</li>
<li>HKCU represents the <strong>LocalService</strong> user account</li>
<li>has <em>minimal</em> privileges on the local computer</li>
<li>presents <em>anonymous</em> credentials on the network</li>
<li><strong>SID</strong>: S-1-5-19</li>
<li>has its own profile under the <strong>HKEY_USERS</strong> registry key (<code>HKEY_USERS\S-1-5-19</code>)</li>
</ul>
<p> </p>
<p>A limited
service account that is very similar to Network Service and meant to run
standard least-privileged services. However, unlike Network Service it <strike>has no ability to access the network as the machine</strike> accesses the network as an <em>Anonymous</em> user.</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684272%28v=vs.85%29.aspx"><strong>NetworkService</strong> account</a></p>
<ul>
<li><code>NT AUTHORITY\NetworkService</code></li>
<li>the account has no password (any password information you provide is ignored)</li>
<li>HKCU represents the <strong>NetworkService</strong> user account</li>
<li>has <em>minimal</em> privileges on the local computer</li>
<li>presents the computer's credentials (e.g. <code>MANGO$</code>) to remote servers</li>
<li><strong>SID</strong>: S-1-5-20</li>
<li>has its own profile under the <strong>HKEY_USERS</strong> registry key (<code>HKEY_USERS\S-1-5-20</code>)</li>
<li>If trying to schedule a task using it, enter <code>NETWORK SERVICE</code> into the <em>Select User or Group</em> dialog </li>
</ul>
<p> </p>
<p>Limited service account that is meant to run standard
least-privileged services. This account is far more limited than Local System (or even Administrator) but still has the right to access the network as the machine (see caveat above).</p></li>
<li><p><a href="http://msdn.microsoft.com/en-us/library/windows/desktop/ms684190%28v=vs.85%29.aspx"><strong>LocalSystem</strong> account</a> <em>(dangerous, don't use!)</em></p>
<ul>
<li>Name: <code>.\LocalSystem</code> (can also use <code>LocalSystem</code> or <code>ComputerName\LocalSystem</code>)</li>
<li>the account has no password (any password information you provide is ignored)</li>
<li><strong>SID</strong>: S-1-5-18</li>
<li>does not have any profile of its own (<code>HKCU</code> represents the <strong>default</strong> user)</li>
<li>has <em>extensive</em> privileges on the local computer</li>
<li>presents the computer's credentials (e.g. <code>MANGO$</code>) to remote servers </li>
</ul>
<p> </p>
<p>Completely trusted account, more so than the administrator account. There is
nothing on a single box that this account cannot do, and it has the
right to access the network as the machine (this requires Active
Directory and granting the machine account permissions to something)</p></li>
</ul>
<p>Above when talking about accessing the network, this refers solely to <a href="http://en.wikipedia.org/wiki/SPNEGO">SPNEGO</a> (Negotiate), NTLM and Kerberos and not to any other authentication mechanism. For example, processing running as <code>LocalService</code> can still access the internet. </p>
<p>The general issue with running as a standard out of the box account is that if you modify any of the default permissions you're expanding the set of things everything running as that account can do. So if you grant DBO to a database, not only can your service running as Local Service or Network Service access that database but everything else running as those accounts can too. If every developer does this the computer will have a service account that has permissions to do practically anything (more specifically the superset of all of the different additional privileges granted to that account).</p>
<p>It is always preferable from a security perspective to run as your own service account that has precisely the permissions you need to do what your service does and nothing else. However, the cost of this approach is setting up your service account, and managing the password. It's a balancing act that each application needs to manage.</p>
<p>In your specific case, the issue that you are probably seeing is that the the DCOM or COM+ activation is limited to a given set of accounts. In Windows XP SP2, Windows Server 2003, and above the Activation permission was restricted significantly. You should use the Component Services MMC snapin to examine your specific COM object and see the activation permissions. If you're not accessing anything on the network as the machine account you should seriously consider using <strong>Local Service</strong> (not Local System which is basically the operating system). </p>
<hr>
<p>In Windows Server 2003 <a href="http://serverfault.com/a/513829/4822">you <strong>cannot</strong> run a scheduled task</a> as </p>
<ul>
<li><code>NT_AUTHORITY\LocalService</code> (aka the Local Service account), or </li>
<li><code>NT AUTHORITY\NetworkService</code> (aka the Network Service account). </li>
</ul>
<p>That capability only was added with Task <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/aa383614%28v=vs.85%29.aspx">Scheduler 2.0</a>, which only exists in Windows Vista/Windows Server 2008 and newer.</p>
<p>A service running as <code>NetworkService</code> presents the machine credentials on the network. This means that if your computer was called <code>mango</code>, <a href="http://serverfault.com/a/135874/4822">it would present as the machine account</a> <code>MANGO$</code>:</p>
<p><img src="http://i.stack.imgur.com/exvfr.png" alt="enter image description here"></p>
|
Getting the parent name of a URI/URL from absolute name C# <p>Given an absolute URI/URL, I want to get a URI/URL which doesn't contain the leaf portion. For example: given <a href="http://foo.com/bar/baz.html">http://foo.com/bar/baz.html</a>, I should get <a href="http://foo.com/bar/">http://foo.com/bar/</a>.</p>
<p>The code which I could come up with seems a bit lengthy, so I'm wondering if there is a better way.</p>
<pre><code>static string GetParentUriString(Uri uri)
{
StringBuilder parentName = new StringBuilder();
// Append the scheme: http, ftp etc.
parentName.Append(uri.Scheme);
// Appned the '://' after the http, ftp etc.
parentName.Append("://");
// Append the host name www.foo.com
parentName.Append(uri.Host);
// Append each segment except the last one. The last one is the
// leaf and we will ignore it.
for (int i = 0; i < uri.Segments.Length - 1; i++)
{
parentName.Append(uri.Segments[i]);
}
return parentName.ToString();
}
</code></pre>
<p>One would use the function something like this:</p>
<pre><code> static void Main(string[] args)
{
Uri uri = new Uri("http://foo.com/bar/baz.html");
// Should return http://foo.com/bar/
string parentName = GetParentUriString(uri);
}
</code></pre>
<p>Thanks,
Rohit</p>
| <p>Did you try this? Seems simple enough.</p>
<pre><code>Uri parent = new Uri(uri, "..");
</code></pre>
|
How to handle incomplete files? Getting exception <p>I need to create a java program which will create thread to search for a file in particular folder(source folder) and pick the file immediately for process work(convert it into csv file format) once it found the file in the source folder. Problem i am facing now is file which comes to source folder is big size(FTP tool is used to copy file from server to source folder), thread is picking that file immediately before it copies fully to source folder and throwing exception. How do i stop thread until the file copy into source folder completely?. It has to pick the file for processing only after the file is copied completely into source folder.</p>
| <p>Tha safest way is to download the file to a different location and then move it to the target folder.</p>
<p>Another variation mentioned by Bombe is to change the file name to some other extension after downloading and look only for files with that extension.</p>
|
Getting table metadata in MySQL <p>I'm trying to find out how to get the following constraint information from a table in MySQL 5.0: </p>
<ul>
<li>primary key</li>
<li>foreign keys and table references</li>
<li>unique columns</li>
</ul>
<p>What is the syntax of the query or queries to do so? I have a feeling I'm close with <a href="http://dev.mysql.com/doc/refman/5.0/en/table-constraints-table.html">this</a>, but there is no example.</p>
| <p>The <a href="http://dev.mysql.com/doc/refman/5.0/en/show-columns.html" title="show columns">SHOW COLUMNS</a> command will show you the primary key and unique columns for a table.</p>
<p>As for foreign keys, you <strong>could</strong> use something like the <a href="http://dev.mysql.com/doc/refman/5.0/en/show-create-table.html">SHOW CREATE TABLE</a> command which will output the DDL statements needed to replicate the table.</p>
|
How can I write to the parallel port from the Windows Command line? <p>How can I write to parallel port through Windows XP command line?</p>
| <p>Looking at your reply to Zoredache, your real problem is not output to the parallel port, that's trivial.</p>
<p>Your real problem is how to get a 0xff character on stdout. This is possible with a trivial <code>.com</code> executable which invokes the relevant soft interrupt, but to be honest it's probably easier to create a file with that single 0xff character in it and then just <code>copy</code> that to the printer:</p>
<pre><code>> copy /b data.bin lpt1
</code></pre>
<p>Note the <code>/b</code> flag which tells copy that the file is a binary file.</p>
|
Connection pooling in the MySQL .NET Connector <p>I'm creating a website in asp.net and mysql, I noticed that the performance of connection pooling in the mysql .net connector is horrible to say the least! For example sql server is 10x times faster in connection pooling (the sql server .net provider connecting to sql server), is there anything I could do to speed up connection pooling? Does the mysql .net connector make any checks when the connection is returned to the pool which cause the slowdown?</p>
<p>Thanks</p>
| <p>Make sure that you are using the latest version of MySQL .Net Connector. The current version is 5.2.5. </p>
<p>Also, the Connection String has a property Connection Lifetime (default value 0). You can try changing that value. More information can be found <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-net-using-connection-pooling.html" rel="nofollow">here</a> and <a href="http://dev.mysql.com/doc/refman/5.1/en/connector-net-examples-mysqlconnection.html#connector-net-examples-mysqlconnection-connectionstring" rel="nofollow">here</a> </p>
|
ASP.NET MVC - Manipulating HTTP Post <p>When a form is posted back to the server, is it possible to manipulate, change, set the values contained in HTTP Post in the controller action? I would like to remove certain textbox values entered by the user so that these values always have to be re-entered (e.g. password fields). By default Html helpers extract initial values for HTML controls from the HTTP Post info.</p>
| <p>You don't need a custom ModelBinder.</p>
<pre><code> [Bind(Exclude="Foo,Bar")]
public ActionResult Insert(T model)
</code></pre>
<p>Now Foo and Bar are null.</p>
<p>This does what you ask, but I'm not actually sure it's what you meant. :)</p>
<p>My guess is that your action does need to see the password (or whatever) entered by the user. But if, for example, a different field needs to be re-entered, you don't want to populate the password when you re-display the form. That's a good idea. But in this case, model binders don't even enter in. You simply set the field to null before you re-display the view.</p>
<pre><code> public ActionResult Insert(T model)
{
try
{
Repository.Add(model);
}
catch (Exception ex)
{
ViewData["Message"] = ex.Message;
model.Password = null;
return View(model);
}
// success!
return RedirectToRoute( //...
}
</code></pre>
|
Java JTree expand only level one nodes <p>With a JTree, assuming the root node is level 0 and there may be up to 5 levels below the root, how can I easily expand all the level 1 nodes so that all level 1 & 2 branches and leafs are visible but levels 3 and below aren't?</p>
| <p>Thanks for the quick response guys. However I have now found the simple solution I was looking for. For some reason I just couldn't see DefaultMutableTreeNode.getLevel() in the JavaDocs! FYI what I'm doing now is:</p>
<pre><code> DefaultMutableTreeNode currentNode = treeTop.getNextNode();
do {
if (currentNode.getLevel()==1)
myTree.expandPath(new TreePath(currentNode.getPath()));
currentNode = currentNode.getNextNode();
}
while (currentNode != null);
</code></pre>
|
Switching between two UITableViewControllers within a single UINavigationController <p>I have a UINavigationController. In its toolbar is a segmented control with two buttons. Each button relates to its own UITableViewController.</p>
<p>What I'm trying to achieve is someway of wiring up the navigation controller so that the views are switched depending on which button within the segmented control is active.</p>
<p>I assume I should hold on to the table controllers, because I want to preserve the scrolling position within each view, e.g., if the user was positioned at the top of table 1, and the bottom of table 2, then this information should be preserved when switching.</p>
<p>Any suggestions would be gratefully received!</p>
| <p>Would it be possible to just switch the dataSource instead of having to deal with two separate table views? Preserving the scrolling position can still just as easily be done, and you end up using less memory (one table view and two data sources instead of two table views and two data sources).</p>
<p>With only 128MB to spare, memory efficiency is king on the iPhone.</p>
|
Real-time Java interoperability <p>I am wondering how it's the interoperability between JRE6 and the JVM from <a href="http://www.rtsj.org" rel="nofollow">rtsj</a>. It seems that I have to use only their implementation (since the code will be interpreted using their JVM), so I cannot use many of the features that Java 6 has to offer.
Can it support a GUI? (say for example to modify the parameters of an industrial process).</p>
<p>I might be wrong, hoping to get some feedback from you.</p>
<p>Also, it seems that are more real time implementations for Java. Which one did you use and which one did you like most?</p>
| <p>In order to provide real-time behavior, the JVM needs to be very specifically engineered. This includes integration at the operating system level to get access to real-time scheduling features of the host OS.</p>
<p>The Sun rea-time JVM is compatible with J2SE5, for instance. <a href="http://java.sun.com/javase/technologies/realtime/faq.jsp#4" rel="nofollow">http://java.sun.com/javase/technologies/realtime/faq.jsp#4</a></p>
<p>Generally, any specialized instance of a system (OS, JVM, etc) that offers niche functionality, like security or real-time behavior, tends to be a release behind the general purpose version.</p>
<p>As to using a GUI for real-time, you should investigate using 2 tier client-server control of the real-time process using something like JMX, RMI or web-services (whichever is the lightest-weight). Using a GUI directly in real-time code seems like it could introduce lots of potential problems for the application as it tries to execute withing real-time constraints.</p>
|
WebSphere Portal 6.0 Portlet Error Logging <p>Where I can find the error logs from a portlet deployed to WebSphere Portal 6.0 (Linux)</p>
| <p>You will find logs in SystemOut.log and SystemErr.log </p>
<p>In a default Webpshere Portal 6.0 installation logs (SystemOut.log, SystemErr.log) are located under <code><PortalServer></code>\log\ </p>
<p>The best way to find out the location of these file is to check in the Websphere Administration console.
In the Administration console, Under Environment > Websphere variables, look for variable SERVER<code>_LOG_</code>ROOT</p>
|
IE7 Ext JS problem: Unspecified JS error on window.close() <p>I am using Ext JS to make a popup window, here is the code:</p>
<pre><code>function popupImage(term, imageNumber){
if(currentPopupWindow!=null){
currentPopupWindow.close();
}
currentPopupWindow = new Ext.Window({
layout : 'fit',
closeAction :'hide',
plain : true,
constrain : true,
width: 300,
border: false,
html: "Blah blah content"<span onclick=\"currentPopupWindow.close();\">cerrar</span>"
});
currentPopupWindow.show(false, function(){
var el = Ext.get("termimage");
currentPopupWindow.setWidth(el.getWidth(true)+150);
});
currentPopupWindow.anchorTo(Ext.get("dictionarycontainer"), "tl");
}
</code></pre>
<p>In firefox this works fine. In IE7 it works, but always produces a javascript error saying "unspecified error". </p>
<p>What am I doing wrong?</p>
<h2>EDIT</h2>
<p>Removing the anchorTo line removes the error. I would still like to anchor to though so this isn't a great solution!</p>
| <p>This is the solution, dumb as it is:</p>
<p>Have the same window creation, then instead of the calls to show and anchor to:</p>
<pre><code> currentPopupWindow.render(document.body);
currentPopupWindow.alignTo(diccon, "tl", [40, 80]);
currentPopupWindow.show(false, function() {
var el = Ext.get(termim);
currentPopupWindow.setWidth(el.getWidth(true)+150);
});
</code></pre>
|
MySQL - Need help to figure out multiple joins <p>I am using the following query to get the transactions from a table made to and from a user. I then want to retrieve the username for the sender_id and for the recipient_id. However I can only seem to get it for the recipient_id or the sender_id. Anyone have any ideas how I can get both.</p>
<pre><code>SELECT us.name, ta.amount, ta.recipient_id, ta.sender_id, ta.timestamp_insert
FROM `transactions` AS ta
JOIN users AS us
ON ta.recipient_id=us.u_id
WHERE ta.sender_id =111111 OR ta.recipient_id = 111111
LIMIT 0 , 10
</code></pre>
<p><strong>Transactions Table Columns:</strong></p>
<p>transaction_id<br />
tw_id<br />
tw<br />
sender_id<br />
recipient_id<br />
amount<br />
timestamp_insert<br />
timestamp_start
timestamp_complete
transaction_status</p>
<p><strong>User Table Columns:</strong></p>
<p>u_id,
name</p>
| <p>You need to join twice, thus:</p>
<pre><code>SELECT ta.amount, ta.recipient_id, ta.sender_id, ta.timestamp_insert, sender.name as Sender, recipient.name as Recipient
FROM `transactions` AS ta
JOIN users AS recipient
ON ta.recipient_id=recipient.u_id
JOIN users AS sender
ON ta.sender_id=sender.u_id
WHERE ta.sender_id =111111 OR ta.recipient_id = 111111
LIMIT 0 , 10
</code></pre>
|
Classic ASP: How to list activated sessions? <p>Is there someway to get a list of activated sessions in classic ASP?</p>
<p>I want to limit the number of simultaneus activated sessions.</p>
| <p>Here is a good article which shows a way to do that: <a href="http://www.aspfree.com/c/a/asp-code/active-user-count-without-global-asa-by-josh-painter/" rel="nofollow">Active User Count Without Global.asa by Josh Painter</a> </p>
<p>I guess you have to change some details, but this is the way you could approach the problem. The author doesn't use global.asa. </p>
<p>A simpler way would be to hook the <code>Sesssion_OnStart</code> and <code>Session_OnEnd</code> events in global.asa and adding/removing the item from the list of sessions implemented as an Application variable.</p>
<p>If you just want the <strong>count</strong> of sessions, you could simply doing it this way:</p>
<pre><code>Sub Session_OnStart
Application.Lock
Application("count") = Application("count") + 1
Application.Unlock
End Sub
Sub Session_OnEnd
Application.Lock
Application("count") = Application("count") - 1
If Application("count") < 0 then ' Could only happen if some other function interfers
Application("count")=0
End If
Application.Unlock
End Sub
</code></pre>
<p>In your ASP file</p>
<pre><code><%
Response.Write "There are currently " & Application("count") & "active sessions>"
%>
</code></pre>
|
"scheduledTimerWithTimeInterval:" problem in cocos2d? <p>I am trying to developed a iPhone app by using cocos2d. I using "scheduledTimerWithTimeInterval" for calling a method that called a fixed time interval. But now time interval increases in gradually. for this reason the time is slow in gradually.
here is my code: </p>
<pre><code>- (void) methodTime: (id) sender{
NSTimer *rat =[NSTimer scheduledTimerWithTimeInterval:(.5) target:self selector:@selector(rotation:) userInfo:nil repeats:YES];
}
- (void) rotation:(NSTimer *)theTimer{
NSLog(@"I m # %i", i);
i=i+10; // Here , i is a global int variable.
i=i % 1440;
if(i==0){
[theTimer invalidate];
}
else {
int rotationNum=i;
Sprite *sp = [Sprite spriteWithFile: @"1.png"];
sp.position=cpv(220,180.5);
sp.rotation=rotationNum;
[self add:sp];
}
}
</code></pre>
| <p>It looks like every 0.5 seconds you are adding a sprite to some list of sprites. Eventually the list is getting very large and all that data causes your method to take longer than 0.5 seconds to execute. This causes the timer to fire fast as it can, which is not all that fast since its always waiting for your method to be finished with.</p>
<p>Without know more about your code, that's my best guess.</p>
|
Is there an STL and UTF-8 friendly C++ Wrapper for ICU, or other powerful Unicode library <p>I need a good Unicode library for C++. I need:</p>
<ol>
<li>Transformations in a Unicode sensitive way. For example sort all strings in a case insensitive way and get their first characters for index. Convert various Unicode strings to upper and to lower case. Split text at a reasonable position -- words that would work for Chinese and Japanese as well.</li>
<li>Formatting numbers, dates in locale sensitive way (should be thread safe).</li>
<li>Transparent support of UTF-8 (primary internal representation).</li>
</ol>
<p>As far as I know the best library is ICU. However, I can't find normal developer friendly API documentation with examples. Also as far as I see, it is not too friendly with
modern C++ design, work with STL and so on. Like this:</p>
<pre><code>std::string msg;
unistring umsg.from_utf8(msg);
unistring::word_iterator wi;
for(wi=umsg.words().begin(),n=0;wi!=usmg.words().wi_end(),n<10;++wi,++n)
;
msg=umsg.substr(umsg.words().begin(),wi).to_utf8();
cout<<_("Five 10 words are ")<<msg;
</code></pre>
<p>Is there a good STL friendly ICU wrapper released under Open Source license? Preferred is a license permissive like MIT or Boost, but others, like LGPLv2 compatible, are OK as well.</p>
<p>Is there another high quality library similar to ICU?</p>
<p>Platform: Unix/POSIX, Windows support is not required.</p>
<p><strong>Edit:</strong> unfortunately I wasn't logged in, so I can't make accept an answer. I have attached the answer by myself.</p>
| <p>This question was asked quite a long time before by myself. There was no such library.</p>
<p>So I had written C++ friendly <a href="http://lists.boost.org/Archives/boost/2010/03/162952.php" rel="nofollow">Boost.Locale</a> library that wraps ICU.</p>
<ul>
<li>Docs: <a href="http://cppcms.sourceforge.net/boost_locale/html/" rel="nofollow">http://cppcms.sourceforge.net/boost_locale/html/</a></li>
<li>Sources: <a href="https://sourceforge.net/projects/cppcms/files/" rel="nofollow">https://sourceforge.net/projects/cppcms/files/</a></li>
</ul>
<p><strong>Edit</strong> Now part of Boost: see <a href="http://www.boost.org/doc/libs/release/libs/locale/" rel="nofollow">Boost.Locale documentation</a></p>
|
Transparent control backgrounds on a VB.NET gradient filled form? <p>I'm filling the background of some VB.NET 2005 WinForms form with a nice pretty gradient fill (by overriding the OnPaint event). This works fine but the various labels etc on the form show with a solid background even after I set the BackColor to Color.Transparent. Setting the transparency key of the form itself seems to affect this but I cannot get the labels to have a truely transparent BackColor, is there an easy way to get around this or am I looking at custom controls etc?</p>
| <p>Add a new class to your project and paste the code shown below. Build. Drop the new control from the top of your toolbox onto your form.</p>
<pre><code>Public Class TransparentLabel
Inherits Label
Public Sub New()
Me.SetStyle(ControlStyles.Opaque, True)
Me.SetStyle(ControlStyles.OptimizedDoubleBuffer, False)
End Sub
Protected Overrides ReadOnly Property CreateParams() As System.Windows.Forms.CreateParams
Get
Dim cp As CreateParams = MyBase.CreateParams
cp.ExStyle = cp.ExStyle Or &H20 ' Turn on WS_EX_TRANSPARENT
Return cp
End Get
End Property
End Class
</code></pre>
<p>The flicker might be noticeable, no fix.</p>
|
mySQL large text comparisson performance... best practices? <p>I've got a largish (~1.5M records) table that holds text strings of varying length for which I run queries against looking for matches:</p>
<pre><code>CREATE TABLE IF NOT EXISTS `shingles` (
`id` bigint(20) NOT NULL auto_increment,
`TS` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`shingle` varchar(255) NOT NULL,
`count` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `shingle` (`shingle`,`TS`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1571668;
</code></pre>
<p>My problem is that I need while I'm doing comparisons against this table I am constantly adding and removing data from it, so maintaining indexes is hard.</p>
<p>I'm looking for best practices for managing the inserts in a timely fashion while maximizing the throughput for the selects. This process is running 24hrs a day and needs to be as quick as possible.</p>
<p>Any help is appreciated.</p>
<p><strong>Update:</strong> <em>To clarify, I'm doing one to one matches on the 'shingle' column, not text searches within it.</em></p>
| <p>First: your bigint primary key could be killing you here, it's a very expensive type to try to maintain. 1.5 million records is nowhere near the limit for unsigned int (~4.2 billion). </p>
<p>Using a big int for a primary key is even worse in InnoDB as it stores the PK against each entry in every other index, so that could partially explain the problems when you tried switching. As soon as you're adding and deleting from the table MyISAM is gonna get screwed if there are a lot of concurrent transactions.</p>
<p>A trick to get around the expense of string comparisons is to store crc32(shingle) as well as shingle. You then index this column, but not your varchar. Something like below is how I'd do it:</p>
<pre><code>CREATE TABLE IF NOT EXISTS `shingles` (
`id` int unsigned NOT NULL auto_increment,
`TS` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
`crc` int unsigned not null,
`shingle` varchar(255) NOT NULL,
`count` int(11) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `crc` (`crc`)
)
insert into shingles (crc, shingle, count) values (crc32('testtest'),'testtest',1),(crc32('foobar'),'foobar',4);
select * from shingles where crc = crc32('foobar') and shingle = 'foobar';
</code></pre>
<p>If you intend to query on 'ts' then add it as the second component of the crc index</p>
|
Generic types not equal <p>The code segment below prints out "The types ARE NOT the same.". Why? I am aware of the fact that using <code>interfaceOnMyType.GetGenericTypeDefinition()</code> will solve the problem, but why should I have to do that?</p>
<pre><code>class Program
{
static void Main(string[] args)
{
var myType = typeof(Baz<>);
var interfaceOnMyType = myType.GetInterfaces().SingleOrDefault();
var exactType = typeof(IBar<>);
if (exactType == interfaceOnMyType)
{
Console.WriteLine("The types ARE the same.");
}
else
{
Console.WriteLine("The types ARE NOT the same.");
}
Console.ReadLine();
}
}
interface IBar<T>
{
}
class Baz<T> : IBar<T>
{
}
</code></pre>
| <pre><code>interfaceOnMyType.GetGenericTypeDefinition()
</code></pre>
<p>returns you the closed constructed type of the interface which is different from the type returned from </p>
<pre><code>typeof(IBar<>)
</code></pre>
<p><a href="http://msdn.microsoft.com/en-us/library/system.type.getgenerictypedefinition.aspx" rel="nofollow">Here is the MSDN article on <code>GetGenericTypeDefinition</code></a>, and here is a good quote from it explaining how it works:</p>
<blockquote>
<p>Given a <code>Type</code> object representing this constructed type, the <code>GetGenericTypeDefinition</code> method returns the generic type definition.</p>
</blockquote>
<p><hr /></p>
Edit (the answer above is correct in some cases but wrong in this one):
<p>I think I may have found it now. The reason that the type comparison is failing is because the <code>Type</code> returned from <code>myType.GetInterfaces()</code> is close to but not identical to the type of the interface itself.</p>
<p>According to <a href="http://msdn.microsoft.com/en-us/library/system.type.fullname.aspx" rel="nofollow">MSDN</a>:</p>
<blockquote>
<p>If you use the <code>BaseType</code> property to obtain the base type of <code>Derived</code>, the <code>FullName</code> property of the resulting Type object returns <code>null</code> (Nothing in Visual Basic). To get a non-null <code>FullName</code>, you can use the <code>GetGenericTypeDefinition</code> method to get the generic type definition. </p>
</blockquote>
<p>So I think this is the problem you are seeing. Since base interfaces are retrieved via <code>GetInterfaces</code> any type retrieved by that call will not have a <code>FullName</code> (<a href="http://msdn.microsoft.com/en-us/library/system.type.basetype.aspx" rel="nofollow">source</a>). Since it does not have a <code>FullName</code> the types will fail in comparison.</p>
<p>What I orginally wrote would be true if you were comparing the constructed type which you are not. So unfortunately my first answer is dead wrong - I have left it so that the comments left will make sense.</p>
|
How to get ID when you pass my ID <p>I have a function that gets passed the document object like:</p>
<pre><code>toggle( $('username') );
function Toggle(id)
{
/// ??
}
</code></pre>
<p>How can I get the actual name of the object passed i.e. username?</p>
| <p>If I understand you correctly, can't you:</p>
<pre><code>$(id).attr("id");
</code></pre>
<p>or</p>
<pre><code>$(id).attr("name");
</code></pre>
<p>Or am I mistaken?</p>
|
Relative percentage UI control <p>I need the user to set a number of percentage values which should always add up to 100%. What are standard ways to archieve this? I came up with the following:</p>
<p>1) have a standard slider control for each value you need to set. Moving one slider will automatically adjust all the others so the sum will always come out as 100%. You can fix inidividual sliders with a checkbox displayed next to it. Only the remaining, "free", sliders will be adjustable.</p>
<p>Pro: consists entirely of standard widgets users already know </p>
<p>Con: lots of widgets, lots of screen real estate used, looks ugly when you have lots of sliders and thus low percentage values, normalization to 100% isn't immediately obvious.</p>
<p>2) have a slider control with several sliding knobs.</p>
<p>Pro: normalization is implicit and obvious because the length of the slider is fixed, relative weight is easy to see at a glance</p>
<p>Con: non-standard, knobs can easily overlap each other, knobs aren't easy to fix, no obvious place to put a text/number representation for each interval/percentage</p>
<p>3) display a standard pie chart.</p>
<p>Pro: normalization is implicit and obvious, relative weight is easy to see</p>
<p>Con: non-standard for interactive use, hard to make intuitive slice resizing work, no place to put a text/number representation for each slice</p>
<p>4) ... ?</p>
<p>I'm not happy with either of these hence my question here. Any better ideas? I'm dealing with 3-10 individual percentage values on a rich windows client (i.e. not web).</p>
<p>cheers,</p>
<pre><code>Sören
</code></pre>
| <p>What about vertical sliders? Like a sound mixer. I think it looks a lot better than a list of 10 horizontal sliders.</p>
<p>Or fixed width bar with several sliders on them, a bit like the gradient control of Photoshop if you know it.</p>
|
"SELECT COUNT(*)" is slow, even with where clause <p>I'm trying to figure out how to optimize a very slow query in MySQL (I didn't design this):</p>
<pre><code>SELECT COUNT(*) FROM change_event me WHERE change_event_id > '1212281603783391';
+----------+
| COUNT(*) |
+----------+
| 3224022 |
+----------+
1 row in set (1 min 0.16 sec)
</code></pre>
<p>Comparing that to a full count:</p>
<pre><code>select count(*) from change_event;
+----------+
| count(*) |
+----------+
| 6069102 |
+----------+
1 row in set (4.21 sec)
</code></pre>
<p>The explain statement doesn't help me here:</p>
<pre><code> explain SELECT COUNT(*) FROM change_event me WHERE change_event_id > '1212281603783391'\G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: me
type: range
possible_keys: PRIMARY
key: PRIMARY
key_len: 8
ref: NULL
rows: 4120213
Extra: Using where; Using index
1 row in set (0.00 sec)
</code></pre>
<p>OK, it still thinks it needs roughly 4 million entries to count, but I could count lines in a file faster than that! I don't understand why MySQL is taking this long.</p>
<p>Here's the table definition:</p>
<pre><code>CREATE TABLE `change_event` (
`change_event_id` bigint(20) NOT NULL default '0',
`timestamp` datetime NOT NULL,
`change_type` enum('create','update','delete','noop') default NULL,
`changed_object_type` enum('Brand','Broadcast','Episode','OnDemand') NOT NULL,
`changed_object_id` varchar(255) default NULL,
`changed_object_modified` datetime NOT NULL default '1000-01-01 00:00:00',
`modified` datetime NOT NULL default '1000-01-01 00:00:00',
`created` datetime NOT NULL default '1000-01-01 00:00:00',
`pid` char(15) default NULL,
`episode_pid` char(15) default NULL,
`import_id` int(11) NOT NULL,
`status` enum('success','failure') NOT NULL,
`xml_diff` text,
`node_digest` char(32) default NULL,
PRIMARY KEY (`change_event_id`),
KEY `idx_change_events_changed_object_id` (`changed_object_id`),
KEY `idx_change_events_episode_pid` (`episode_pid`),
KEY `fk_import_id` (`import_id`),
KEY `idx_change_event_timestamp_ce_id` (`timestamp`,`change_event_id`),
KEY `idx_change_event_status` (`status`),
CONSTRAINT `fk_change_event_import` FOREIGN KEY (`import_id`) REFERENCES `import` (`import_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code></pre>
<p>Version:</p>
<pre><code>$ mysql --version
mysql Ver 14.12 Distrib 5.0.37, for pc-solaris2.8 (i386) using readline 5.0
</code></pre>
<p>Is there something obvious I'm missing? (Yes, I've already tried "SELECT COUNT(change_event_id)", but there's no performance difference).</p>
| <p>InnoDB uses clustered primary keys, so the primary key is stored along with the row in the data pages, not in separate index pages. In order to do a range scan you still have to scan through all of the potentially wide rows in data pages; note that this table contains a TEXT column.</p>
<p>Two things I would try:</p>
<ol>
<li>run <code>optimize table</code>. This will ensure that the data pages are physically stored in sorted order. This could conceivably speed up a range scan on a clustered primary key.</li>
<li>create an additional non-primary index on just the change_event_id column. This will store a copy of that column in index pages which be much faster to scan. After creating it, check the explain plan to make sure it's using the new index.</li>
</ol>
<p>(you also probably want to make the change_event_id column bigint <em>unsigned</em> if it's incrementing from zero)</p>
|
Testing in ASP.net MVC Beta 1 <p>I'm wring a unit test for a controller and here is my code.</p>
<pre><code>public void DocumentController_IndexMethod_ShouldReturn_Documents()
{
DocumentsController c = new DocumentsController(_repository);
ViewResult result = (ViewResult)c.Index("1");
DocumentsController.DocumentsData data = (DocumentsController.DocumentsData)result.ViewData;
Assert.IsNotNull(data.Documents);
Assert.IsTrue(data.Documents.Count() > 0);
Assert.IsNotNull(result);
}
</code></pre>
<p>I'm basically following along with Rob Conery's asp.net storefront application and realized that I can't use the RenderView method. As shown I have tried the ViewResult method to create an instance of the view. I'm getting this error:
Error 1 Cannot convert type 'System.Web.Mvc.ViewDataDictionary' to 'HomeOwners.Controllers.DocumentsController.DocumentsData' C:\Documents and Settings\drmarshall\My Documents\Visual Studio 2008\Projects\HomeOwners\HomeOwners.Tests\DocumentsControllerTests.cs 61 54 HomeOwners.Tests</p>
<p>Am I using the correct replacement method or am I missing something?</p>
<p>I figured it out.</p>
<pre><code>[TestMethod]
public void DocumentController_IndexMethod_ShouldReturn_Documents()
{
DocumentsController c = new DocumentsController(_repository);
ViewResult result = c.Index("1") as ViewResult;
ViewDataDictionary dictionary = result.ViewData;
DocumentsController.DocumentsData data = (DocumentsController.DocumentsData)dictionary["Documents"];
Assert.IsNotNull(data.Documents);
Assert.IsTrue(data.Documents.Count() > 0);
Assert.IsNotNull(result);
}
</code></pre>
| <p>[TestMethod]
public void DocumentController_IndexMethod_ShouldReturn_Documents()
{
DocumentsController c = new DocumentsController(_repository);</p>
<pre><code> ViewResult result = c.Index("1") as ViewResult;
ViewDataDictionary dictionary = result.ViewData;
DocumentsController.DocumentsData data = (DocumentsController.DocumentsData)dictionary["Documents"];
Assert.IsNotNull(data.Documents);
Assert.IsTrue(data.Documents.Count() > 0);
Assert.IsNotNull(result);
}
</code></pre>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.