instruction
stringlengths 21
27.8k
| chosen
stringlengths 18
28.2k
| rejected
stringlengths 18
33.6k
| __index_level_0__
int64 0
50k
|
|---|---|---|---|
<p>I looked for the name of a procedure, which applies a tree structure of procedures to a tree structure of data, yielding a tree structure of results - all three trees having the same structure. </p>
<p>Such a procedure might have the signature: </p>
<pre>(map-tree data functree)</pre>
<p>Its return value would be the result of elementwise application of functree's elements on the corresponding data elements. </p>
<p>Examples (assuming that the procedure is called map-tree): </p>
<p>Example 1: </p>
<pre>(define *2 (lambda (x) (* 2 x)))
; and similar definitions for *3 and *5
(map-tree '(100 (10 1)) '(*2 (*3 *5)))</pre>
<p>would yield the result <pre>(200 (30 5))</pre></p>
<p>Example 2: </p>
<pre>(map-tree '(((aa . ab) (bb . bc)) (cc . (cd . ce)))
'((car cdr) cadr))</pre>
<p>yields the result <pre>((aa bc) cd)</pre></p>
<p>However I did not find such a function in the SLIB documentation, which I consulted. </p>
<p>Does such a procedure already exist?<br>
If not, what would be a suitable name for the procedure, and how would you order its arguments?</p>
|
<p>I don't have a very good name for the function. I'm pasting my implementation below (I've called it <code>map-traversing</code>; others should suggest a better name). I've made the argument order mirror that of <code>map</code> itself.</p>
<pre><code>(define (map-traversing func data)
(if (list? func)
(map map-traversing func data)
(func data)))
</code></pre>
<p>Using your sample data, we have:</p>
<pre><code>(map-traversing `((,car ,cdr) ,cadr) '(((aa . ab) (bb . bc)) (cc cd . ce)))
</code></pre>
<p>The second sample requires SRFI 26. (Allows writing <code>(cut * 2 <>)</code> instead of <code>(lambda (x) (* 2 x))</code>.)</p>
<pre><code>(map-traversing `(,(cut * 2 <>) (,(cut * 3 <>) ,(cut * 5 <>))) '(100 (10 1)))
</code></pre>
<p>The most important thing is that your functions must all be unquoted, unlike your example.</p>
|
<p>I found that with the follwing definition of map-traversing, you don't need to unquote the functions:</p>
<pre>(define (map-traversing func data)
(if (list? func)
(map map-traversing func data)
(apply (eval func (interaction-environment)) (list data))))</pre>
<p>Note: in my installed version of Guile, due to some reason, only (interaction-environment) does not raise the Unbound variable error. The other environments i.e. (scheme-report-environment 5) and (null-environment 5) raise this error. </p>
<p>Note 2: Subsequently, I found in [1] that for (scheme-report-environment 5) and (null-environment 5) to work, you need first to (use-modules (ice-9 r5rs))</p>
<p>[1]: <a href="http://www.mail-archive.com/bug-guile@gnu.org/msg04368.html" rel="nofollow noreferrer">http://www.mail-archive.com/bug-guile@gnu.org/msg04368.html</a> 'Re: guile -c "(scheme-report-environment 5)" ==> ERROR: Unbound variable: scheme-report-environment'</p>
| 12,380
|
<p>Does anyone know of an IDE for F# development that does not involve me shelling out $300? I will gladly move to F# VS Express if they ever release one, but spending money to just get started with a new language is not in my budget.</p>
|
<p><a href="http://msdn.microsoft.com/en-us/vsx2008/products/bb933751.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/vsx2008/products/bb933751.aspx</a></p>
<p>Visual Studio Shell - Free, and F# supports it out of the box.</p>
<p>(edited)
<a href="http://blogs.msdn.com/dsyme/archive/2008/04/04/tackling-the-f-productization.aspx" rel="noreferrer">http://blogs.msdn.com/dsyme/archive/2008/04/04/tackling-the-f-productization.aspx</a></p>
<p>Theres a link talking about using the Shell and such too</p>
|
<p>start a WebsiteSpark microsoft programm. It is free and for three years you will have access to latest version of visual studio professional. Glad I found it three years ago...</p>
<p><a href="http://www.microsoft.com/web/websitespark/" rel="nofollow">here</a> the link</p>
<p>this is the description of my company just to show you :</p>
<p><em>freelance without any customer just to learn new stuff ;)</em></p>
| 11,849
|
<p>What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?</p>
<p>For example. If I have some Products and I'm pulling from a database</p>
<p>explicit way:</p>
<pre><code>public List<Product> GetProduct(int productId) { // return a List }
public List<Product> GetProductByCategory(Category category) { // return a List }
public List<Product> GetProductByName(string Name ) { // return a List }
</code></pre>
<p>overloaded way:</p>
<pre><code>public List<Product> GetProducts() { // return a List of all products }
public List<Product> GetProducts(Category category) { // return a List by Category }
public List<Product> GetProducts(string searchString ) { // return a List by search string }
</code></pre>
<p>I realize you may get into a problem with <strong>similar signatures</strong>, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to <strong>overload a method</strong> to reduce the number of methods you have and for clarity, <strong>or</strong> should <strong>each method</strong> that filters the data a different way <strong>have a different method name</strong>?</p>
|
<p>Yes, overloading can easily be overused.</p>
<p>I've found that the key to working out whether an overload is warranted or not is to consider the audience - not the compiler, but the maintenance programmer who will be coming along in weeks/months/years and has to understand what the code is trying to achieve.</p>
<p>A simple method name like GetProducts() is clear and understandable, but it does leave a lot unsaid. </p>
<p>In many cases, if the parameter passed to GetProducts() are well named, the maintenance guy will be able to work out what the overload does - but that's relying on good naming discipline at the point of use, which you can't enforce. What you can enforce is the name of the method they're calling.</p>
<p>The guideline that I follow is to only overload methods if they are interchangable - if they do the same thing. That way, I don't mind which version the consumer of my class invokes, as they're equivalent.</p>
<p>To illustrate, I'd happily use overloads for a DeleteFile() method:</p>
<pre><code>void DeleteFile(string filePath);
void DeleteFile(FileInfo file);
void DeleteFile(DirectoryInfo directory, string fileName);
</code></pre>
<p>However, for your examples, I'd use separate names:</p>
<pre><code>public IList<Product> GetProductById(int productId) {...}
public IList<Product> GetProductByCategory(Category category) {...}
public IList<Product> GetProductByName(string Name ) {...}
</code></pre>
<p>Having the full names makes the code more explicit for the maintenance guy (who might well be me). It avoids issues with having signature collisions:</p>
<pre><code>// No collisions, even though both methods take int parameters
public IList<Employee> GetEmployeesBySupervisor(int supervisorId);
public IList<Employee> GetEmployeesByDepartment(int departmentId);
</code></pre>
<p>There is also the opportunity to introduce overloading for each purpose:</p>
<pre><code>// Examples for GetEmployees
public IList<Employee> GetEmployeesBySupervisor(int supervisorId);
public IList<Employee> GetEmployeesBySupervisor(Supervisor supervisor);
public IList<Employee> GetEmployeesBySupervisor(Person supervisor);
public IList<Employee> GetEmployeesByDepartment(int departmentId);
public IList<Employee> GetEmployeesByDepartment(Department department);
// Examples for GetProduct
public IList<Product> GetProductById(int productId) {...}
public IList<Product> GetProductById(params int[] productId) {...}
public IList<Product> GetProductByCategory(Category category) {...}
public IList<Product> GetProductByCategory(IEnumerable<Category> category) {...}
public IList<Product> GetProductByCategory(params Category[] category) {...}
</code></pre>
<p>Code is read a lot more than it is written - even if you never come back to the code after the initial check in to source control, you're still going to be reading that line of code a couple of dozen times while you write the code that follows.</p>
<p>Lastly, unless you're writing throwaway code, you need to allow for other people calling your code from other languages. It seems that most business systems end up staying in production well past their use by date. It may be that the code that consumes your class in 2016 ends up being written in VB.NET, C# 6.0, F# or something completely new that's not been invented yet. It may be that the language doesn't support overloads.</p>
|
<p>yes you can overuse it. In your example it would seem like the first and third would probably return a single item, where the second would return several. If that is correct, then I would call the first and third GetProduct and the second GetProducts or GetProductList</p>
<p>if this is not the case and all three return several (as in if you pass it productID 5, it returns any items with 5 in the productid, or returns any items with the string parameter in its name) then I would call all three GetProducts or GetProductList and override all of them.</p>
<p>In any event, the name should reflect what the function does, so calling it GetProduct (singular) when it returns a list of Products doesn't make a good function name. IMNSHO</p>
| 30,840
|
<p>Say I have two lists:</p>
<pre><code>var list1 = new int[] {1, 2, 3};
var list2 = new string[] {"a", "b", "c"};
</code></pre>
<p>Is it possible to write a LINQ statement that will generate the following list:</p>
<pre><code>var result = new []{
new {i = 1, s = "a"},
new {i = 1, s = "b"},
new {i = 1, s = "c"},
new {i = 2, s = "a"},
new {i = 2, s = "b"},
new {i = 2, s = "c"},
new {i = 3, s = "a"},
new {i = 3, s = "b"},
new {i = 3, s = "c"}
};
</code></pre>
<p>?</p>
<p>Edit: I forgot to mention I didn't want it in query syntax. Anyway, based on preetsangha's answer I've got the following:</p>
<pre><code>var result = list1.SelectMany(i => list2.Select(s => new {i = i, s = s}));
</code></pre>
|
<pre><code>var result = from l1 in list1
from l2 in list2
select new { i = l1, s = l2};
</code></pre>
|
<pre><code>var result = from l1 in list1
from l2 in list2
select new { i = l1, s = l2};
</code></pre>
| 36,835
|
<p>I have this C-code to do multiplications over GF(8):</p>
<pre><code>int32_t GaloisMultiply (int32_t a, int32_t b)
{
int32_t i;
int32_t mask = 0x100;
int32_t y = 0;
for(i=0;i<8;i++)
{
if(b & mask)
{
y ^= a;
}
mask >>= 1;
y <<= 1;
}
if(b & 0x1)
{
y ^= a;
}
return(y);
}
</code></pre>
<p>That's more or less the text-book implementation.</p>
<p>I wonder if I there is a clever optimization for above algorithm if I can assert that a is always b, e.g. I do squaring instead of multiplication. I'm not after a cryptographic use btw. I just want to make use of the fact that x*x in GF(8) interleaves the bits of x with zero bits one by one.</p>
<p>There are already quite clever methods to do the bit interleaving, but since I've found out that x*x in GF(8) does the bit interleaving thing (by accident) I can't stop trying to use it for bit-interleaving optimizations.</p>
<p>Any ideas?</p>
|
<p>Table-based? <a href="http://www.samiam.org/galois.html" rel="nofollow noreferrer">link</a></p>
<p>And when you are limited to x*x, it's a sparse matrix.</p>
<p>Here's another <a href="http://www.cs.utk.edu/~plank/plank/papers/CS-07-593/" rel="nofollow noreferrer">good paper (and a library)</a></p>
|
<p>You could probably write some assembly to do a slightly better job. However, I'd be pretty surprised if this was the bottleneck in your application; have you done any profiling? This function doesn't seem like it's worth optimizing.</p>
| 14,291
|
<p>I have a build server running CruiseControl.NET. It works well for the 7 projects that are configured to run on that server (let's call it server A).</p>
<p>Now I have a new project that I wish to build on a different server (server B), but I want it to appear in the same ccnet dashboard as the existing projects. </p>
<p>How do I configure CCNet for this scenario?</p>
|
<p>In <code>dashboard.config</code> (default location is <code>c:\Program Files\CruiseControl.NET\webdashboard\dashboard.config</code>) take a look at the <a href="http://confluence.public.thoughtworks.org/display/CCNET/Servers+Configuration+Block" rel="nofollow noreferrer">Servers Configuration Block</a>:</p>
<pre><code> <servers>
<server name="local" url="tcp://localhost:21234/CruiseManager.rem"
allowForceBuild="true" allowStartStopBuild="true" />
</servers>
</code></pre>
<p>It allows you to configure the remote servers you want to report on - just add another <code><server /></code> node.
To force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.</p>
|
<p>Duckworth's answer is the one I found via Google. I found the complete story (identifying all protagonists) as:</p>
<p>Open the dashboard.config file. Its default location is \Program Files\CruiseControl.NET\webdashboard. </p>
<p>At the top of dashboard.config, add the extra server. Eg</p>
<p>
</p>
<p>and save the changes.</p>
<p>To force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.</p>
| 34,101
|
<p>This code works in Firefox, Internet Explorer, not in Safari/Chrome:</p>
<pre><code><head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-ui.js"></script>
<script>
function newDiv() {
var div = $('<div id="divNew" style="width: 50px; height: 50px; border: solid 1px; background: Red"></div>');
$('#divParent').append(div);
div.draggable(
{
containment: 'parent'
});
}
</script>
</head>
<body>
<a href="javascript:;" onclick="newDiv()">new div</a>
<div id="divParent" style="width: 500px; height: 500px; border: solid 1px;"></div>
</body>
</code></pre>
<p>In Safari/Chrome, the divNew can only be moved vertically. jQuery's this feature is currently incompatible? I am using 1.5.2 stable version.It can be found here <a href="http://jquery-ui.googlecode.com/files/jquery.ui-1.5.2.zip" rel="nofollow noreferrer">jQuery 1.5.2</a></p>
|
<p>the solution i found is to set the element <code>position: absolute !important</code>, :))</p>
|
<p>To resolve this problem, you must define WMODE diferent to transparent. I just set the wmode=window and this works fine in all browsers.</p>
| 36,244
|
<p>Do you think there is a big difference in for...in and for loops? What kind of "for" do you prefer to use and why?</p>
<p>Let's say we have an array of associative arrays:</p>
<pre><code>var myArray = [{'key': 'value'}, {'key': 'value1'}];
</code></pre>
<p>So we can iterate:</p>
<pre><code>for (var i = 0; i < myArray.length; i++)
</code></pre>
<p>And:</p>
<pre><code>for (var i in myArray)
</code></pre>
<p>I don't see a big difference. Are there any performance issues?</p>
|
<p>The choice should be based on the which idiom is best understood.</p>
<p>An array is iterated using:</p>
<pre><code>for (var i = 0; i < a.length; i++)
//do stuff with a[i]
</code></pre>
<p>An object being used as an associative array is iterated using:</p>
<pre><code>for (var key in o)
//do stuff with o[key]
</code></pre>
<p>Unless you have earth shattering reasons, stick to the established pattern of usage.</p>
|
<p>Be careful!!!
I am using Chrome 22.0 in Mac OS and I am having problem with the for each syntax.</p>
<p>I do not know if this is a browser issue, javascript issue or some error in the code, but it is VERY strange. Outside of the object it works perfectly.</p>
<pre><code>var MyTest = {
a:string = "a",
b:string = "b"
};
myfunction = function(dicts) {
for (var dict in dicts) {
alert(dict);
alert(typeof dict); // print 'string' (incorrect)
}
for (var i = 0; i < dicts.length; i++) {
alert(dicts[i]);
alert(typeof dicts[i]); // print 'object' (correct, it must be {abc: "xyz"})
}
};
MyObj = function() {
this.aaa = function() {
myfunction([MyTest]);
};
};
new MyObj().aaa(); // This does not work
myfunction([MyTest]); // This works
</code></pre>
| 30,073
|
<p>Let's say I do something in Java like:</p>
<pre>
<code>
RemoteResponse response = null;
try {
FutureTask task new FutureTask(....);
executor.execute(task);
response = task.get(1000, TimeUnits.MILLISECONDS);
}
catch( TimeoutException te ) {
<b>
.. should I do something special here? ...
.. what happens to the return value of the task if task.get() throws an exception? ...
.. is it ever garbage collected? ..
</b>
}
</code>
</pre>
<p>My question is does something hold onto RemoteResponse in the case where TimeoutException is thrown? Will it get garbage collected? Do I have to call the cancel() method on the task for that to happen?</p>
|
<p>Edit after the question was revised:</p>
<p><code>response</code> is a reference to a <code>RemoteResponse</code> that <code>task</code> is responsible for allocating. The assignment of the return value from a method won't happen if the method threw an exception, so there is no need for special handling of <code>response</code>.</p>
<p><code>task</code> will be unreferenced when it goes out of scope, either through normal execution or if an exception is thrown.</p>
<p>If the resources allocated by <code>task</code> are well encapsulated, ie there are no externally held references, and are released (<code>close</code>, <code>release</code>, whatever), then there should be no resource leakage. </p>
<p>There's no need to call cancel unless there is some shared resource the <code>task</code> has exclusively or some other consumable resource that the rest of the application needs.</p>
<p>I'd at least log the fact that the task didn't complete in the time allotted. What else you do depends on the requirements of your application.</p>
<p>Note that <code>task</code> will continue executing until completion, regardless of the <code>get</code> call.</p>
|
<p>I think the way to look at the problem is that you need to claim the resource outside of the FutureTask, so that when you do decide to cancel it you can force the reclamation of resources.</p>
<p>so:</p>
<pre><code>Resource res = null;
try {
resource = ResourceAquirer.claim()
FutureTask<?> task = new FutureTask<?>(resource);
executor.execute(task);
response = task.get(1000, TimeUnits.MILLISECONDS);
} catch (Exception e) {
// logging
} finally {
if (resource != null) {
resource.release();
}
}
</code></pre>
<p>This way you can be sure that the resource will be freed. It is really frustrating that all of that cannot be encapuslated inside the future task, but I cannot find proof that calling cancel on a futuretask will ensure that a finally block is invoked inside the FutureTask. (Maybe I'll ask that as another question)</p>
| 35,279
|
<p>OK, I am not sure if the title it completely accurate, open to suggestions!</p>
<p>I am in the process of creating an ASP.NET custom control, this is something that is still relatively new to me, so please bear with me.</p>
<p>I am thinking about the event model. Since we are not using Web Controls there are no events being fired from buttons, rather I am manually calling <strong>__doPostBack</strong> with the appropriate arguments. However this can obviously mean that there are a lot of postbacks occuring when say, selecting options (which render differently when selected).</p>
<p>In time, I will need to make this more Ajax-y and responsive, so I will need to change the event binding to call local Javascript.</p>
<p>So, I was thinking I should be able to toggle the "mode" of the control, it can either use postback and handlle itself, or you can specify the Javascript function names to call instead of the doPostBack.</p>
<ul>
<li>What are your thoughts on this?</li>
<li>Am I approaching the raising of the events from the control in the wrong way? (totally open to suggestions here!)</li>
<li>How would you approach a similar problem?
<hr></li>
</ul>
<h2>Edit - To Clarify</h2>
<ul>
<li>I am creating a custom rendered control (i.e. inherits from WebControl).</li>
<li>We are not using existnig Web Controls since we want complete control over the rendered output.</li>
<li>AFAIK the only way to get a server side event to occur from a custom rendered control is to call doPostBack from the rendered elements (please correct if wrong!).</li>
<li>ASP.NET MVC is not an option.</li>
</ul>
|
<p>You might like to try this <a href="http://www.vim.org/scripts/script.php?script_id=1491" rel="noreferrer">improved Javascript syntax highlighter</a> rather than the one that ships with VIMRUNTIME.</p>
|
<p>For a quick and dirty fix, sometimes I just scroll up and down and the highlighting readjusts. <kbd>Ctrl</kbd>+<kbd>L</kbd> for a screen redraw can also fix it.</p>
| 8,327
|
<p>I think I know the answer, but I would like to bounce around some ideas.</p>
<p>I would like to pass several (in this instance 2) somewhat different pieces of data to a View. My initial thought is simply to wrap-up the various objects into a containing object and pass them along that way. Then from the View, I'd have something like </p>
<pre><code>var objContainer = ViewData.Model;
var thisObject = objContainer.ThisObject;
var thatObject = objContainer.ThatObject;
</code></pre>
<p>and these could be used independently in the Master Page and View Page.</p>
<p>Is that the "best" way?</p>
|
<p>I find it useful to create additional classes dedicated that are to be presented to the Views. I keep them in a separate namespace called 'Core.Presentation' to keep things organized. Here is an example:</p>
<pre><code>namespace Core.Presentation
{
public class SearchPresentation
{
public IList<StateProvince> StateProvinces { get; set; }
public IList<Country> Countries { get; set; }
public IList<Gender> Genders { get; set; }
public IList<AgeRange> AgeRanges { get; set; }
}
}
</code></pre>
<p>Then I make sure that my View is a strongly typed view that uses the generic version of that presentation class:</p>
<pre><code>public partial class Search : ViewPage<SearchPresentation>
</code></pre>
<p>That way in the View, I can use Intellisense and easily navigate through the items.</p>
|
<p>I've got the same dealie going on. Here's my solution (may not be the best practice, but it works for me).</p>
<p>I created a number of "Grouping" classes:</p>
<pre><code>public class Duo<TFirst,TSecond> { /*...*/ }
public class Trio<TFirst,TSecond, TThird> { /*...*/ }
</code></pre>
<p>and a factory object to create them (to take advantage of type inference... some of the TFirsts and TSeconds and TThirds can be LONG)</p>
<pre><code>public static class Group{
public static Duo<TFirst, TSecond> Duo(TFirst first, TSecond second) {
return new Duo<TFirst, TSecond>(first, second);
}
/*...*/
}
</code></pre>
<p>It gives me type safety and intellisense with a minimum of fuss. It just smells because you're grouping together classes that essentially have no real relation between them into a single object. I suppose it might be better to extend the ViewPage class to add a second and third ViewModel, but the way I did it takes lots less work.</p>
| 29,485
|
<p>I just started getting into BizTalk at work and would love to keep using everything I've learned about DDD, TDD, etc. Is this even possible or am I always going to have to use the Visio like editors when creating things like pipelines and orchestrations?</p>
|
<p>You can certainly apply a lot of the concepts of TDD and DDD to BizTalk development. </p>
<p>You can design and develop around the concept of domain objects (although in BizTalk and integration development I often find interface objects or contract first design to be a more useful way of thinking - what messages get passed around at my interfaces). And you can also follow the 'Build the simplest possible thing that will work' and 'only build things that make tests pass' philosophies of TDD.</p>
<p>However, your question sounds like you are asking more about the code-centric sides of these design and development approaches.</p>
<p>Am I right that you would like to be able to follow the test driven development approach of first writing a unti test that exercises a requirement and fails, then writing a method that fulfils the requirement and causes the test to pass - all within a traditional programing language like C#?</p>
<p>For that, unfortunately, the answer is no. The majority of BizTalk artifacts (pipelines, maps, orchestrations...) can only really be built using the Visual Studio BizTalk plugins. There are ways of viewing the underlying c# code, but one would never want to try and directly develop this code.</p>
<p>There are two tools <a href="http://www.codeplex.com/bizunit" rel="nofollow noreferrer">BizUnit</a> and <a href="http://www.codeplex.com/bizunitextensions" rel="nofollow noreferrer">BizUnit Extensions</a> that give some ability to control the execution of BizTalk applications and test them but this really only gets you to the point of performing more controled and more test driven integration tests.</p>
<p>The shapes that you drag onto the Orchestration design surface will largely just do their thing as one opaque unit of execution. And Orchestrations, pipelines, maps etc... all these things are largely intended to be executed (and tested) within an entire BizTalk solution.</p>
<p>Good design practices (taking pointers from approaches like TDD) will lead to breaking BizTalk solutions into smaller, more modular and testable chunks, and are there are ways of testing things like pipelines in isolation. </p>
<p>But the detailed specifics of TDD and DDD in code sadly don't translate.</p>
<p>For some related discussion that may be useful see this question:</p>
<p><a href="https://stackoverflow.com/questions/256897/mocking-webservice-consumed-by-a-biztalk-request-response-port#271044">Mocking WebService consumed by a Biztalk Request-Response port</a></p>
|
<p>You could use BizUnit to create and reuse generic test cases both in code and excel(for functional scenarios)</p>
<p><a href="http://www.codeplex.com/bizunit" rel="nofollow noreferrer">http://www.codeplex.com/bizunit</a></p>
<p>BizTalk Server 2009 is expected to have more IDE integrated testability.</p>
<p>Cheers
Hemil.</p>
| 36,359
|
<p>I am trying to get started writing scalable, telecom-grade applications with Asterisk and Ruby. I had originally intended to use the Adhearsion framework for this, but it does not have the required maturity and its documentation is severely lacking. AsteriskRuby seems to be a good alternative, as it's well documented and appears to be written by Vonage.</p>
<p>Does anyone have experience deploying AGI-based IVR applications? What framework, if any, did you use? I'd even consider a non-Ruby one if it's justified. Thanks!</p>
|
<p>SipX is really the wrong answer. I've written some extremely complicated VoiceXML on SipX 3.10.2 and it's been all for naught since SipX 4 is dropping SipXVXML for an interface that requires IVRs to be compiled JARs. Top that off with Nortel filing bankruptcy, extremely poor documentation on the open-source version, poor compliance with VXML 2.0 (as of 3.10.2) and SIP standards (as of 3.10.2, does not trunk well with ITSPs). I will applaud it for a bangup job doing what it was designed to do, be a PBX. But as an IVR, if I had it to do all over again, I'd do something different. I don't know what for sure, but something different. I'm toying with Trixbox CE now and working on tying it into JVoiceXML or VoiceGlue.</p>
<p>Also, don't read that SipX wiki crap. It compares SipX 3.10 to AsteriskNOW 1 to Trixbox 1. Come on. It's like comparing Mac OS X to Win95! A more realistic comparison would be SipX 4 (due out 1Q 2009) to Asterisk 1.6 and Trixbox 2.6, which would show that they accomplish near identical results except in the arena of scalibility and high-availability; SipX wins at that. But, for maturity and stability, I'd advocate Asterisk.</p>
<p>Also, my real world performance results with SipXVXML:<br />
Dell PowerEdge R200, Xeon Dual Core 3.2GHz, handles 17 calls before jitters.<br />
HP DL380 G4, Dual Xeon HT 3.2 GHz, handles 30 calles before long pauses.</p>
<p>I'll post my findings when I finish evaluating VoiceGlue and JVoiceXML but I think I'm going to end up writing a custom PHP called from AGI since all the tools are native to Asterisk.</p>
|
<p>There really aren't any other frameworks out there. There's of course AGI bindings to every language, but as far as full-fledged frameworks for developing telephony applications, we're just not there yet. At least in the open-source world.</p>
| 12,339
|
<p>How do I programmatically reset the Excel <code>Find and Replace</code> dialog box parameters to defaults ("Find what", "Replace with", "Within", "Search", "Look in", "Match case", "Match entire cell contents")?</p>
<p>I am using <code>Application.FindFormat.Clear</code> and <code>Application.ReplaceFormat.Clear</code> to reset find and replace cell formats.</p>
<p>Interestingly, after using <code>expression.Replace(FindWhat, ReplaceWhat, After, MatchCase, WholeWords)</code>, the <code>FindWhat</code> string shows in the <code>Find and Replace</code> dialog box but not the <code>ReplaceWhat</code> parameter.</p>
|
<p>You can use this macro to reset find & replace. Unfortunately, you have to call them both as there are one or two arguments unique to each, so if you want to reset everything, you're stuck. There is no 'reset', so the only way I have found is to execute a fake find & replace using the default parameters.</p>
<pre><code>Sub ResetFind()
Dim r As Range
On Error Resume Next 'just in case there is no active cell
Set r = ActiveCell
On Error Goto 0
Cells.Find what:="", _
After:=ActiveCell, _
LookIn:=xlFormulas, _
LookAt:=xlPart, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False
Cells.Replace what:="", Replacement:="", ReplaceFormat:=False
If Not r Is Nothing Then r.Select
Set r = Nothing
End Sub
</code></pre>
|
<p>No need to use sendkeys you can easily refer to the values you need to reset the dialog box values.</p>
<pre><code>Sub ResetFindReplace()
'Resets the find/replace dialog box options
Dim r As Range
On Error Resume Next
Set r = Cells.Find(What:="", _
LookIn:=xlFormulas, _
SearchOrder:=xlRows, _
LookAt:=xlPart, _
MatchCase:=False)
On Error GoTo 0
'Reset the defaults
On Error Resume Next
Set r = Cells.Find(What:="", _
LookIn:=xlFormulas, _
SearchOrder:=xlRows, _
LookAt:=xlPart, _
MatchCase:=False)
On Error GoTo 0
End Sub
</code></pre>
| 30,151
|
<p>I would like to be able to embed a command line interpreter inside a dockable window in Visual Studio. Is there any nice way to do this?</p>
|
<p>See the <a href="http://www.codeplex.com/Wiki/View.aspx?ProjectName=VSCmdShell" rel="noreferrer">VS Command shell</a> project</p>
|
<p>Checkout <a href="https://marketplace.visualstudio.com/items?itemName=MadsKristensen.OpenCommandLine" rel="nofollow noreferrer">Open Command Line</a> by Mads Kristensen. <strong>note</strong> it doesn't really "embed" the shell in VS, rather it adds a keyboard shortcut to open the shell at the project directory</p>
<p>it supports bash, powershell, git bash, ...etc</p>
| 8,247
|
<p>I want to update/upgrade the standard Leopard install of Sqlite3 to >3.5 to use the new sqlite_xxx_v2 methods from a Cocoa project.</p>
<p>I can't seem to find any information on how to do this. Does anyone have any tips or a site that outlines the update procedure. </p>
<p>Also is 3.5+ supported on the iPhone. I understand it's embedded so shouldn't be an issue...</p>
|
<p>What you want to do is grab the amalgamation sources from <a href="http://sqlite.org/download.html" rel="noreferrer">http://sqlite.org/download.html</a> . Then just compile that into / add it to your project. You don't want to replace the system sqlite- that'll have unintended consequences in other applications. Plus, I'm pretty sure the system sqlite isn't a stock sqlite... Apple has probably made their own modifications to it that core data relies on.</p>
<p>You can read up on the amalgamation stuff here: <a href="http://sqlite.org/amalgamation.html" rel="noreferrer">http://sqlite.org/amalgamation.html</a> , but in short: '''The amalgamation is a single C code file, named "sqlite3.c", that contains all C code for the core SQLite library and the FTS3 and RTREE extensions'''</p>
<p>I'd also suggest not using the sqlite calls directly, they weren't designed to be used that way (says the author of sqlite). Instead, there are a number of cocoa wrappers out there, including fmdb: <a href="http://code.google.com/p/flycode/source/browse/trunk/fmdb/" rel="noreferrer">http://code.google.com/p/flycode/source/browse/trunk/fmdb/</a> (which I wrote) :)</p>
<p>-gus</p>
|
<p>I don't believe i've updated my version, but it's currently at 3.4.2, and i'm able to use the new methods with the current version.</p>
<p>And i'm running 10.5.5 with the latest (public) iPhone SDK.</p>
| 34,823
|
<p>Banging my head against the wall here. I don't want to reinvent the wheel.</p>
<p>The default Flex 3 classs for PopupButton is a combination of two buttons. One is a normal button with label and/or icon, and the second is the arrow which opens the popup. </p>
<p>My struggle here is that I just want a button with an icon that opens the popup directly, without having to write all the popup handling code all over again. The plan was to override the PopupButton class with, say, a new class called SimplePopupButton. This class would just hide the arrow, and point the button click handler to open the popup.</p>
<p>Seems simple, but I don't see an easy way to do this. Suggestions? Alternatives?</p>
<hr>
<p>[<strong>Edit</strong>] I want a 16x16 icon button that opens a popup. PopupButton shipped with flex has two buttons: "It contains a main button and a secondary button, called the pop-up button, which pops up any UIComponent object when a user clicks the pop-up button." (<a href="http://livedocs.adobe.com/flex/3/langref/index.html" rel="nofollow noreferrer">source</a>). I want the main button to open the popup, and hide the popup-button. (or vice-versa) </p>
|
<p>Have you tried setting a <a href="http://www.adobe.com/devnet/flex/articles/flex_skins.html" rel="nofollow noreferrer">new skin</a>? Not sure if it would work but it would be far easier than trying to write a new control.</p>
|
<p>It's been a while since I did some work with Flex, but here's my idea:
<br/>
Create a new component consisting of a classic button and a list. The component should have two view states. The list should not be visible in the base state, but should become visible when the component enters the other state. The other state is, of course, entered on the click of the button. You can set the list to be initially positioned so that it's bottom left corner is aligned with the buttons's bottom left corner. Then create a transition from base state to the other state that would make the list do a "slide down" as it does in a standard PopuButton control. You can do this by simultaneously using a wipeup effect and a move effect in which you move the list on its y axis until it's top left corner is where it's bottom left corner was. Name the component MyPopupButton or whatever you wish to call it. For returning to the base state simply do a reverse on these effects.
As for the handling code - your app, of course, only needs to know what the user chose from the list, so that's no more code than usual.
<br/>
Hope this was helpful.</p>
| 18,271
|
<p>I have a daily batch process that involves selecting out a large number of records and formatting up a file to send to an external system. I also need to mark these records as sent so they are not transmitted again tomorrow.</p>
<p>In my naive JDBC way, I would prepare and execute a statement and then begin to loop through the recordset. As I only go forwards through the recordset there is no need for my application server to hold the whole result set in memory at one time. Groups of records can be feed across from the database server.</p>
<p>Now, lets say I'm using hibernate. Won't I endup with a bunch of objects representing the whole result set in memory at once?</p>
|
<p>Hibernate does also iterate over the result set so only one row is kept in memory. This is the default. If it to load greedily, you must tell it so.</p>
<p>Reasons to use Hibernate:</p>
<ul>
<li>"Someone" was "creative" with the column names (PRXFC0315.XXFZZCC12)</li>
<li>The DB design is still in flux and/or you want one place where column names are mapped to Java.</li>
<li>You're using Hibernate anyway</li>
<li>You have complex queries and you're not fluent in SQL</li>
</ul>
<p>Reasons <strong>not</strong> to use Hibernate:</p>
<ul>
<li>The rest of your app is pure JDBC</li>
<li>You don't need any of the power of Hibernate</li>
<li>You have complex queries and you're fluent in SQL</li>
<li>You need a specific feature of your DB to make the SQL perform</li>
</ul>
|
<p>If there are possible performance issues then stick with the JDBC code.</p>
<p>There are a number of well known pure SQL optimisations which
which would be very difficult to do in Hibernate.</p>
<p>Only select the columns you use! (No "select *" stuff ).</p>
<p>Keep the SQl as simple as possible. e.g. Dont include small reference tables like currency codes in the join. Instead load the currency table into memory and resolve currency descriptions with a program lookup.</p>
<p>Depending on the DBMS minor re-ordering of the SQL where predicates can have a major effect on performance.</p>
<p>If you are updateing/inserting only commit every 100 to 1000 updates. i.e. Do not commit every unit of work but keep some counter so you commit less often.</p>
<p>Take advantage of the aggregate functions of your database. If you want totals by DEPT code then do it in the SQL with " SUM(amount) ... GROUP BY DEPT ".</p>
| 43,185
|
<p>For example:</p>
<pre><code>me$ FOO="BAR * BAR"
me$ echo $FOO
BAR file1 file2 file3 file4 BAR
</code></pre>
<p>and using the <code>\</code> escape character:</p>
<pre><code>me$ FOO="BAR \* BAR"
me$ echo $FOO
BAR \* BAR
</code></pre>
<p>I'm obviously doing something stupid.</p>
<p>How do I get the output <code>BAR * BAR</code>?</p>
|
<p>Quoting when setting <code>$FOO</code> is not enough. You need to quote the variable reference as well:</p>
<pre><code>me$ FOO="BAR * BAR"
me$ echo "$FOO"
BAR * BAR
</code></pre>
|
<pre><code>echo "$FOO"
</code></pre>
| 12,755
|
<p>I am looking for a way of efficiently specifying a recurring job execution time without having to write an explicit execution time to a datastore. In other words, rather than saying 'job x next runs at 13.00pm on 11.12.08' and then having to update the execution time for the following week once the job has run, I want to be able to say 'job x runs at 13.00pm every thursday'. I need to be able to specify a recurrence range of anything from a few minutes to once per month. My guess is the shorter the recurrence period, the more difficult this becomes. Any ideas?</p>
<p>Note: I'm not looking for advice on the scheduling <strong>mechanism</strong>. I cannot use Windows Scheduler, Cron or create a Windows Service (I have no choice but to use a background thread in ASP.NET). </p>
|
<p>I have seen cron expressions used widely for doing this, it might work well as an internal representation format. </p>
|
<p>I implemented some unattended services (Windows Services written in c#), using cron to manage the scheduling. The pattern is powerful, and flexible. We can create schedules to any time we want, only using the cron expression. Maybe I am wrong, but the only schedule that I think cron doesn't cover is if we want the last day of the month, but this was never a requirement for all services.</p>
<p>I copied the cron algorithm from an article in the internet (open source by Atif Aziz), and implemented in my utility class, working beautifully for years.</p>
<p>See more details in my blog:
<a href="http://blog.robertolopes.com/2010/11/17/crontab-schedule-parser-algorithm/" rel="nofollow">CronTab schedule parser algorithm</a></p>
<p>Cheers!</p>
<p>Roberto</p>
| 44,714
|
<p>I need to grep for lines with bunch of names, say <code>clientLogin=a@yahoo.com</code>, <code>clientLogin=b@gmail.com</code> from a file.txt.</p>
<p>file.txt has junk which is <code>email=a@yahoo.com email=b@gmail.com</code>. I need to filter these out</p>
<p>Once I get these lines I need to grep for gmail and yahoo and get their counts</p>
<pre><code>List l = new ArrayList{a@yahoo.com, b@gmail.com}
def gmail = ['sh','-c','grep "clientLogin="$l.get(0) file.txt' | grep gmail | wc -l ]
def yahoo = ['sh','-c','grep "clientLogin="$l.get(1) file.txt' | grep yahoo| wc -l ]
</code></pre>
<p>This doesn't work. How can I substitute the $l.get(1) value dynamically?</p>
<hr>
<p>the problem is that ${l.get(0)} has to be inside the " ",
i.e.:</p>
<pre><code>def gmail = ['sh','-c','grep "clientLogin=${l.get(0)}" file.txt' | grep gmail | wc -l ]
</code></pre>
<p>so that it will look like:</p>
<pre><code>def gmail = ['sh','-c','grep "clientLogin=a@yahoo.com" file.txt' | grep gmail | wc -l ]
</code></pre>
<p>but <code>clientLogin=${l.get(0)}</code> doesn't produce the result. I am not sure where I am going wrong. </p>
<p>Thanks for your suggestion but it doesn't produce the result, at least when I tried it.</p>
<hr>
<p>file.txt has lot of junk and a pattern something like:</p>
<pre><code>Into the domain clientLogin=a@yahoo.com exit on 12/01/2008 etc..
</code></pre>
<p>hence I do </p>
<pre><code>def ex = ['sh','-c','grep "domain clientLogin=$client" file.txt'| grep "something more" | wc -l]
</code></pre>
<p>that way I can chain the grep as I want and eventually land at the count I need.</p>
<p>I am not sure if I can chain the greps if I use </p>
<pre><code>def ex = ['grep', "$client", 'file.txt']
</code></pre>
<p>thanks for your input.</p>
|
<p>You're already using groovy, does using a regular expression that gives you your answer work?</p>
<pre><code>def file = new File("file.txt")
file.delete() // clear out old version for multiple runs
file << """
foobar clientLogin=a@yahoo.com baz quux # should match a@yahoo.com
foobar email=a@yahoo.com baz quux
foobar email=b@gmail.com bal zoom
foobar clientLogin=a@yahoo.com baz quux # should match a@yahoo.com
foobar clientLogin=b@gmail.com bal zoom # should match b@gmail.com
foobar email=b@gmail.com bal zoom
"""
def emailList = ["a@yahoo.com", "b@gmail.com"]
def emailListGroup = emailList.join('|')
def pattern = /(?m)^.*clientLogin=($emailListGroup).*$/
def resultMap = [:]
(file.text =~ pattern).each { fullLine, email ->
resultMap[email] = resultMap[email] ? resultMap[email] + 1 : 1
}
assert resultMap["a@yahoo.com"] == 2
assert resultMap["b@gmail.com"] == 1
</code></pre>
<p>That feels cleaner to me than trying to shell out to a process and working with that, plus it only will pick out the exact lines with "clientLogin=(email)" that you're looking for.</p>
|
<p>You need {}'s around the variable expression. That is:</p>
<pre><code> "${l.get(0)}"
</code></pre>
<p>See <a href="http://groovy.codehaus.org/JN1525-Strings" rel="nofollow noreferrer">Groovy String</a> documentation for more information. </p>
<p>Full example:</p>
<pre><code>List l = new ArrayList{a@yahoo.com, b@gmail.com}
def gmail = ['sh','-c','grep "clientLogin="${l.get(0)} file.txt' | grep gmail | wc -l ]
def yahoo = ['sh','-c','grep "clientLogin="${l.get(1)} file.txt' | grep yahoo| wc -l ]
</code></pre>
| 45,638
|
<p>Here is the sample:</p>
<pre><code> Dim TestString As String = "Hello," & Chr(0) & "World"
MsgBox(TestString, , "TestString.Length=" & TestString.Length.ToString)
</code></pre>
<p>Result - Messagebox shows "Hello," with title says TestString.Length=12 </p>
<p>I guess the chr(0) is treated as the end of zero terminated string, but it's not what i want. </p>
<p>What the right method to operate with Chr(0) ?</p>
<hr>
<p>I've also tried this in asp.net with no avail. I'm sending the string over a socket. My problem is that when I'm debugging it the whole string doesn't add up. I need to send them a rather large string for it. What comes up really on the message window doesn't bother me. I used the above as an example. I just need when putting the multiple variables that it adds correctly to the string. Another example of it would be </p>
<pre><code>"SCORE".ToString.PadRight(8, chr(0)) & "3.0".ToString.PadRight(10, chr(0)) & "0".ToString.PadRight(1, "0")
</code></pre>
<p>the expected value would score3.00</p>
<p>What I get though is score3.0</p>
|
<p>The sample code in the questioner's example ("SCORE".ToString...) works fine for me in a console application. The VS2005 debugger does not show the string correctly, but it outputs to the console just fine. So, my feeling is either that you think it's incorrect because the debugger wrongly says so or your output string is not long enough to include all the padding.</p>
|
<p>chr(0) is null. Are you after a single space chr(32) or just type vblf or after Enter(Return) chr(13) or type vbcrlf</p>
| 21,547
|
<p>I want to implement my own clustering algorithm using this Virtual Earth javascript API: <a href="http://msdn.microsoft.com/en-us/library/cc966716.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/cc966716.aspx</a>
However, the VE engine calls my cluster function once for every shape in the layer. This makes it very slow!
It seems to me that VE should put all the shapes into a layer, then ask my function to cluster them. Not repeatedly call cluster!</p>
<p>Why does the VE engine do this? Is there another way to do client side clustering with this API?</p>
<p>More Information: I am loading the shapes from a GeoRSS feed.</p>
|
<p>The CRLF pair is the expected end-of-line (EOL) marker on most internet protocols.</p>
<p>Here, Postel's "Robustness Principle" should apply. Be liberal in what you accept, but strict in what you send. So, be prepared to receive just a LF, but if you're sending data use whatever the relevant standards require.</p>
|
<p>This is not a language compatibility issue, but either a file issue or a protocol issue. File-wise: Unix uses \n as a carriage return, Windows uses \r\n and I think MacOS used (not sure about now) \r. Many 'cross platform' languages abstract this in a platform dependant variable. Protocol-wise: what the protocol specifies.</p>
| 32,116
|
<p>Is the jQuery intellisense plugin available for Visual Studio now?</p>
|
<p>Yes, it is. <a href="http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx" rel="nofollow noreferrer">Rich Intellisense for JQuery</a>.</p>
|
<p>Yes. <a href="http://mwtech.blogspot.com/2009/05/how-to-get-jquery-intellisense-working.html" rel="nofollow noreferrer">This blog</a> taught me how to do it.</p>
| 37,253
|
<p>I have a csv imported into my Hyperion v8.3 bqy file. I have some custom columns and a pivot already created. I just want to refresh the data. In the past, I would hit Process Current and it would direct me to my computer and I could select the csv file to update from. Now it will not do that. It doesn't go to my computer at all.</p>
<p>Any ideas?</p>
|
<p>It appears that you're using schtasks.exe - it took me longer to figure that out than to find an answer! More details please! :) I found an answer with <a href="http://tinyurl.com/6z6m8j" rel="nofollow noreferrer">a quick google search</a></p>
<p>Try this code:</p>
<pre><code>string args = "/CREATE /RU SYSTEM /SC " + taskSchedule + " /MO " + taskModifier + " /SD " + taskStartDate + " /ST " + taskStartTime + " /TN " + taskName + " /TR \"\\\"" + taskSource + "\""
</code></pre>
<p>It's adding a \" to the front of the TR parameter value.</p>
|
<p>Put a batch file in a location that does not have spaces.</p>
<p>In the batch file, run the program commands that have spaces.</p>
| 47,037
|
<p>I am trying to get a simple demo started with ActiveMQ that will demonstrate a TCP to TCP route. I am coding the endpoints and routes in a camel context in my activemq.xml configuration file.</p>
<pre><code><camelContext id="camel" xmlns="http://activemq.apache.org/camel/schema/spring">
<package>org.myorg.codec</package>
<endpoint id="listener_A" uri="mina:tcp://localhost:42000?sync=false&amp;textline=true"/>
<endpoint id="listener_B" uri="mina:tcp://localhost:42001?sync=false&amp;textline=true"/>
<route>
<from uri="activemq:listener_A"/>
<to uri="activemq:listener_B"/>
</route>
<route>
<from uri="activemq:listener_B"/>
<to uri="activemq:listener_A"/>
</route>
</camelContext>
</code></pre>
<p>Any idea why this doesn't work?</p>
<p>The AMQ server does not seem to be opening a listening port.</p>
<p>Edit: The intent here, as a simple demonstation, is to connect to ActiveMQ with two telnet terminals (A and B) and be able to route messages from one to another through the message queue server. Later, I may try filtering or routing based on content.</p>
|
<p>I'm a bit confused by your configuration file. What exactly are you trying to do? </p>
<p>You've defined 2 endpoints for using MINA (which won't use ActiveMQ at all); then you are using a route from an ActievMQ queue listener_A to listener_B then listener_B to listener_A (which is a recursive loop).</p>
<p>Maybe if you start describing what you want to do we can figure out what the XML should look like.</p>
<p>Incidentally if you just want to refer to endpoints you've defined, use the <em>ref="name"</em> attribute rather than <em>uri="..."</em>.</p>
<p>e.g.</p>
<pre><code><route>
<from ref="listener_A"/>
<to ref="listener_B"/>
</route>
</code></pre>
<p>All that being said - you tend to get better & faster support on Camel via the <a href="http://activemq.apache.org/camel/discussion-forums.html" rel="nofollow noreferrer">Camel User Forum</a></p>
|
<p>More on this:</p>
<p>When the endpoint is defined as a mina tcp connection, it cannot be identified as "activemq::listener_A" </p>
<pre><code><endpoint id="listener_A" uri="mina:tcp://localhost:42000?sync=false&amp;textline=true"/>
</code></pre>
<p>this is wrong:</p>
<pre><code> <from uri="activemq:listener_A"/>
</code></pre>
<p>this works: </p>
<pre><code> <from ref="listener_A"/>
</code></pre>
<p>so does this:</p>
<pre><code> <from ref="mina:tcp://localhost:42000?sync=false&amp;textline=true"/>
</code></pre>
| 33,256
|
<p>I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.</p>
<p>What is going on?</p>
<p>VB.Net version - fails:</p>
<pre class="lang-vb prettyprint-override"><code><TestFixture()> _
Public Class TestClass
<Test()> _
Public Sub EventTest()
Dim eventClass As New EventClass
Dim eventRaised As Boolean = False
AddHandler eventClass.AnEvent, Function() (eventRaised = True)
eventClass.RaiseIt()
Assert.IsTrue(eventRaised)
End Sub
End Class
Public Class EventClass
Public Event AnEvent()
Public Sub RaiseIt()
RaiseEvent AnEvent()
End Sub
End Class
</code></pre>
<p>C# version - passes:</p>
<pre><code>[TestFixture]
public class TestClass
{
[Test]
public void EventTest()
{
var eventClass = new EventClass();
var eventRaised = false;
eventClass.AnEvent += () => { eventRaised = true; };
eventClass.RaiseIt();
Assert.IsTrue(eventRaised);
}
}
public class EventClass
{
public delegate void EventHandler();
public event EventHandler AnEvent;
public void RaiseIt()
{
AnEvent();
}
}
</code></pre>
|
<blockquote>
<p><strong>Note:</strong> This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10</p>
</blockquote>
<p>The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression <code>eventRaised = true</code> is being interpreted as a boolean expression rather than an assignment i.e. is evaluating to false rather than setting to true.</p>
<p>Further details on <a href="http://msdn.microsoft.com/en-us/library/bb531253.aspx" rel="noreferrer">MSDN</a>.</p>
<p>I'm don't think the c# pattern for testing events used in the example can be done in VB.Net without introducing another function e.g.</p>
<pre class="lang-vb prettyprint-override"><code><TestFixture()> _
Public Class Test
<Test()> _
Public Sub EventTest()
Dim eventClass As New EventClass
Dim eventRaised As Boolean = False
AddHandler eventClass.AnEvent, Function() (SetValueToTrue(eventRaised))
eventClass.RaiseIt()
Assert.IsTrue(eventRaised)
End Sub
Private Function SetValueToTrue(ByRef value As Boolean) As Boolean
value = True
Return True
End Function
End Class
Public Class EventClass
Public Event AnEvent()
Public Sub RaiseIt()
RaiseEvent AnEvent()
End Sub
End Class
</code></pre>
|
<p>WPF controls that have popups require an instance of the WPF Application Object. In a WPF application, this is automatically created. This is not the case in a WinForm application. For this reason, this object must be created manually. The Application also must be set to remain open until it is shut down through code, otherwise it will shut automatically when the WinForm applications determines it is no longer needed. The following code will open the Application object in a WinForm and keep it open until it is closed. Shutting down the Application object when the WinForm closes is the recommended approach.</p>
<pre><code> Dim app As System.Windows.Application = New System.Windows.Application With {
.ShutdownMode = Windows.ShutdownMode.OnExplicitShutdown
}
AddHandler Closed, Sub()
app.Shutdown()
End Sub
</code></pre>
| 25,078
|
<p>The heart of any good web app is it's offline capability and JavaScript functionality. Currently what tools and wrappers are availability for the desktop web app maker to cross over to the mobile market? What would be the necessary read ups for such a team?</p>
<p>Clarifications:
I am searching for information on how much offline capabilities and JavaScript functionality has improved on the Mobile phones. I know that the term 'mobile phones' are too broad. I am aware of offline solutions like Gears, Adobe AIR, Silverlight etc. But are these really for mobile phones? </p>
<p>How much has JavaScript improved on Mobile Webkit Browsers such as iPhone and Symbians? OperaMini also claims some JavaScript functionality.</p>
|
<p>I'm not totally sure I understand your question, but you'll probably want to take a look at the <a href="http://developer.apple.com/iphone/" rel="nofollow noreferrer">iPhone Dev Center</a> and the <a href="http://code.google.com/android/" rel="nofollow noreferrer">Google Android SDK</a> to start. <a href="http://na.blackberry.com/eng/developers/resources/" rel="nofollow noreferrer">Blackberry</a> also has a Development Program. Beyond that, you may want to look into <a href="http://www.w3schools.com/wap/" rel="nofollow noreferrer">WAP and WML</a>. <a href="http://gears.google.com/" rel="nofollow noreferrer">Google Gears</a>, <a href="http://www.adobe.com/products/air/" rel="nofollow noreferrer">Adobe Air</a>, and <a href="http://www.mozilla.org/projects/xul/" rel="nofollow noreferrer">Mozilla's XUL</a> will give you some offline capability, but to my knowledge they won't wrap an existing desktop app and make it available for the web.</p>
|
<blockquote>
<p>The heart of any good web app is it's offline capability and JavaScript functionality.</p>
</blockquote>
<p>You are talking about Single Page webapps like GMail right? Then you will probably need a Mashup platform (<a href="http://en.wikipedia.org/wiki/Mashup_(web_application_hybrid)#Mashup_editors" rel="nofollow noreferrer">good starting point</a> here).</p>
<p>I don't know which of these support mobile. Probably none because Javascript support on mobiles is basically zero.</p>
| 17,306
|
<p>I'm writing a program that uses <a href="http://msdn.microsoft.com/en-us/library/dd145102(VS.85).aspx" rel="nofollow noreferrer"><code>SetWindowRgn</code></a> to make transparent holes in a window that belongs to another process. (This is done only when the user explicitly requests it.)</p>
<p>The program has to assume that the target window may already have holes which need to be preserved, so before it calls <code>SetWindowRgn</code>, it calls <a href="http://msdn.microsoft.com/en-us/library/dd144950(VS.85).aspx" rel="nofollow noreferrer"><code>GetWindowRgn</code></a> to get the current region, then combines the current region with the new one and calls <code>SetWindowRgn</code>:</p>
<pre><code>HRGN rgnOld = CreateRectRgn ( 0, 0, 0, 0 );
int regionType = GetWindowRgn ( hwnd, rgnOld );
</code></pre>
<p>This works fine in XP, but the call to <code>GetWindowRgn</code> fails in Vista. I've tried turning off Aero and elevating my thread's privilege to <code>SE_DEBUG_NAME</code> with <a href="http://msdn.microsoft.com/en-us/library/aa375202(VS.85).aspx" rel="nofollow noreferrer"><code>AdjustTokenPrivileges</code></a>, but neither helps.</p>
<p>GetLastError() doesn't seem to return a valid value for GetWindowRgn -- it returns 0 on one machine and 5 (Access denied) on another.</p>
<p>Can anyone tell me what I'm doing wrong or suggest a different approach? </p>
|
<p>Are you sure your window <em>has</em> a region? Most top-level windows in XP do, simply because the default theme uses them for round corners... but this is still a bad assumption to be making, and may very well not hold once you get to Vista.</p>
<p>If you haven't set a region yet, and the call fails, use a sensible default (the window rect) and don't let it ruin your life. Now, if <code>SetWindowRgn()</code> fails... </p>
|
<p>You mention that you're trying to get the region of the window of <strong>another process</strong>. Vista tightened up the security of a lot of cross-process Win32 calls. I can't find any documentation one way or the other for <code>GetWindowRgn()</code>, but you could test it simply enough. Make a simple project that sets it's own region, and try to use your original app to get the simple app's region. If it works, then it's just going to be annoying and people can't use your app on just anything. If it doesn't work, there's a chance that your app won't work at all on Vista.</p>
| 17,462
|
<p>Say I have a Student table, it's got an int ID. I have a fixed set of 10 multiple choice questions with 5 possible answers. I have a normalized answer table that has the question id, the Student.answer (1-5) and the Student.ID</p>
<p>I'm trying to write a single query that will return all scores over a certain pecentage. To this end I wrote a simple UDF that accepts the Student.answers and the correct answer, so it has 20 parameters.</p>
<p>I'm starting to wonder if it's better to denormalize the answer table, bring it into my applcation and let my application do the scoring.</p>
<p>Anyone ever tackle something like this and have insight? </p>
|
<p>If I understand your schema and question correctly, how about something like this:</p>
<pre><code>select student_name, score
from students
join (select student_answers.student_id, count(*) as score
from student_answers, answer_key
group by student_id
where student_answers.question_id = answer_key.question_id
and student_answers.answer = answer_key.answer)
as student_scores on students.student_id = student_scores.student_id
where score >= 7
order by score, student_name
</code></pre>
<p>That should select the students with a score of 7 or more, for example. Just adjust the where clause for your purposes.</p>
|
<p>The architecture you are talking about could become very cumbersome in the long run, and if you need to change the questions it means more changes to the UDF you are using.</p>
<p>I would think you could probably do your analysis in code without necessarily de-normalizing your database. De-normalization could also lend to inflexibility, or at least added expense to update, down the road.</p>
| 4,243
|
<p>I'm 3D printing almost 2 years, and I expected to have better result after changing to complete smooth rods with new bearings.</p>
<p>I have a problem with my Z axis giving me inconsistent prints; I already replaced the leadscrews, E3D clone with Bowden tube, I decided to replace all smooth rods on all axis and also the bearings. After I replaced all this, my prints are still bad, also I'm very dissapointed with the results after the replacements. I have checked all I could think of; PID tuning, belts, ....) but I'm running out of ideas.</p>
<p><a href="https://i.stack.imgur.com/33DQZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/33DQZ.jpg" alt="inconsistent print layer results"></a></p>
<p>Printing settings:</p>
<ul>
<li>print speed is 40mm/s, </li>
<li>retraction is 3mm at 30mm/s, </li>
<li>extruder 205°C for the first layer, then 200°C</li>
</ul>
|
<p>From the pictures can be seen that you have good lead screws as there is no cyclic anomaly/wobble present at the side. It appears as though the lines at the sides of the print are more or less random X/Y positional inaccurate.</p>
<p>These lines can be caused by various reasons. From what is read you tried to improve the mechanical system by upgrading the hardware. It could still be the case that there is still some backlash or play left in the system (e.g. I had once had too much tolerance on the holes of the linear shafts in the printed X-Z mounts causing similar problems). Vibration should be looked into also, e.g. do you have a binding bearing or a large mass on the printer that interacts with the carriage movement like a spool holder on top of your frame. Or maybe the micro-stepping does not work optimally, so check the stepper driver currents.</p>
<p>If it is no mechanical issue, it could be that you are facing inconsistent extrusion caused by variation in filament thickness or gear slipping or too much tension on the filament by friction in unspooling. Or else a hotend temperature variation. Maybe insulation on the hotend helps.</p>
|
<p>From the pictures can be seen that you have good lead screws as there is no cyclic anomaly/wobble present at the side. It appears as though the lines at the sides of the print are more or less random X/Y positional inaccurate.</p>
<p>These lines can be caused by various reasons. From what is read you tried to improve the mechanical system by upgrading the hardware. It could still be the case that there is still some backlash or play left in the system (e.g. I had once had too much tolerance on the holes of the linear shafts in the printed X-Z mounts causing similar problems). Vibration should be looked into also, e.g. do you have a binding bearing or a large mass on the printer that interacts with the carriage movement like a spool holder on top of your frame. Or maybe the micro-stepping does not work optimally, so check the stepper driver currents.</p>
<p>If it is no mechanical issue, it could be that you are facing inconsistent extrusion caused by variation in filament thickness or gear slipping or too much tension on the filament by friction in unspooling. Or else a hotend temperature variation. Maybe insulation on the hotend helps.</p>
| 1,075
|
<p>I'm planning to write a program in Ruby to analyse some data which has come back from an online questionnaire. There are hundreds of thousands of responses, and each respondent answers about 200 questions. Each question is multiple-choice, so there are a fixed number of possible responses to each.</p>
<p>The intention is to use a piece of demographic data given by each respondent to train a system which can then guess that same piece of demographic data (age, for example) from a respondent who answers the same questionnaire, but doesn't specify the demographic data.</p>
<p>So I plan to use a vector (in the mathematical sense, not in the data structure sense) to represent the answers for a given respondent. This means each vector will be large (over 200 elements), and the total data set will be huge. I plan to store the data in a MySQL database.</p>
<p>So. 2 questions:</p>
<ol>
<li><p>How should I store this in the database? One row per response to a single question, or one row per respondent? Or something else?</p></li>
<li><p>I'm planning to use something like the k-nearest neighbour algorithm, or a simple machine learning algorithm like a naive bayesian classifier to learn to classify new responses. Should I manipulate the data purely through SQL or should I load it into memory and store it in some kind of vast array?</p></li>
</ol>
|
<p>First thing that comes to mind: Storing it in Memory can be absolutely reasonable for processing purposes. Lets say you reserve one byte for each answer, you have a million responses and 200 questions, then you have a 200 MB array. Not small but definitely not memory exhausting on a modern desktop, even with a 32 bit OS.</p>
<p>As for the database I think you should have three tables. One for the respondent with the demographical data, one for the questions, and, since you have a n:m relation between these tables, a third one with the Respondent-ID, the Question-ID and the Answercode.</p>
<p>If you don't need additional data for the questions (like the question-text or something) you can even optimize away the question table.</p>
|
<p>I'm not a great database person, so I'll just answer #2:</p>
<p>If you'd really like to save on memory (or foresee a situation where there will be a lot more data) you could take the best of both worlds: Use ruby as essentially a data-mining tool. Have it pull some of the data from the DB, then write the results back to the DB (probably under a different table or database altogether). This has the benefit of only using as much memory as you want it to.</p>
| 17,386
|
<p>I have a rather simple scenario where I have two tables in which I want to add data. They are managed with primary key/foreign key. I want to add new data into TABLE A and then retrieve the Id and insert into TABLE B. </p>
<p>I can certainly do it with a stored procedure, but I'm looking at trying to do it using Linq. </p>
<p>What is the best approach ? </p>
<p>I can certainly get the ID and do two separate inserts but that doesn't certainly seem to be a very good way of doing things.</p>
<pre><code>db.Table.InsertOnSubmit(dbObject);
db.SubmitChanges();
Int32 id = dbOject.Id;
//Rest of the code
</code></pre>
<p>Any way to elegantly do this?</p>
|
<p>Do you have the relationship defined between the 2 tables in the object relational designed? If so, you can have linq take care of assigning the ID property of the second table automatically.</p>
<p>Example...<br/>
Table A – Order<br/>
OrderId<br/>
OrderDate<br/><br/>
Table B – Order Item<br/>
OrderItemId<br/>
OrderId<br/>
ItemId<br/><br/></p>
<p>Code (Using LINQ-to-SQL):</p>
<pre><code>Order order = new Order();
Order.OrderDate = DateTime.Now();
dataContext.InsertOnSubmit(order);
OrderItem item1 = new OrderItem();
Item1.ItemId = 123;
//Note: We set the Order property, which is an Order object
// We do not set the OrderId property
// LINQ will know to use the Id that is assigned from the order above
Item1.Order = order;
dataContext.InsertOnSubmit(item1);
dataContext.SubmitChanges();
</code></pre>
|
<p>hi i insert data into three table using this code </p>
<pre><code> Product_Table AddProducttbl = new Product_Table();
Product_Company Companytbl = new Product_Company();
Product_Category Categorytbl = new Product_Category();
// genrate product id's
long Productid = (from p in Accountdc.Product_Tables
select p.Product_ID ).FirstOrDefault();
if (Productid == 0)
Productid++;
else
Productid = (from lng in Accountdc.Product_Tables
select lng.Product_ID ).Max() + 1;
try
{
AddProducttbl.Product_ID = Productid;
AddProducttbl.Product_Name = Request.Form["ProductName"];
AddProducttbl.Reorder_Label = Request.Form["ReorderLevel"];
AddProducttbl.Unit = Convert.ToDecimal(Request.Form["Unit"]);
AddProducttbl.Selling_Price = Convert.ToDecimal(Request.Form["Selling_Price"]);
AddProducttbl.MRP = Convert.ToDecimal(Request.Form["MRP"]);
// Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl );
// genrate category id's
long Companyid = (from c in Accountdc.Product_Companies
select c.Product_Company_ID).FirstOrDefault();
if (Companyid == 0)
Companyid++;
else
Companyid = (from Ct in Accountdc.Product_Companies
select Ct.Product_Company_ID).Max() + 1;
Companytbl.Product_Company_ID = Companyid;
Companytbl.Product_Company_Name = Request.Form["Company"];
AddProducttbl.Product_Company = Companytbl;
//Genrate Category id's
long Categoryid = (from ct in Accountdc.Product_Categories
select ct.Product_Category_ID).FirstOrDefault();
if (Categoryid == 0)
Categoryid++;
else
Categoryid = (from Ct in Accountdc.Product_Categories
select Ct.Product_Category_ID).Max() + 1;
Categorytbl.Product_Category_ID = Categoryid;
Categorytbl.Product_Category_Name = Request.Form["Category"];
AddProducttbl.Product_Category = Categorytbl;
Accountdc.Product_Tables.InsertOnSubmit(AddProducttbl);
Accountdc.SubmitChanges();
}
catch
{
ViewData["submit Error"] = "No Product Submit";
}
</code></pre>
| 36,592
|
<p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p>
<ul>
<li><p>text files, which would involve some sort of read line function.</p></li>
<li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li>
</ul>
|
<p>There are three ways to do this, depending on your needs. You could use the old-school C way and call <code>fopen</code>/<code>fread</code>/<code>fclose</code>, or you could use the C++ fstream facilities (<code>ifstream</code>/<code>ofstream</code>), or if you're using MFC, use the <code>CFile</code> class, which provides functions to accomplish actual file operations.</p>
<p>All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:</p>
<pre><code>int nsize = 10;
std::vector<char> somedata(nsize);
ifstream myfile;
myfile.open("<path to file>");
myfile.read(somedata.data(), nsize);
myfile.close();
</code></pre>
<p>Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).</p>
|
<p>fstream are great but I will go a little deeper and tell you about <a href="http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization" rel="nofollow noreferrer">RAII</a>.</p>
<p>The problem with a classic example is that you are forced to close the file by yourself, meaning that you will have to bend your architecture to this need. RAII makes use of the automatic destructor call in C++ to close the file for you.</p>
<p><strong>Update</strong>: seems that std::fstream already implements RAII so the code below is useless. I'll keep it here for posterity and as an example of RAII. </p>
<pre><code>class FileOpener
{
public:
FileOpener(std::fstream& file, const char* fileName): m_file(file)
{
m_file.open(fileName);
}
~FileOpeneer()
{
file.close();
}
private:
std::fstream& m_file;
};
</code></pre>
<p>You can now use this class in your code like this:</p>
<pre><code>int nsize = 10;
char *somedata;
ifstream myfile;
FileOpener opener(myfile, "<path to file>");
myfile.read(somedata,nsize);
// myfile is closed automatically when opener destructor is called
</code></pre>
<p>Learning how RAII works can save you some headaches and some major memory management bugs.</p>
| 2,943
|
<p>So, in reading this site, it seems that the shop in which I work does a lot of things wrong and some things right. How can I improve the code that I work with from my colleagues? The only thing I can think of is to lead by example - start using Boost, etc. Any other thoughts? </p>
|
<p>You probably have to look more closely at what it is your shop does wrong and what they do right. What can you actually change there? <em>What can you change about your own practices that will improve your skills or that of your team?</em> It can be difficult to realize change in an entrenched shop. Try proposing code reviews (on your code first), which could lead to discussion.</p>
<p>For tangible items, I'd look at <a href="http://www.aristeia.com/" rel="nofollow noreferrer">Scott Meyers</a>' Effective C++, etc. Develop your skillset and you will either help improve others around you or move on to a shop that will. Also, look at the Gang of Four's <a href="https://rads.stackoverflow.com/amzn/click/com/0201633612" rel="nofollow noreferrer" rel="nofollow noreferrer">Design Patterns</a> book.</p>
|
<p>Leading by example is always a good thing, though convincing others that your example is better than however they're currently doing it is not so easy. Constructive criticism through code review is probably your best bet for gently suggesting alternative approaches to how your colleagues work. The key point is to convince others that what you're proposing really is better in a tangible way that they can appreciate.</p>
| 19,394
|
<p>Do bubble sorts have any real world use? Every time I see one mentioned, it's always either:</p>
<ol>
<li>A sorting algorithm to learn with.</li>
<li>An example of a sorting algorithm <em>not</em> to use.</li>
</ol>
|
<p>It depends on the way your data is distributed - if you can make some assumptions.</p>
<p>One of the best links I've found to understand when to use a bubble sort - or some other sort, is this - an animated view on sorting algorithms:</p>
<p><a href="http://www.sorting-algorithms.com/" rel="noreferrer">http://www.sorting-algorithms.com/</a></p>
|
<p>Mostly <em>nothing</em>. Use QuickSort or SelectionSort instead...!</p>
| 34,811
|
<p>How to serve users a dynamically generated ZIP archive in Django?</p>
<p>I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.</p>
|
<p>The solution is as follows.</p>
<p>Use Python module <a href="https://docs.python.org/3/library/zipfile.html" rel="noreferrer">zipfile</a> to create zip archive, but as the file specify <a href="https://docs.python.org/3/library/io.html#io.StringIO" rel="noreferrer">StringIO</a> object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in <code>HttpResponse</code> with mimetype set to <code>application/x-zip-compressed</code> (or at least <code>application/octet-stream</code>). If you want, you can set <code>content-disposition</code> header, but this should not be really required.</p>
<p>But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics.</p>
|
<p>Can't you just write a link to a "zip server" or whatnot? Why does the zip archive itself need to be served from Django? A 90's era CGI script to generate a zip and spit it to stdout is really all that's required here, at least as far as I can see.</p>
| 9,299
|
<p>I'm trying to generate synthetic Javascript events in an Internet Explorer extension, and I'm having trouble getting the fromElement property to stick. Here's an excerpt of my code:</p>
<pre><code>MsHtml.IHTMLDocument4 doc4 = ... // the document object
Object o = null;
MsHtml.IHTMLEventObj2 eObj =
(MsHtml.IHTMLEventObj2)doc4.CreateEventObject(ref o);
// string that specifies the from element, e.g. "document.getElementById('id1')":
string locator = ...
object from = doc4.Script.GetType().InvokeMember("eval",
BindingFlags.InvokeMethod,
null,
doc4.Script,
new object[] { locator });
// from now holds a ref to an object that implements the IHTMLElement interface
eObj.fromElement = from;
IHTMLElement el = eObj.fromElement;
// el == null
</code></pre>
<p>What am I doing wrong here? eObj.fromElement should be equal to from, but it doesn't seem to be getting set.</p>
|
<p>A lot of this depends on what you want to do with the data. I assume render it.</p>
<p>Flash probably would be the simplest solution. It's a common enough add-on that just about everyone should have it by now; so you're not running much of a risk for incompatibility.</p>
<p>JavaScript just hasn't been considered much of a good platform for binary data handling -- so, there hasn't been too much development in the realm. I don't think you're going to find a lot of help for what you want. Especially when you get the point of rendering -- unless you can <em>maybe</em> convert every binary file to a <a href="http://en.wikipedia.org/wiki/Canvas_(HTML_element)" rel="nofollow noreferrer">canvas script</a>, since it's about the only dynamic imaging available in JavaScript.</p>
<p>IE might actually be the exception, since you might be able to use some ActiveX objects to accomplish this for a few file types. But, then you cut out most other browser.</p>
|
<p>You can use Base64 to convert the binary to text and send that to the browser. With IE you can convert it directly to binary, but I'm not sure if you can do it with Firefox and others. I did see jscripts for Base64 enflate/deflate and a script named base64.js which probably does the conversion as well.</p>
<p>However, you are probably better off converting the binary data into JSON and using AJAX to transfer the data and then processing it as a javascript object in the browser. The web server would be responsible for acquiring the data and converting it to JSON, so you should be able to process the binary regardless of which programming language you are using.</p>
| 44,450
|
<p>An abstract class can only be used as a base class which is extended by some other class, right? The constructor(s) of an abstract class can have the usual access modifiers (public, protected, and private (for internal use)). Which of <code>protected</code> and <code>public</code> is the correct access modifier to use, since the abstract type seems to indicate that technically a public constructor will act very much protected? Should I just use protected on all my constructors?</p>
|
<blockquote>
<blockquote>
<p>since the abstract type seems to indicate that technically a public constructor will act very much protected</p>
</blockquote>
<p>This is not correct. An abstract class cannot be directly instatiated by calling its constructor, however, any concrete implementation <em>will inherit the abstract class' methods and visibility</em></p>
<p>So the abstract class can certainly have public constructors.</p>
</blockquote>
<p>Actually, the abstract class's constructor can only be called from the implementation's constructor, so there is no difference between it being public or protected. E.g.:</p>
<pre><code>public class Scratch
{
public static abstract class A
{
public A( int i ) {}
}
public static class B extends A
{
private B() { super(0); };
}
}
</code></pre>
|
<blockquote>
<p>since the abstract type seems to indicate that technically a public constructor will act very much protected</p>
</blockquote>
<p>Umm... for abstract classes this constructor scope [public or protected] is not of much difference since the instantiation is not allowed [even if public]. Since it is meant to be invoked by the subclass, it can invoke either public or protected constructor seamlessly.</p>
<p>Its completely on choice what to use. I generally prefer public as it is in most of the cases.</p>
| 32,604
|
<p>I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values.</p>
<p>I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available.</p>
<p>My current solution looks something like this:</p>
<pre><code>enum MetaValueType
{
MetaChar,
MetaString,
MetaShort,
MetaInt,
MetaFloat,
MetaDouble
};
union MetaUnion
{
char cValue;
short sValue;
int iValue;
float fValue;
double dValue;
};
class MetaValue
{
...
private:
MetaValueType ValueType;
std::string StringValue;
MetaUnion VariantValue;
};
</code></pre>
<p>The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for.</p>
<p>I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above.</p>
<p>Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?</p>
|
<p>As of C++17, there’s <a href="http://en.cppreference.com/w/cpp/utility/variant" rel="noreferrer"><code>std::variant</code></a>.</p>
<p>If you can’t use that yet, you might want <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/variant.html" rel="noreferrer">Boost.Variant</a>. A similar, but distinct, type for modelling polymorphism is provided by <a href="http://en.cppreference.com/w/cpp/utility/any" rel="noreferrer"><code>std::any</code></a> (and, pre-C++17, <a href="http://www.boost.org/doc/libs/1_36_0/doc/html/any.html" rel="noreferrer">Boost.Any</a>).</p>
<p>Just as an additional pointer, you can look for “<a href="https://stackoverflow.com/q/5450159/1968">type erasure</a>”.</p>
|
<p>Although the question had been answered for a long time, for the record I would like to mention that <a href="http://doc.qt.io/qt-5/qvariant.html" rel="nofollow noreferrer">QVariant</a> in the Qt libraries also does this.</p>
<blockquote>
<p>Because C++ forbids unions from including types that have non-default
constructors or destructors, most interesting Qt classes cannot be
used in unions. Without QVariant, this would be a problem for
QObject::property() and for database work, etc.</p>
<p>A QVariant object holds a single value of a single type() at a time.
(Some type()s are multi-valued, for example a string list.) You can
find out what type, T, the variant holds, convert it to a different
type using convert(), get its value using one of the toT() functions
(e.g., toSize()) and check whether the type can be converted to a
particular type using canConvert().</p>
</blockquote>
| 25,634
|
<p>I have a project with literally thousands of image files that aren't being used. The main problem is that they are intermixed with images that are.</p>
<p>Is there a way to get a list of all project artifacts which aren't referenced?</p>
<p><strong>EDIT</strong>: Assuming I don't have access to the web logs... Is there an option?</p>
|
<p>Basically, no there isn't a straightforward, works-always way. You could build image-references based on user input or other context. So spidering your website means that you have to execute all code paths, otherwise you might throw away stuff that you actually need.</p>
<p>But now for the specific case of Chris, you could use multiple approaches:</p>
<ul>
<li>search image for image for
occurrences in your code (maybe
automate this with visual studio
plug-ins or so) </li>
<li>remove everything
and start browsing your website, add
all images that are not found. (this
depends on the ratio of not used
images versus used images) </li>
<li>search
your code for all occurrences of
.png, .jpg, .gif (and so on) and
keep those images, throw everything
else away. </li>
<li>...</li>
</ul>
|
<ul>
<li><p>access your web server logs, parse for GET's of the desired file pattern, unique them, then compare them against your reference list.</p></li>
<li><p>or, look at the file access dates (you may need to turn on this feature if you are sysop)</p></li>
</ul>
| 31,357
|
<p>I've been doing PHP/MySQL websites with shared hosting providers for the last couple years. The day-to-day process is basically:</p>
<ul>
<li>develop in Eclipse, one website per folder</li>
<li>upload via FileZilla, one website per folder</li>
<li>use PHPMyAdmin to create and manage your local and online databases and transfer data from one to another</li>
<li>to backup the online database I do dump of the database tables into script and copy them locally</li>
</ul>
<p><strong>I now want to build websites with ASP.NET with SQL Server 2008</strong> on shared hosting providers, and am trying to get into this new paradigm, hopefully some of you can give me some pointers based on your experience and tell me what I am not doing optimally:</p>
<ul>
<li>I've installed both the Visual Web Developer 2008 Express as well as the full version of Visual Studio 2008, both seem to be full-featured tools for developing ASP.NET sites. <strong>In terms of websites at shared hosting providers, what can you do with the full version that you can't do with the express version?</strong></li>
<li>I use FileZilla to upload my sites, which seems to work fine. <strong>Do you use an external FTP program to upload your sites or do you use the "Publish" or "FTP Website" in the above IDEs?</strong></li>
<li>I installed SQL Server 2008 Management Studio and can now issue SQL commands to my online SQL Server database (although I strangely can't see my database in the list on the left, I can still access it, I assume this is some rights issue with my provider, www.domainbox.de, but this provider told me to use their online manager instead, which is called "ASP.NET Enterprise Manager" which is extremely simple but at least has a "Query Box" which allows me to send queries to my database.) <strong>Is this "ASP.NET Enterprise Manager" standard with ASP.NET hosters or is there something else that is better, e.g. where you could edit your data in the grid, etc.?</strong> And I assume that with most providers you are able to manage your online SQL Server database with SQL Server Management Studio, is that correct? (I remember back in 2001 managing online SQL Server 2000 database at a shared hosting provider with Enterprise Manager and it would take literally 10 minutes for me to see my database on the left because it listed out the other 800 customer databases as well -- hopefully this has been solved by now).</li>
<li><strong>How do you backup your data in your online database to local storage?</strong> (currently I would have to write code that output my data to some other format, e.g. XML or SQL Script)</li>
<li>And after you make a number of structural and data changes to your local database, <strong>how do you transfer those changes and the new data to your online database?</strong> (I had to install SSMS Tools [<a href="http://www.ssmstoolspack.com]" rel="nofollow noreferrer">http://www.ssmstoolspack.com]</a> to be able to dump my data into a script so that I could get it back into my online database).</li>
</ul>
<p>So, although I've gotten most things to work, I feel like there must be better ways to go about this, better providers, better tools, etc. <strong>Would like to hear some "best practices" advice from anyone who works with ASP.NET, SQL Server and shared hosting.</strong></p>
|
<p>For the most part, what you're doing now will work with an asp.net website.</p>
<p>For your development environment, I don't think you will be limited by using Visual Web Developer 2008 express for what you want to do. Here is a microsoft page that compares every version of visual studio 2008, including Visual Web Developer 2008 Express: <a href="http://msdn.microsoft.com/en-us/vstudio/products/cc149003.aspx" rel="nofollow noreferrer">Visual Studio 2008 Product Comparison</a></p>
<p>For deploying your website over the net, I would generall stick to deploying manually. You can use some of the automated stuff in visual studio, but your deployment will tend to be a little slower. After compiling your application, it will then delete every file in your destination website, and upload everying from scratch (uncompressed I think). Your whole site will be down while this happens. When you deploy manually you can upload just the changed files, or everything in a compressed format.</p>
<p>Regarding the SQL server, many shared hosting services will let you connect with some sort of local SQL management tool. However, connecting this way generally uses a lot of bandwidth so they throttle the allowed bandwidth for this way down. This is probably the performance issues you previously saw. If you can get by with it, I would use their hosted SQL tools for most of your work, but then use the management studio for anything it can't handle.</p>
<p>For backing up your SQL server, if your host doesn't have a way for you to perform an automatic backup then you will have to do something yourself. I would first check to see if they will allow you to at least run a SQL backup command. This will generate a .bak file of your database, but on the local database server. Most places will work with you on this, since many customers need this.</p>
<p>For applying changes to your database, your best bet is to script all of the changes into one sql script and run it using the remote SQL management tool. These aren't hard to write, and there are a few tools out there that will help you with it. I personally like to use Visio. It lets me compare two databases (local and remote) then generate a script to apply to the remote one with all the changes.</p>
<p>Good luck</p>
|
<p>As far as capabilities of VS Express vs Standard - Standard is still the better tool. It gives you a richer debugging experience, broader support for solutions/projects dependencies among other things.</p>
<p>These things still matter even when doing shared hosting b/c you absolutely need to debug your app (client and server side). You can do this adequately with Express with some caveats (cant attach to an arbitrary process, client side javascript debugging is a pain), Standard makes this MUCH easier.</p>
<p>For publishing/deploying - I would recommend '<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en" rel="nofollow noreferrer">Web Depoyment Projects</a>' - an MSBuild extension that you can download from MS. This gives you a lot of customizability of how you want to build and deploy your website - which can include sending it to an FTP site. If you have ever used MSBuild and like it - Web Deployment Projects are the easiest hook to extend your build process with an ASP.NET website.</p>
| 40,542
|
<p>I was browsing <a href="https://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers">this thread</a>, which has good recommendation but a bit too general for me.</p>
<p>So, if anyone has a collection of nice game programming feeds,please share them. :)</p>
<p>(both general and specific topics are welcome)</p>
|
<p>My first suggestion would be to use a drop-in logging tool like log4net, which will make formatting much more automatic.</p>
<p>If you are going to go the route of two files (and I agree with Craig that a database is probably a better choice,) you can probably save yourself a lot of heartache by having one file that is as sparse as you can make it for later fast searches and one that holds all the information in one place (metadata and data) rather than creating a metadata-only format.</p>
|
<p>If you are catpuring logging information for future searching and anaylsis perhaps a database would be a better answer. </p>
<p>As for your solution. Flat files do not scale well at all where as a database scale much better. I wouldn't split the files either, that just compounds the scalability issue. If you have to use a flat file I would probably try keeping the meta data in a csv (less over head) and the data in a series of files indexed by the csv file. That way all the data doesn't impact your index file. Just my thoughts.</p>
| 7,348
|
<p>What is the easiest way to match non-ASCII characters in a regex? I would like to match all words individually in an input string, but the language may not be English, so I will need to match things like ü, ö, ß, and ñ. Also, this is in Javascript/jQuery, so any solution will need to apply to that. </p>
|
<p>This should do it:</p>
<pre><code>[^\x00-\x7F]+
</code></pre>
<p>It matches any character which is not contained in the <a href="http://en.wikipedia.org/wiki/American_Standard_Code_for_Information_Interchange" rel="noreferrer">ASCII character set</a> (0-127, i.e. 0x0 to 0x7F). </p>
<p>You can do the same thing with Unicode:</p>
<pre><code>[^\u0000-\u007F]+
</code></pre>
<p>For unicode you can look at this 2 resources:</p>
<ul>
<li><a href="http://www.unicode.org/charts/" rel="noreferrer">Code charts</a> list of Unicode ranges </li>
<li><a href="http://kourge.net/projects/regexp-unicode-block" rel="noreferrer">This tool</a> to create a regex filtered by Unicode block.</li>
</ul>
|
<p>I had a problem with <strong>\p</strong> working as expected, so I just used a different strategy like:</p>
<pre><code>([^\t]+)\t
</code></pre>
<p>Find anything that is not a tab character until the next tab character... obviously this depends on your search source, but you get the idea. Now I don't have to figure out what unicode characters work and don't work etc.</p>
| 18,078
|
<p>How do I make <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>-<a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="noreferrer">Vim</a> never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like <a href="http://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> does?</p>
<p>Also, how do I save these settings so I never have to input them again?</p>
<p>I've seen other questions related to this, but it always seems to be a little off from what I want.</p>
|
<p>As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your <a href="https://stackoverflow.com/questions/10921441/where-is-my-vimrc-file"><code>.vimrc</code></a>):</p>
<pre><code>filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
</code></pre>
<hr />
<strike>
In your [.vimrc:][1] file:
<pre><code>set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
</code></pre>
<p>The help files take a bit of time to get used to, but the more you read, the better Vim gets:</p>
<pre><code>:help smartindent
</code></pre>
<p>Even better, you can embed these settings in your source for portability:</p>
<pre><code>:help auto-setting
</code></pre>
<p>To see your current settings:</p>
<pre><code>:set all
</code></pre>
<p>As <a href="https://stackoverflow.com/users/18038/graywh">graywh</a> points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:</p>
<pre><code>:help C-indenting
</code></pre>
</strike>
|
<p>Firstly, do not use the <kbd>Tab</kbd> key in Vim for manual indentation. Vim has a pair of commands in insert mode for manually increasing or decreasing the indentation amount. Those commands are <kbd>Ctrl-T</kbd> and <kbd>Ctrl-D</kbd>. These commands observe the values of <code>tabstop</code>, <code>shiftwidth</code> and <code>expandtab</code>, and maintain the correct mixture of spaces and tabs (maximum number of tabs followed by any necessary number of spaces).</p>
<p>Secondly, these manual indenting keys don't have to be used very much anyway if you use automatic indentation.</p>
<p>If <kbd>Ctrl-T</kbd> instead of <kbd>Tab</kbd> bothers you, you can remap it:</p>
<pre><code>:imap <Tab> ^T
</code></pre>
<p>You can also remap <kbd>Shift-Tab</kbd> to do the <kbd>Ctrl-D</kbd> deindent:</p>
<pre><code>:imap <S-Tab> ^D
</code></pre>
<p>Here ^T and ^D are literal control characters that can be inserted as <kbd>Ctrl-V</kbd><kbd>Ctrl-T</kbd>.</p>
<p>With this mapping in place, you can still type literal Tab into the buffer using <kbd>Ctrl-V</kbd><kbd>Tab</kbd>. Note that if you do this, even if <code>:set expandtab</code> is on, you get an unexpanded tab character.</p>
<p>A similar effect to the <code><Tab></code> map is achieved using <code>:set smarttab</code>, which also causes backspace at the front of a line to behave smart.</p>
<p>In <code>smarttab</code> mode, when <kbd>Tab</kbd> is used not at the start of a line, it has no special meaning. That's different from my above mapping of <kbd>Tab</kbd> to <kbd>Ctrl-T</kbd>, because a <kbd>Ctrl-T</kbd> used anywhere in a line (in insert mode) will increase that line's indentation.</p>
<p>Other useful mappings may be:</p>
<pre><code>:map <Tab> >
:map <S-Tab> <
</code></pre>
<p>Now we can do things like select some lines, and hit <kbd>Tab</kbd> to indent them over. Or hit <kbd>Tab</kbd> twice on a line (in command mode) to increase its indentation.</p>
<p>If you use the proper indentation management commands, then everything is controlled by the three parameters: <code>shiftwidth</code>, <code>tabstop</code> and <code>expandtab</code>.</p>
<p>The <code>shiftwidth</code> parameter controls your indentation size; if you want four space indents, use <code>:set shiftwidth=4</code>, or the abbreviation <code>:set sw=4</code>.</p>
<p>If only this is done, then indentation will be created using a mixture of spaces and tabs, because <code>noexpandtab</code> is the default. Use <code>:set expandtab</code>. This causes tab characters which you type into the buffer to expand into spaces, and for Vim-managed indentation to use only spaces.</p>
<p>When <code>expandtab</code> is on, and if you manage your indentation through all the proper Vim mechanisms, the value of <code>tabstop</code> becomes irrelevant. It controls how tabs appear if they happen to occur in the file. If you have <code>set tabstop=8 expandtab</code> and then sneak a hard tab into the file using <kbd>Ctrl-V</kbd><kbd>Tab</kbd>, it will produce an alignment to the next 8-column-based tab position, as usual.</p>
| 29,034
|
<p>We would like to have the FormsCookieName of FormsCookiePath change per instance of our application. We have an application which has multiple instances on 1 server/domainname. Because of this we can only work in 1 application at the same time, since the cookies will overwrite eachother. Same for the Sessions btw.</p>
<p>Is there a way to dynamicly, for example in the Global.asax Application_Start, change this name? This would be usefull as we keep a license name in each application which could be used as the basis for the CookieName.</p>
<p>We already work with Web.config and extra files to overwrite Web.config values in external files using: <code><appSettings file="Web.AppSettings.Config"></code></p>
<p>But this requires manual actions which can be forgotten and are redundant since the settings can be retrieved from the database.</p>
<p>Thanks.</p>
|
<p>According to <a href="http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.formscookiename.aspx" rel="nofollow noreferrer">MSDN</a>, the FormsAuthentication.FormsCookieName property that stores the cookie name is a read-only property. This property must be read from the web.config.</p>
<p>Each instance will need a separate name in the web.config. I suggest including the name of the authentication cookie in your existing change management system.</p>
|
<p>I had similar situation, I did the following. In the Application_Start, I checked to see if my cookie name needed change. This would occur after a new deployment for all applications where I have the same web.config for all.</p>
<p><pre><code>
protected void Application_Start(object sender, EventArgs e)
{
// determine unique cookie name per application
string cookieName = ...
// Get the web.config forms settings
Configuration c = WebConfigurationManager.OpenWebConfiguration("~");
AuthenticationSection auth = c.GetSection("system.web/authentication")
as AuthenticationSection;
// See if we have mismatch in web.config or in Forms cookiename
if (auth != null && auth.Forms != null &&
(auth.Forms.Name != cookieName
|| FormsAuthentication.FormsCookieName != cookieName
)
)
{
// Assign value in web.config for future restarts
auth.Forms.Name = cookieName;
// would be nice if this restarted the app, but it doesn't appear to
c.Save();
// This seems to restart the app
System.Web.HttpRuntime.UnloadAppDomain();
}
...
}
</pre></code></p>
<p>The web.config is modified on the application start and then the web app is restarted. Next time the web app comes up, cookie names are in sync and the reset code is skipped.</p>
| 33,179
|
<p>I have a coworker who is planning a database for a new app that will have several tables with over 30 fields each. Is this excessive? Maybe I'm just not enterprisey enough to understand. </p>
<p>Edit: Also, a lot of the fields are option-type sort of things (like on a request form, would you like your widget to be yellow or green, he has a field for 'colour' with an enum). It's quite likely that these will be added to or removed over time. I haven't really done database design and try to stay away from it myself, so maybe I'm being completely stupid, but surely there's a better way of doing this??</p>
|
<p>Database tables can legitimately have 30 or more fields in them. What you need to look at is the normalization of the data and whether that normalization makes any sense. It will normally change in the future, as well. But, you want to try to minimize that.</p>
<p>For instance, if you have a table that has addresses in it, do you include the city, state, and zip code fields in that table? Or, do you only include one field that "points" to a record in a separate table for those values? The separate table would contain unique city, state, zip code combinations. The effect of splitting the data into two tables is a reduction in the amount of data stored (most likely but not absolute) but a bit of added complexity when you go to run queries against the database. Now, you have to deal with 2 tables instead of just one. But, on the bright side, it's much cleaner, and much smaller (likely).</p>
<p>The real answer is it's okay to leave the city-state-zip data in the address table in the right circumstances. Or, you might want to "normalize" it out. Both are okay.</p>
<p>Find a good database administrator and hire them short term to review the plan, if it's in the budget. It will pay off in the long run.</p>
|
<p>A tell-tale sign is just what you said. He has fields that should in theory be split out into a different table. Another giveaway is the presence of many optional fields.</p>
<p>I'd say that a course in database design is in order for your DB "Expert". And I'd suggest that you brush up on it as well...it can only help you grow in your career :)</p>
| 27,166
|
<p>I'm trying to provide a link to my company's website from a Windows Form. I want to be well behaved and launch using the user's preferred browser.</p>
<p>What is the best way to open a URL in the user's default browser from a Windows Forms application?</p>
|
<p>This <a href="http://support.microsoft.com/kb/320478" rel="noreferrer">article</a> will walk you through it.</p>
<p>Short answer:</p>
<pre><code>ProcessStartInfo sInfo = new ProcessStartInfo("http://mysite.com/");
Process.Start(sInfo);
</code></pre>
|
<p>The above approach is perfect, I would like to recommend this approach to where you can pass your parameters.</p>
<pre><code>Process mypr;
mypr = Process.Start("iexplore.exe", "pass the name of website");
</code></pre>
| 8,246
|
<p>I have a very simple mapping function called "BuildEntity" that does the usual boring "left/right" coding required to dump my reader data into my domain object. (shown below) My question is this - If I don't bring back every column in this mapping as is, I get the "System.IndexOutOfRangeException" exception and wanted to know if ado.net had anything to correct this so I don't need to bring back every column with each call into SQL ... </p>
<p>What I'm really looking for is something like "IsValidColumn" so I can keep this 1 mapping function throughout my DataAccess class with all the left/right mappings defined - and have it work even when a sproc doesn't return every column listed ...</p>
<pre><code>Using reader As SqlDataReader = cmd.ExecuteReader()
Dim product As Product
While reader.Read()
product = New Product()
product.ID = Convert.ToInt32(reader("ProductID"))
product.SupplierID = Convert.ToInt32(reader("SupplierID"))
product.CategoryID = Convert.ToInt32(reader("CategoryID"))
product.ProductName = Convert.ToString(reader("ProductName"))
product.QuantityPerUnit = Convert.ToString(reader("QuantityPerUnit"))
product.UnitPrice = Convert.ToDouble(reader("UnitPrice"))
product.UnitsInStock = Convert.ToInt32(reader("UnitsInStock"))
product.UnitsOnOrder = Convert.ToInt32(reader("UnitsOnOrder"))
product.ReorderLevel = Convert.ToInt32(reader("ReorderLevel"))
productList.Add(product)
End While
</code></pre>
|
<p>Also check out this <a href="http://www.madprops.org/blog/another-idbcommand-extension-fill/" rel="noreferrer">extension method I wrote</a> for use on data commands:</p>
<pre><code>public static void Fill<T>(this IDbCommand cmd,
IList<T> list, Func<IDataReader, T> rowConverter)
{
using (var rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
list.Add(rowConverter(rdr));
}
}
}
</code></pre>
<p>You can use it like this:</p>
<pre><code>cmd.Fill(products, r => r.GetProduct());
</code></pre>
<p>Where "products" is the IList<Product> you want to populate, and "GetProduct" contains the logic to create a Product instance from a data reader. It won't help with this specific problem of not having all the fields present, but if you're doing a lot of old-fashioned ADO.NET like this it can be quite handy.</p>
|
<p>Why don't you use LinqToSql - everything you need is done automatically. For the sake of being general you can use any other <a href="http://en.wikipedia.org/wiki/Object-relational_mapping" rel="nofollow noreferrer">ORM tool</a> for .NET</p>
| 4,218
|
<p>Does anywone know when a UnknownMessageReceived event on a WCF ServiceHost will be fired?</p>
<p>I have some code where I capture the Faulted en UnknownMessageReceived event but even when I post a wrong message to a particular service I never get the event.</p>
<p>Jochen</p>
|
<p>I ran into this event when I, incorrectly specified an address like this:
<a href="http://localhost:4000/SomeService//mex" rel="nofollow">http://localhost:4000/SomeService//mex</a></p>
<p><strong>Note the double forward slash</strong></p>
<p>The service was hosted in a WPF application. Because of that I also found out that this event is raised on a different thread than the main/ui thread. </p>
|
<p>I guess (not sure though) it means that you get (back) a message that is not defined in your contract.</p>
| 26,797
|
<p>I like to read about new and clever algorithms. And I like to think out of the box, so all kinds of algorithms from all fields of computation are welcome.</p>
<p>From time to time I read research papers to keep up with the current research and expand my horizon. I also like to learn new tricks. Unfortunately I tend to concentrate only on my field of interest, so I miss a lot of usefull stuff.</p>
<p>Let's just not post mainstream things. Instead write about something special that made you think: "Wow - now <em>that's</em> a clever solution!".</p>
|
<p>I'll start with something everyone can use: introspective sort. <a href="http://en.wikipedia.org/wiki/Introsort" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Introsort</a> </p>
<p>A new sort algorithms that combines the best of quick, insertion and heap sort. To be exact it's not a new algorithm by itself but a <strong>very</strong> clever combination. </p>
<p>You get the speed of quick-sort up to the point where the quick-sort runs into the degenerated O(n²) case. That gets detected for almost no cost. The remaining partition get sorted using heap- or merge-sort. This not only avoids the degenerated case but creates an clear defined upper bound for stack-usage as well. </p>
<p>Insertion sort takes - as usual - care about all small partitions that are left over from the quick-sort pass. </p>
<p>For me that was a new discovery because I stopped to use quick-sort for my applications. </p>
<p>I do a lot of work on embedded devices and I do have to care about stack usage. Using quick-sort was always a bit risky because the faint chance that it runs amok on the stack. Even if you know that with the current data everything will be fine you never know if someone later cut'n'pastes your code into a different project and uses it for data it was never ment for. </p>
<p>Thanks to introspective sort I now have full control over the stack usage and get a performance boost as well. </p>
|
<p>I found this very useful proof that a^n = b^n + c^n but only for n=2.<br>
Unfortunately this comment box is too small to contain it!</p>
| 20,786
|
<p>Is there a way to change the color of the background for a MDIParent windows in MFC (2005)?</p>
<p>I have tried intercepting ON_WM_CTLCOLOR AND ON_WM_ERASEBKGND but neither work. OnEraseBkgnd does work, but then it gets overwritten by the standard WM_CTL color.</p>
<p>Cheers</p>
|
<p>The CMDIFrameWnd is actually covered up by another window called the MDIClient window. Here is a Microsoft article on how to subclass this MDIClient window and change the background colour. I just tried it myself and it works great.</p>
<p><a href="http://support.microsoft.com/kb/129471" rel="nofollow noreferrer">http://support.microsoft.com/kb/129471</a></p>
|
<p>Just guessing here, but try handling ON_WM_PAINT.</p>
| 24,373
|
<p>I have a web app which connects to a server using a TCP connection and reads a binary document which it then writes to its response object. In other words it's transferring a file from a backend server using a custom protocol and returning that file to its client through HTTP.</p>
<p>The server sends a status code and a mime type, which I read successfully and then writes the contents of the file and closes the socket. This seems to work fine.</p>
<p>The client (a C# web app), reads the data:</p>
<pre><code> private NetworkStream stream_;
public void WriteDocument(HttpResponse response)
{
while (stream_.DataAvailable)
{
const int bufsize = 4 * 1024;
byte[] buffer = new byte[bufsize];
int nbytes = stream_.Read(buffer, 0, bufsize);
if (nbytes > 0)
{
if (nbytes < bufsize)
Array.Resize<byte>(ref buffer, nbytes);
response.BinaryWrite(buffer);
}
}
response.End();
}
</code></pre>
<p>This seems to always exit the read loop before all the data has arrived. What am I doing wrong?</p>
|
<p>I would use the <code>OutputStream</code> directly with a general-purpose function. With the <code>Stream</code>, you can control <code>Flush</code>.</p>
<pre><code> public void WriteDocument(HttpResponse response) {
StreamCopy(response.OutputStream, stream_);
response.End();
}
public static void StreamCopy(Stream dest, Stream src) {
byte[] buffer = new byte[4 * 1024];
int n = 1;
while (n > 0) {
n = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, n);
}
dest.Flush();
}
</code></pre>
|
<p>Not sure how things work in .Net, but in most environments I've worked in Read() returns 0 bytes when the connection is closed. So you'd do something like:</p>
<pre>
char buffer[4096];
int num_read;
while ( num_read = src.Read(sizeof(buffer)) > 0 )
{
dst.Write(buffer, num_read);
}
</pre>
| 13,634
|
<p>I have one aspx page with some controls.
Also i have one DIV which is dynamically populated from AJAX call.
This AJAX call return couple of controls, for example HtmlInputText1 and HtmlInputText2.</p>
<p>When page is submitted, I can get values from this controls through Request.Form.
If possible access to the attributes of this control on pege code behind (for example HtmlInputText1.Height, etc). </p>
<p>I think that is impossible, but I am not sure.
I can use hidden field. Is any other way?</p>
|
<p>The data you want the server to know can be set by the javascript within the form.
Then You can process postback data for the target values manually.</p>
<p>You can write some javascript which modify the value of the server control within browser.</p>
<pre><code><script language="javascript" type="text/javascript">
function changeValue() {
var txtControlClient = document.getElementById('<%= txtControl.ClientID %>');
txtControlClient.value = "modified text";
}
</script>
</code></pre>
<p>In the expected event, you call changeValue() function before the postback, then you can just use server control object txtControl to obtain the value or property you have altered.</p>
|
<blockquote>
<p>The data you want the server to know
can be set by the javascript within
the form. Then You can process
postback data for the target values
manually.</p>
</blockquote>
<p>How to make this?</p>
| 30,046
|
<p>Is there something like the Python descriptor protocol implemented in other languages? It seems like a nice way to increase modularity/encapsulation without bloating your containing class' implementation, but I've never heard of a similar thing in any other languages. Is it likely absent from other languages because of the lookup overhead?</p>
|
<p>I've not heard of a direct equivalent either. You could probably achieve the same effect with macros, especially in a language like Lisp which has extremely powerful macros.</p>
<p>I wouldn't be at all surprised if other languages start to incorporate something similar because it is so powerful.</p>
|
<p>Ruby and C# both easily let you create accessors by specifying getter/setter methods for an attribute, much like in Python. However, this isn't designed to naturally let you write the code for these methods in another class the way that Python allows. In practice, I'm not sure how much this matters, since every time I've seen an attribute defined through the descriptor protocol its been implemented in the same class.</p>
<p>EDIT: Darn my dyslexia (by which I mean careless reading). For some reason I've always read "descriptor" as "decorator" and vice versa, even when I'm the one typing both of them. I'll leave my post intact since it has valid information, albeit information which has absolutely nothing to do with the question.</p>
<p>The term "decorator" itself is actually the name of a design pattern described in the famous "Design Patterns" book. The Wikipedia article contains many examples in different programming languages of decorator usage: <a href="http://en.wikipedia.org/wiki/Decorator_pattern" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Decorator_pattern</a></p>
<p>However, the decorators in that article object-oriented; they have classes implementing a predefined interface which lets another existing class behave differently somehow, etc. Python decorators act in a functional way by replacing a function at runtime with another function, allowing you to effectively modify/replace that function, insert code, etc.</p>
<p>This is known in the Java world as Aspect-Oriented programming, and the AspectJ Java compiler lets you do these kinds of things and compile your AspectJ code (which is a superset of Java) into Java bytecode.</p>
<p>I'm not familiar enough with C# or Ruby to know what their version of decorators would be.</p>
| 5,443
|
<p>When I create an Issue Tracking list in SharePoint, I am unable to remove the Categories choice field that it adds by default as part of the Issue content type. I looked in the list definition but I can't find anything explicit about not allowing the column to be deleted. Does anybody know why the Delete button isn't showing up? Is there a way to delete this field?</p>
|
<p>Toni's solution did work, but be careful- this will also remove the category field from EVERY ISSUES TRACKING LIST being used currently and any future ones created.</p>
|
<p>I know that I have had a similar issue with field in a variety of fields where once the field is added, it is not possible to remove it. </p>
<p>Sometimes it is possible to create code to delete the field, but in most of the situations I have come across we have had to hide the field to prevent it from appearing.</p>
<p>This requires moving to using Powershell and the SharePoint object model to make the changes.</p>
<p>In most of our implementations, we have found it much better to create a custom solution with a custom feature that adds the custom lists and fields using the XML format for doing this. A list template can then be create exactly for what you need.</p>
<p>Doing it this way gives us more control over the result in a repeatable manner.</p>
| 15,123
|
<p>An instance of class A instantiates a couple of other objects, say for example from class B:</p>
<pre><code>$foo = new B();
</code></pre>
<p>I would like to access A's public class variables from methods within B.</p>
<p>Unless I'm missing something, the only way to do this is to pass the current object to the instances of B:</p>
<pre><code>$foo = new B($this);
</code></pre>
<p>Is this best practice or is there another way to do this?</p>
|
<p>That looks fine to me, I tend to use a rule of thumb of "would someone maintaining this understand it?" and that's an easily understood solution.</p>
<p>If there's only one "A", you could consider using the registry pattern, see for example <a href="http://www.phppatterns.com/docs/design/the_registry" rel="nofollow noreferrer">http://www.phppatterns.com/docs/design/the_registry</a></p>
|
<p>Similar to what Paul said, if there's only one A, you can implement that as a singleton. You can then pass the instance of A as an argument to the constructor (aggregation), with a setter method (essentially aggregation again), or you can set this relationship directly in the constructor (composition).</p>
<p>However, while singletons are powerful, be wary of implementing them with composition. It's nice to think that you can do it that way and get rid of a constructor argument, but it also makes it impossible to replace A with something else without a code rewrite. Peronsally, I'd stick with aggregation, even if using a singleton</p>
<pre><code>$foo = new B( A::getInstance() );
</code></pre>
| 8,758
|
<p>I have a read-only database that has cached information which is used to display pages on the site. There are processes that run to generate the database, and those run on a different server. When I need to update the live database, I restore this database to the live server, to a new name and file. Then I drop the live database and rename this one to the original name. Currently I do this with a stored procedure, that kills all connections via 'sp_who' and 'kill', then the drop database command, then 'sp_renamedb'. Now when I kill all connections it will throw an error on the site for people and crawlers currently accessing those pages, is there a better methodology for performing this procedure?</p>
|
<p>Probably what you want to do is take the live database offline with the command:</p>
<pre><code>ALTER DATABASE name SET OFFLINE
</code></pre>
<p>You can read more <a href="http://www.blackwasp.co.uk/SQLOffline.aspx" rel="nofollow noreferrer">here</a>, but it says:</p>
<blockquote>
<p>The above command attempts to take the named database off-line immediately. If a user or a background process is currently connected to the database the command cannot be completed. In this situation, the ALTER DATABASE statement will be blocked and will wait until all connections are closed. This ensures that no transactions are rolled back unexpectedly. During the period of blocking, no new connections to the database will be permitted.</p>
</blockquote>
<p>Once the database is offline, you should be able to do your restore/rename operations safely and bring it back online when done. You might have to do some playing around to see what is permitted while the database is in the offline state.</p>
<p>If you have trouble doing the restore/rename while it's offline, you'll want to bring it back online in single user mode.</p>
<p>Connection pooling or other long-running connections may cause problems in this scenario. You may want to set up a script to wait for a period of time after the ALTER DATABASE SET OFFLINE command has been issued (say 15 minutes), and if the database is still not offline yet, you can reissue the command with the WITH NO_WAIT option to force it offline.</p>
<p>If that isn't high-powered enough for you, you can also gracefully shutdown SQL Server...that will also wait until all work in the server is done before stopping.</p>
|
<p>+1 for Mike Sharek - I like your solution, it's very tidy and prevents users being disconnected abruptly (and very rudely).</p>
<p>Another alternative, if you don't want to sit around waiting for users to log off for hours. You could send an alert to connected clients through an AJAX mechanism you build into the site that basically sits "open" and waits for a notification from the server for a period before it times out and reconnects so essentially the XmlHttpObject is always waiting for a response. At the point of receiving the response, it displays it onscreen and then opens another connection. You then have an administrator interface that pushes out messages to the waiting AJAX component.</p>
<p>This would allow you to send a message in approximately realtime in a similar manner to the way Microsoft's Outlook Mobile Access works allowing users to be notified that in 10 minutes, the site is going down for maintenance.</p>
<p>I'm not sure if there's any prebuilt components out there that do this, but I'm sure it couldn't be too difficult to implement.</p>
<p>It doesn't help you out in the immediate sense, but it's worth thinking about for future releases of your site.</p>
| 48,657
|
<p>What is the best full text search alternative to Microsoft SQL? (which works with MS SQL)</p>
<p>I'm looking for something similar to <a href="http://lucene.apache.org/java/docs/index.html" rel="nofollow noreferrer">Lucene</a> and <a href="http://incubator.apache.org/lucene.net/" rel="nofollow noreferrer">Lucene.NET</a> but without the .NET and Java requirements. I would also like to find a solution that is usable in commercial applications.</p>
|
<p>Take a look at <a href="http://clucene.wiki.sourceforge.net/" rel="nofollow noreferrer">CLucene</a> - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application.</p>
<p>Performance is incredible, however you do have to get your head around some of the strange API conventions.</p>
|
<p>I second Sphinx, but <a href="http://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a> is also not so bad despite the Java. :) If you are not dealing with too much data spread out etc., then also look into MySQL's <a href="http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html" rel="nofollow noreferrer">FULLTEXT</a>. We are using it to search across a 20 GB database.</p>
| 5,979
|
<p>Is there any good practice related to dynamic_cast error handling (except not using it when you don't have to)? I'm wondering how should I go about NULL and bad_cast it can throw.
Should I check for both? And if I catch bad_cast or detect NULL I probably can't recover anyway...
For now, I'm using assert to check if dynamic_cast returned not NULL value. Would you accept this solution on a code review?</p>
|
<p>If the <code>dynamic_cast</code> <em>should</em> succeed, it would be good practice to use <code>boost::polymorphic_downcast</code> instead, which goes a little something like this:</p>
<pre><code>assert(dynamic_cast<T*>(o) == static_cast<T*>(o));
return static_cast<T*>(o);
</code></pre>
<p>This way, you will detect errors in the debug build while at the same time avoiding the runtime overhead in a release build.</p>
<p>If you suspect the cast <em>might</em> fail and you want to detect it, use <code>dynamic_cast</code> and cast to a reference type. This cast will throw <code>bad_cast</code> in case of error, and will take down your program. (This is good if, as you say, you are not going to recover anyway)</p>
<pre><code>T& t = dynamic_cast<T&>(o);
t.func(); //< Use t here, no extra check required
</code></pre>
<p>Use <code>dynamic_cast</code> to a pointer type only if the 0-pointer makes sense in the context. You might want to use it in an <code>if</code> like this:</p>
<pre><code>if (T* t = dynamic_cast<T*>(o)) {
t->func(); //< Use t here, it is valid
}
// consider having an else-clause
</code></pre>
<p>With this last option you need to make sure that the execution path makes sense if the <code>dynamic_cast</code> returns 0.</p>
<p>To answer your question directly: I would prefer one of the two first alternatives I have given to having an explicit <code>assert</code> in the code :)</p>
|
<p>I'd concur with the 'it depends' answer, and also add "Graceful degradation": just because a cast fails somewhere isn't enough reason to let the application fail (and the user lose his/her work, etc.). I'd recommend a combination of asserts and defensive programming:</p>
<pre><code>ptr = dynamic_cast<MyClass>(obj);
ASSERT(ptr);
if(ptr)
{
// do stuff
}
</code></pre>
| 30,566
|
<p>I am porting an existing application to C# and want to improve performance wherever possible. Many existing loop counters and array references are defined as System.UInt32, instead of the Int32 I would have used.</p>
<p>Is there any significant performance difference for using UInt32 vs Int32?</p>
|
<p>I don't think there are any performance considerations, other than possible difference between signed and unsigned arithmetic at the processor level but at that point I think the differences are moot.</p>
<p>The bigger difference is in the CLS compliance as the unsigned types are not CLS compliant as not all languages support them.</p>
|
<p>Its going to allocate the same amount of memory either way (although the one can store a larger value, as its not saving space for the sign). So I doubt you'll see a 'performance' difference, unless you use large values / negative values that will cause one option or the other to explode. </p>
| 39,443
|
<p>I was wondering if anyone had come across this one before. I have a customer who uses special characters in their product description field. Updating to a MySQL database works fine if we use their HTML equivalents but it fails if the character itself is used (copied from either character map or Word I would assume).</p>
<p>Has anyone seen this behaviour before? The character in question in this case is ø - and we can't seem to do a replace on it (in ASP at least) as the character comes though to the SQL string as a "?".</p>
<p>Any suggestions much appreciated - thanks!</p>
|
<p>This suggests a mismatched character set between your database (connection) and actual data.</p>
<p>Most likely, you're using ISO-8859-1 on your site, but MySQL thinks it should be getting UTF-8.</p>
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html" rel="nofollow noreferrer">http://dev.mysql.com/doc/refman/5.0/en/charset-connection.html</a> describes what to check and how to change it. The simplest way is probably to run the query "SET NAMES latin1" when connecting to the database (assuming that's the character set you need).</p>
<p>Being a fan of Unicode, I'd suggest switching over to UTF-8 entirely, but I realize that this is not always a feasible option.</p>
<p>Edit: @markokocic: Collation only dictates the sorting order. Although this should of course match your character set, it does not affect the range of characters that can be stored in a field.</p>
|
<p>Have you tried to set collation for the table to utf-8 or something non latin1/ascii.</p>
| 28,859
|
<p>I have a DataGridView which shows the content of a DataTable.</p>
<p>I want to set the backcolor of a row based on the value of a cell in this row.</p>
<p>Note that the cell in question is in a column which is not displayed in the DataGridView (Visible=False).</p>
|
<p>If you handle the RowDataBound event you can check the value of the data and modify the attributes of the cell or apply a different style in that event handler.</p>
<pre><code>protected void Page_Load(object sender, EventArgs e)
{
GridView g1 = new GridView();
g1.RowDataBound += new GridViewRowEventHandler(g1_RowDataBound);
}
void g1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// Check the Value
if(e.Row.Cells[1].Text = someValue)
{
e.Row.Cells[1].CssClass = "colorCellRed";
}
}
}
</code></pre>
<p>That should give you what you are looking for. Let me know if you need it in VB rather than C#.</p>
<p>Good Luck!</p>
|
<p>Another option would be to use the CellFormatting event.
First option shows accessing the bound data item and is useful if you don't have a column set up for the data in question. Second option works if there is a column whether it is visible or not.</p>
<pre><code> private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (((MyDataObject)dataGridView.Rows[e.RowIndex].DataBoundItem).Condition == Value)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}
</code></pre>
<p>// Option two -- can use ColumnIndex instead of ColumnName</p>
<pre><code> private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (dataGridView["ColumnName", e.RowIndex].Value).Condition == TargetValue)
{
e.CellStyle.BackColor = System.Drawing.Color.Gold;
}
}
</code></pre>
| 23,178
|
<p><strong>TL;DR:</strong> I'm looking to change the steps per mm but I'm not sure what to set it to. Do I decide on a temperature and change the rate based on the percentage for that temp? Or is there a more general setting I can put it to? Or is there a different underlying problem here?</p>
<p>I'm running into an issue with my Ender 3 where when I print PLA at different temperatures I'm getting different extrusion rates. I've done the test where marking it at 120 mm and then extruding using PronterFace 100 mm and measuring the distance and this is my results. I did two tests of each to confirm results</p>
<ul>
<li><p>185 °C 80 mm left = 60 % under extrusion</p></li>
<li><p>200 °C 31 mm Left = 11 % Under Extrusion</p></li>
<li><p>210 °C 32 mm Left = 12 % Under Extrusion</p></li>
<li><p>220 °C 28 mm Left = 8 % Under Extrusion</p></li>
<li><p>230 °C 25 mm Left = 5 % Under Extrusion</p></li>
</ul>
<p>When I feed 100 mm through the Bowden tube without the filament going through the hot end I get exactly 20 mm left meaning:</p>
<ul>
<li><p>0% under Extrusion</p>
<pre><code>echo: Steps per unit:
echo: M92 X80.00 Y80.00 Z400.00 E93.00
</code></pre></li>
</ul>
<p>I have been having this problem since I started. I normally print at 210 °C at 50 mm/s with a flow rate of 103 % which seems to work well for most prints but on flat walls on prints it under extrudes in the same spot each time it comes around to that point. </p>
<p>Steps I have taken so far:</p>
<ul>
<li><p>Different PLA filaments. All perform the same</p></li>
<li><p>Replaced the nozzle with a new one</p></li>
<li><p>Checked all fittings with the bowen tube system</p></li>
<li><p>Printed a spring spacer to make the spring tighter on the extruder gear</p></li>
<li><p>Changed the V<sub>ref</sub> from 0.75 to 1 for the extruder stepper</p></li>
</ul>
<p>The reason I changed the V<sub>ref</sub> on the extruder stepper is because the system would click back when printing as if the pressure was too great in the tube. Changing this has helped some of the under extrusion a bit.</p>
<p>So. depending on the temperature, it's harder or easier to push the filament by hand through the hot end. Maybe I need a better hot end?</p>
<p><a href="https://imgur.com/a/BhukLRb" rel="nofollow noreferrer">Examples</a>: </p>
<p>My test print to replicate the issue. The ripple bit is brittle and under extruded.</p>
<p><a href="https://i.stack.imgur.com/udUdz.jpg" rel="nofollow noreferrer" title="Test print - Image#1"><img src="https://i.stack.imgur.com/udUdz.jpg" alt="Test print - Image#1" title="Test print - Image#1"></a></p>
<p><a href="https://i.stack.imgur.com/br6vA.jpg" rel="nofollow noreferrer" title="Test print - Image#2"><img src="https://i.stack.imgur.com/br6vA.jpg" alt="Test print - Image#2" title="Test print - Image#2"></a></p>
<p>This was a Prototype piece for an up-sized print I was planning. After going around it under extrudes at the same point each time 210 °C</p>
<p><a href="https://i.stack.imgur.com/lPySW.jpg" rel="nofollow noreferrer" title="Prototype piece"><img src="https://i.stack.imgur.com/lPySW.jpg" alt="Prototype piece" title="Prototype piece"></a></p>
<p>Most of the print is fine just some parts are different. This is an inner wall.</p>
<p><a href="https://i.stack.imgur.com/qJNnr.jpg" rel="nofollow noreferrer" title="Inner wall"><img src="https://i.stack.imgur.com/qJNnr.jpg" alt="Inner wall" title="Inner wall"></a></p>
<p><a href="https://imgur.com/4THD6eY" rel="nofollow noreferrer">Heat towers</a></p>
|
<p>Obviously, your extrusion process is troubled by a lot of pressure. This can be seen from the extensive experiment you conducted with PLA extrusion at different temperatures. Please do note that 230 °C is considered pretty high for PLA! Usually it should be in the range of <a href="https://rigid.ink/blogs/news/3d-printing-basics-how-to-get-the-best-results-with-pla-filament" rel="nofollow noreferrer">185 - 205 °C</a>:</p>
<blockquote>
<p>In general, PLA filament settings have an optimal printing PLA
temperature range from about 185C to about 205C. If you’re using
1.75mm as opposed to thicker 2.85mm (or 3.00mm) your optimal print will be closer to the lower end of this PLA filament temperature
range.</p>
</blockquote>
<p>The temperature dependency of filament diameter is explained that small diameter filament warms up way faster in the heating zone of the hotend than large diameter filament as the heat travels less far to the filament core. Basically, with 1.75 mm filament you should be able to print at 195 °C. The pressure that the filament exerts on the hotend and extruder is clearly too much and leads to skipped steps.</p>
<p>It is <strong><em>strongly discouraged</em></strong> to create a function of steps per millimeter (or an over-extrusion by specifying a more than 100% flow modifier). This is a mechanical issue that needs to be fixed by addressing the hardware problem. Usually this is done by:</p>
<ul>
<li>fixing the extruder;
<ul>
<li>is it skipping steps? </li>
<li>does the filament tension get too high that it skips back pass the extruder gear?</li>
<li>does increase the stepper current work?</li>
</ul></li>
<li>fixing the Bowden tube;
<ul>
<li>is it clean?</li>
<li>is there too much friction?</li>
<li>are there kinks?</li>
</ul></li>
<li>fixing the hotend;
<ul>
<li>is the temperature that is reported the correct one? (thermistor problem?)</li>
<li>is the heat conducting properly to the nozzle?</li>
<li>is there a tolerance issue in the hotend/heatbreak?</li>
<li>is the coldend properly cooled?</li>
</ul></li>
</ul>
<p>A few of these you already explored, others you have not. Unfortunately, you have to do a little more troubleshooting the get to the bottom of the actual problem that is causing this pressure preventing the extruder to extrude the proper commanded length.</p>
|
<p>So I feel that I solved the problem thanks to a few sources. Thanks to 0scar for his quick response and help.</p>
<p>The problem was two fold. Mechanical problem causing blockage and slicer setting causing ripple.</p>
<ol>
<li>The PTFE tube wasn't pushed all the way in as far as it could go causing too much pressure in the hotend. This seems to be a really common problem with stock Ender 3's Because of the gap the hotend needed to heat up into the heat break to melt the lump in the gap between the hot end and the PTFE tube. </li>
<li>The slicing settings in cura had combing enabled. I set it to not comb on skin but what it was doing is combing just behind the skin and as a result would leak out filament in little blobs that when it printed the outer layer would be pushed out causing a ripple effect. This caused under extrusion once it finished the move because there wasnt enough filament left in the end.</li>
</ol>
<p>After I fixed these two things I was printing at 190c with no under extrusion, motor slipping, very little stringing and printing much better.</p>
| 1,109
|
<p>I've got a css menu like this:</p>
<pre><code><ul>
<li><a>Item1</a></li>
<li><a>Item Two</a></li>
<li><a>Item C</a></li>
<li><a>A Rather Long Menu Item Down Here</a></li>
</ul>
</code></pre>
<p>I want to create this:</p>
<pre>
|-----------------------------------|
| Item1 |
|-----------------------------------|
| Item Two |
|-----------------------------------|
| Item C |
|-----------------------------------|
| A Rather Long Menu Item Down Here |
|-----------------------------------|
</pre>
<p>but I'm getting this:</p>
<pre>
--------
| Item1 |
|-----------
| Item Two |
|-----------
| Item C |
|-----------------------------------
| A Rather Long Menu Item Down Here |
-----------------------------------
</pre>
<p>If I set either the [li] or [a] tags to display:block, they stretch to fill the maximum possible width. I want them all to have the same width, which is dynamically determined by the widest item, rather than by manually putting a width on the [ul] tag.</p>
<p>Oh, and the target is IE6. :)</p>
<h3>Update:</h3>
<p><code>width:1px, overflow:visible</code> didn't work. (Got the same squashed effect as without the display:blocked anchors.)</p>
<p>This is for an intranet where IE6 is the target, so I'm stuck there. (In other projects, I've stopped worrying about it.) JS is a requirement, so maybe I'll use that. (I always hate doing that, though.)</p>
|
<p>This is remarkably simple: </p>
<pre><code><style>
ul {
float: left;
}
ul li a {
display: block;
white-space: nowrap;
border: 1px solid blue;
}
</style>
<ul>
<li><a>Item1</a></li>
<li><a>Item Two</a></li>
<li><a>Item C</a></li>
<li><a>A Rather Long Menu Item Down Here</a></li>
</ul>
</code></pre>
<p>The trick here is the combination of floating the <ul> and adding white-space: nowrap; to the blocked anchors. In fact you don't even need the "nowrap" unless your <ul> is battling for space. As for the suggestion of ignoring 12% of your visitors.. well... </p>
|
<p>Certain amount of hacking to make it work in IE6, because width:auto never really worked properly. </p>
<p>I have seen some solutions to this problem using width:1px; overflow:visible;, which might work in this case, but best to do it in a conditional comment so as not to stuff up in "real" browsers, or use the holly hack or similar. Be aware that IE 6 will probably handle this differently in quirks mode to standards mode, so know your doctype. </p>
<p>BTW, would put your anchor tags as block, so you get consistent width mouse targets.</p>
| 38,468
|
<p>I am using MS AJAX ASP.NET Components (Calendar Extender) and I'm finding this problem.</p>
<p>Some weekdays are not being displayed....</p>
<p>I uploaded a picture so you can view exactly how it is being displayed...</p>
<p>The one on the right (calnder) in the picture is taken from microsoft's sample.</p>
<p>Have you got any idea what is causing this problem?</p>
<p>See screenshot: <a href="http://www.sajtkik.com/calendar.jpg" rel="nofollow noreferrer">http://www.sajtkik.com/calendar.jpg</a></p>
<p>Thanks Alot!</p>
|
<p>I have seen enough odd behavior when it comes to using MS "Ajax" objects across different browsers, to recommend not using the Calendar object if it can be avoided. There are enough client side (JS) libraries out there for calendars that are significantly better. </p>
<p>Why not try a <a href="http://marcgrabanski.com/article/jquery-calendar-version-2" rel="nofollow noreferrer">jQuery calendar</a>? </p>
|
<p>You don't need to know much about javascript to use JQuery. It's more simple than Javascript and just a few lines of code you can use JQuery Calendar on your page.</p>
<p>But of course being good needs some efforts.</p>
| 47,727
|
<p>I want to display documents on my website. The server is hosted on a Debian machine. I was thinking I can allow the upload of support documents then use a Linux app or PHP app to convert the doc into PDF and display that in an HTML page. Are there any APIs or binaries that allow me to do this?</p>
|
<p>If it is an office document, one option would be to use openoffice in headless mode. See here for a python script that shows how: <a href="http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html" rel="nofollow noreferrer">http://www.oooninja.com/2008/02/batch-command-line-file-conversion-with.html</a> </p>
<p>If it is any other kind of document (e.g. your own XML document), then you would need to do a bit more work. I have had some success using XSL to define a translation to docbook format, then using docbook tools to generate the PDF (and various other formats). You could also use XSL to go straight to PDF if you need more precise control over how things look. </p>
|
<p>Pear has a PHP PDF class. See:<br>
<a href="http://pear.php.net/package/File_PDF" rel="nofollow noreferrer">http://pear.php.net/package/File_PDF</a><br>
<a href="http://pear.php.net/package/File_PDF/docs/latest/apidoc/File_PDF/File_PDF.html" rel="nofollow noreferrer">http://pear.php.net/package/File_PDF/docs/latest/apidoc/File_PDF/File_PDF.html</a></p>
| 49,382
|
<p>I love programming with and for Windows Presentation Framework. Mostly I write browser-like apps using WPF and XAML.</p>
<p>But what really annoys me is the slowness of WPF. A simple page with only a few controls loads fast enough, but as soon as a page is a teeny weeny bit more complex, like containing a lot of data entry fields, one or two tab controls, and stuff, it gets painful.</p>
<p>Loading of such a page can take more than one second. Seconds, indeed, especially on not so fast computers (read: the customers computers) it can take ages.</p>
<p>Same with changing values on the page. Everything about the WPF UI is somehow sluggy.</p>
<p>This is so mean! They give me this beautiful framework, but make it so excruciatingly slow so I'll have to apologize to our customers all the time!</p>
<p>My Question: </p>
<ol>
<li>How do you speed up WPF?</li>
<li>How do you profile bottlenecks?</li>
<li>How do you deal with the slowness?</li>
</ol>
<p>Since this seems to be an universal problem with WPF, I'm looking for general advice, useful for many situations and problems.</p>
<p>Some other related questions:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/38642/what-tools-do-you-use-for-wpf-development">What tools do you use for WPF development</a></li>
<li><a href="https://stackoverflow.com/questions/189244/tools-to-develop-wpf-or-silverlight-applications">Tools to develop WPF or Silverlight applications</a></li>
</ul>
|
<ol>
<li><p><strong>How do you speed up WPF?</strong><br /><br>
Often after using one of the following profiling tools it is obvious what is causing my bottlenecks.</p>
<ul>
<li>If memory is the issue then I virtualize my data.</li>
<li>If render time is the issue then I virtualize the controls or simplify control templates where possible.</li>
<li>If processing time is the issue I try to improve my algorithm or move that work to a background thread and show a throbber in my ui while the work is going.<br>
<br/></li>
</ul></li>
<li><p><strong>How do you profile bottlenecks?</strong></p>
<ul>
<li><a href="http://memprofiler.com/" rel="noreferrer">.NET Memory Pofiler</a></li>
<li><a href="http://www.jetbrains.com/profiler/" rel="noreferrer">dotTrace</a></li>
<li><a href="http://windowsclient.net/wpf/perf/wpf-perf-tool.aspx" rel="noreferrer">Performance Profiling Tools for WPF</a></li>
<li><a href="http://blois.us/Snoop/" rel="noreferrer">Snoop</a></li>
<li><a href="http://www.codeplex.com/cracknetproject" rel="noreferrer">Crack.NET</a><br>
<br/></li>
</ul></li>
<li><p><strong>How do you deal with the slowness?</strong><br /><br>
Profiling and counseling.</p></li>
</ol>
|
<p>can you give more details? </p>
<p>I only noticed a slow performance when I use something like a listview or a grid that has some complexity. The solution is to simplify it. </p>
<p>Other than that I only noticed a slow performance when loading the app for the first time.</p>
<p>HTH</p>
| 27,390
|
<p>Im trying to do a dialog box with jquery. In this dialog box Im going to have terms and conditions. The problem is that the dialog box is only displayed for the FIRST TIME.</p>
<p>This is the code.</p>
<p>JavaScript:</p>
<pre><code>function showTOC()
{
$("#TOC").dialog({
modal: true,
overlay: {
opacity: 0.7,
background: "black"
}
})
}
</code></pre>
<p>HTML (a href):</p>
<pre><code><a class="TOClink" href="javascript:showTOC();">View Terms & Conditions</a>
<div id="example" title="Terms & Conditions">1..2..</div>
</code></pre>
<p>The problem I think is that when you close the dialog box the DIV is destroyed from the html code therfore it can never be displayed again on screen.</p>
<p>Can you please help!</p>
<p>Thanks</p>
|
<p>Looks like there is an issue with the code you posted. Your function to display the T&C is referencing the wrong div id. You should consider assigning the showTOC function to the onclick attribute once the document is loaded as well:</p>
<pre><code>$(document).ready({
$('a.TOClink').click(function(){
showTOC();
});
});
function showTOC() {
$('#example').dialog({modal:true});
}
</code></pre>
<p>A more concise example which accomplishes the desired effect using the jQuery UI dialog is:</p>
<pre><code> <div id="terms" style="display:none;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<a id="showTerms" href="#">Show Terms &amp; Conditions</a>
<script type="text/javascript">
$(document).ready(function(){
$('#showTerms').click(function(){
$('#terms').dialog({modal:true});
});
});
</script>
</code></pre>
|
<p>This is a little more concise and also allows you to have different dialog values etc based on different click events:</p>
<pre><code>$('#click_link').live("click",function() {
$("#popup").dialog({modal:true, width:500, height:800});
$("#popup").dialog("open");
return false;
});
</code></pre>
| 47,859
|
<p>I'm creating an installer for a website that uses a custom event log source. I would like our WiX based installer to create that event log source during installation.</p>
<p>Does anyone know the best way to do this using the WiX framework.</p>
|
<p>Wix has out-of-the-box support for creating event log sources.</p>
<p>Assuming you use Wix 3, you first need to add a reference to WixUtilExtension to either your Votive project or the command line. You can then add an EventSource element under a component :</p>
<pre><code><Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
<Component ...>
...
<util:EventSource Log="Application" Name="*source name*"
EventMessageFile="*path to message file*"/>
...
</Component>
</code></pre>
<p>If this is a .NET project, you can use EventLogMessages.dll in the framework directory as the message file.</p>
|
<p>Just to save people some time - if you are trying to use the Application log and the .NET messages you can cut paste the below code:</p>
<pre><code><Util:EventSource
xmlns:Util="http://schemas.microsoft.com/wix/UtilExtension"
Name="ROOT Builder"
Log="Application"
EventMessageFile="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll"
/>
</code></pre>
<p>NOTE: the path above is now correct..</p>
| 8,289
|
<p>I put together a class yesterday to do some useful task. I started alpha testing, and at some point realized I was adding alpha test related methods to the class itself. It hit me that they don't belong there. After a bit of head scratching I derived a test class from the base class that has access to the protected members as well. I put all of the testing related methods, and set up and tear down in the test class, and left the base class lean and mean as the old saying goes.</p>
<p>After browsing around here awhile I found one comment that suggested using this sort of technique by making the testing class a friend of the real class.</p>
<p>In retrospect both of those techniques should have been obvious to me.</p>
<p><strong>What I am looking for, are techniques for specifically alpha testing/unit testing classes, without adding to the weight of the class being tested.</strong></p>
<p><strong>What techniques have you personally used, and recommend?</strong></p>
|
<p>One of the goals of unit testing is to verify the <i>interface</i> to your classes. This means that, generally speaking, you shouldn't be testing the dirty innards of your class. The unit test is supposed to interact with the public inputs and outputs of your class, and verify that the behaviour is as expected. You are thus able to change the internal implementation of your class without affecting all of the other objects that depend on it. Obviously, I don't know the details in your situation but I would say that, as a general rule, if your unit test is trying to figure out the private details of the class, you are doing something wrong.</p>
<p><b>edit:</b> See also: <a href="https://stackoverflow.com/questions/34571/whats-the-best-way-of-unit-testing-private-methods">This SO question</a>. Notice that it can be done (top answer), but also notice that the second-place answer (by a short margin) says more or less the same thing as I mention above.</p>
|
<p>Those are good. I have usually also wanted the test class to not only be spearate from the original, but also in a complete different DLL/EXE, as well as testing the "real" compiled class from the "real" DLL/EXE into which it was compiled.</p>
<p>The one additional technique I've found is to re-define the class within the testing tool. Copy the class definition exactly, but make everything public. This allows the test tool to have 'white-box' access to the class, but the actual implementation is still from the real class code.</p>
<p>i.e.</p>
<pre><code>class myClass
{
private:
int foo;
public:
myClass() { foo = 0; }
}
</code></pre>
<p>and then:</p>
<pre><code>class test_myClass
{
public:
int foo;
public:
test_myClass();
};
void test()
{
myClass *c = new myClass();
test_myClass *t = (test_myClass*)c;
// All methods are called on c.
// White-box access is available through t.
};
</code></pre>
<p>Oh... and DevStudio 2008 now has some really cool unit testing capabilities, including the ability to declare a 'friend' <em>assembly</em>, which allows white-box access to all your internal classes in the assembly being tested.</p>
| 44,455
|
<p>Re the recent question at <a href="https://stackoverflow.com/questions/361481/when-are-modal-dialogs-truly-necessary">when are modal dialogs truly necessary?</a>. WHY are modal dialog boxes evil? Is it because people don't read them anyway? Because they are often implemented so poorly? Something else?</p>
|
<p>About half of the answers so far are addressing the flaws of <em>confirmation</em> dialogs, not of <em>modal</em> dialogs. While the vast majority of confirmation dialogs are modal, this does not mean that the two terms are synonymous.</p>
<p>A <em>mod</em>al dialog is one which puts the program into a specific <em>mode</em> and does not allow you to do anything which doesn't correspond to that mode while it is open. In the most common implementation, this means you can't access any other windows.</p>
<p>This is evil.</p>
<p>Consider an address book application. Suppose you have an existing person in the address book and you wish to add their roommate.</p>
<ul>
<li>If the "add person" dialog is non-modal, you can flip back and forth between the old record and the new one copying and pasting your data.</li>
<li>If the "add person" dialog is modal, you can't do anything with the old record while the add dialog is open. You can select something to copy before selecting "add", but just one thing. Everything else has to be manually retyped.</li>
</ul>
<p>On rare occasions, you run into something which truly must be done in one piece without allowing the user to diverge from that task until it is complete. Modal dialogs are appropriate for such cases. <em>But these cases are very rare!</em> Which is basically the point of the other thread referenced by this question.</p>
|
<p>One of the reasons that I don't like them is because they are showing information in serial(one lot of information at a time) and not parallel(all the information you need to see at once), parallel will allow the user to choose what they want to look at where as in serial you are pretty much forcing them to pick an option.</p>
<p>Plus also the fact that they break a users flow of control(eg steals focus from the object you working on) which I really don't like doing. So in effect from this the user will just hit OK so that they can get back to what they where doing and ignore the information in the dialog box.</p>
<p>Mind you you still need them in some cases.</p>
| 47,179
|
<p>We are in the process of upgrading our VS2008 to the new SP1, but noticed a change in the csproj files for something that we can't find information on. Seems that the ProductVersion in the csproj file is changed from:</p>
<pre><code><ProductVersion>9.0.21022</ProductVersion>
</code></pre>
<p>to</p>
<pre><code><ProductVersion>9.0.30729</ProductVersion>
</code></pre>
<p>It looks like some property signalling that the csproj file is/can be consumed by VS 2008 SP1 (perhaps for the Solution Selector to peek into) but are there other hidden side-effects of this property change that we should be looking out for?</p>
|
<p>I think it's more likely to be the product version that <em>produced</em> the file rather than saying what it can be consumed by. I'd be very surprised to see the build version make any tangible difference.</p>
|
<p>My coworker just got SP1 courtesy of of a ninja update from corporate IT (presumably I'll be getting it after rebooting). My RTM copy doesn't seem to care about the newer version string in all the csproj files.</p>
| 33,203
|
<p>I'm learning C++ and writing little programs as I go along. The following is one such program:</p>
<pre><code>// This program is intended to take any integer and convert to the
// corresponding signed char.
#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(true){
std::cin >> n;
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
</code></pre>
<p>When I run this program and keep inputs at reasonably small absolute values, it behaves as expected. But when I enter larger inputs, e.g., 10000000000, the program repetitively spits out the same output. Some combinations of input cause erratic behavior. For example:</p>
<pre><code>#: ./int2ch
10
10 -->
10000000000
10 -->
10 -->
10 -->
10 -->
</code></pre>
<p>The program spits out "10 --> " until it's killed. (With this particular sequence of inputs, the program's output changes speed erratically.) I also noticed that the output of large values is determined by the previous legal input as well as the value of the current illegal input.</p>
<p>What's going on? (I don't care about fixing the program, that's easy. I want to understand it.)</p>
|
<p>Basically your <code>cin</code> stream is in a fail state and thus returns immediately when you try to read it. Rewrite your example like this:</p>
<pre><code>#include <iostream>
int main()
{
signed char sch = 0;
int n = 0;
while(std::cin >> n){
sch = n;
std::cout << n << " --> " << sch << std::endl;
}
}
</code></pre>
<p><code>cin >> n</code> will return a reference to <code>cin</code>, which you can test for "good-ness" in a conditional. So basically the the "<code>while(std::cin >> n)</code>" is saying "while i could still read from standard input successfully, do the following"</p>
<p>EDIT: the reason it repeatedly output the last good value entered is because that was the last value successfully read in n, the failed reads won't change the value of n</p>
<p>EDIT: as noted in a comment, you can clear the error state and try again something like this would probably work and just ignore bad numbers:</p>
<pre><code>#include <iostream>
#include <climits>
int main() {
signed char sch = 0;
int n = 0;
while(true) {
if(std::cin >> n) {
sch = n;
std::cout << n << " --> " << sch << std::endl;
} else {
std::cin.clear(); // clear error state
std::cin.ignore(INT_MAX, '\n'); // ignore this line we couldn't read it
}
}
}
</code></pre>
|
<p>One problem here is that a <code>char</code> has a size of one byte, and thus can only hold a number between -127 and 128. An <code>int</code> on the other hand, is typically 4 bytes, and can take on much larger values. Second problem is that you are inputting a value that is too large even for an <code>int</code>.</p>
| 33,431
|
<p>I have boiled down an issue I'm seeing in one of my applications to an incredibly simple reproduction sample. I need to know if there's something amiss or something I'm missing.</p>
<p>Anyway, below is the code. The behavior is that the code runs and steadily grows in memory until it crashes with an OutOfMemoryException. That takes a while, but the behavior is that objects are being allocated and are not being garbage collected. </p>
<p>I've taken memory dumps and ran !gcroot on some things as well as used ANTS to figure out what the problem is, but I've been at it for a while and need some new eyes.</p>
<p>This reproduction sample is a simple console application that creates a Canvas and adds a Line to it. It does this continually. This is all the code does. It sleeps every now and again to ensure that the CPU is not so taxed that your system is unresponsive (and to ensure there's no weirdness with the GC not being able to run). </p>
<p>Anyone have any thoughts? I've tried this with .NET 3.0 only, .NET 3.5 and also .NET 3.5 SP1 and the same behavior occurred in all three environments.</p>
<p>Also note that I've put this code in a WPF application project as well and triggered the code in a button click and it occurs there too.</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Shapes;
using System.Windows;
namespace SimplestReproSample
{
class Program
{
[STAThread]
static void Main(string[] args)
{
long count = 0;
while (true)
{
if (count++ % 100 == 0)
{
// sleep for a while to ensure we aren't using up the whole CPU
System.Threading.Thread.Sleep(50);
}
BuildCanvas();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void BuildCanvas()
{
Canvas c = new Canvas();
Line line = new Line();
line.X1 = 1;
line.Y1 = 1;
line.X2 = 100;
line.Y2 = 100;
line.Width = 100;
c.Children.Add(line);
c.Measure(new Size(300, 300));
c.Arrange(new Rect(0, 0, 300, 300));
}
}
}
</pre>
<p>NOTE: the first answer below is a bit off-base since I explicitly stated already that this same behavior occurs during a WPF application's button click event. I did not explicitly state, however, that in that app I only do a limited number of iterations (say 1000). Doing it that way would allow the GC to run as you click around the application. Also note that I explicitly said I've taken a memory dump and found my objects were rooted via !gcroot. I also disagree that the GC would not be able to run. The GC does not run on my console application's main thread, especially since I'm on a dual core machine which means the Concurrent Workstation GC is active. Message pump, however, yes.</p>
<p>To prove the point, here's a WPF application version that runs the test on a DispatcherTimer. It performs 1000 iterations during a 100ms timer interval. More than enough time to process any messages out of the pump and keep the CPU usage low.</p>
<pre>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Shapes;
namespace SimpleReproSampleWpfApp
{
public partial class Window1 : Window
{
private System.Windows.Threading.DispatcherTimer _timer;
public Window1()
{
InitializeComponent();
_timer = new System.Windows.Threading.DispatcherTimer();
_timer.Interval = TimeSpan.FromMilliseconds(100);
_timer.Tick += new EventHandler(_timer_Tick);
_timer.Start();
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
void RunTest()
{
for (int i = 0; i < 1000; i++)
{
BuildCanvas();
}
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
private static void BuildCanvas()
{
Canvas c = new Canvas();
Line line = new Line();
line.X1 = 1;
line.Y1 = 1;
line.X2 = 100;
line.Y2 = 100;
line.Width = 100;
c.Children.Add(line);
c.Measure(new Size(300, 300));
c.Arrange(new Rect(0, 0, 300, 300));
}
void _timer_Tick(object sender, EventArgs e)
{
_timer.Stop();
RunTest();
_timer.Start();
}
}
}
</pre>
<p>NOTE2: I used the code from the first answer and my memory grew very slowly. Note that 1ms is much slower and less iterations than my example. You have to let it run for a couple minutes before you start to notice growth. After 5 minutes it's at 46MB from a starting point of 30MB. </p>
<p>NOTE3: Removing the call to .Arrange completely eliminates the growth. Unfortunately, that call is pretty vital to my use since in many cases I'm creating PNG files from the Canvas (via the RenderTargetBitmap class). Without the call to .Arrange it doesn't layout the canvas at all.</p>
|
<p>I was able to reproduce your problem using the code you provided. Memory keeps growing because the Canvas objects are never released; a memory profiler indicates that the Dispatcher's ContextLayoutManager is holding on to them all (so that it can invoke OnRenderSizeChanged when necessary).</p>
<p>It seems that a simple workaround is to add</p>
<pre><code>c.UpdateLayout()
</code></pre>
<p>to the end of <code>BuildCanvas</code>.</p>
<p>That said, note that <code>Canvas</code> is a <code>UIElement</code>; it's supposed to be used in UI. It's not designed to be used as an arbitrary drawing surface. As other commenters have already noted, the creation of thousands of Canvas objects may indicate a design flaw. I realise that your production code may be more complicated, but if it's just drawing simple shapes on a canvas, GDI+-based code (i.e., the System.Drawing classes) may be more appropriate.</p>
|
<p><strong>Edit 2:</strong> Obviously not the answer, but was part of the back-and-forth among answers and comments here, so I'm not deleting it.</p>
<p>The GC never gets a chance to collect those objects because your loop and its blocking calls never end, and therefore the message pump and events never get their turn. If you used a <code>Timer</code> of some sort so that messages and events actually have a chance to process, you probably wouldn't be able to eat up all your memory.</p>
<p><strong>Edit:</strong> The following does not eat up my memory as long as the interval is greater than zero. Even if the interval is just 1 Tick, as long as it isn't 0. If it's 0, we're back to the infinite loop.</p>
<pre><code>public partial class Window1 : Window {
Class1 c;
DispatcherTimer t;
int count = 0;
public Window1() {
InitializeComponent();
t = new DispatcherTimer();
t.Interval = TimeSpan.FromMilliseconds( 1 );
t.Tick += new EventHandler( t_Tick );
t.Start();
}
void t_Tick( object sender, EventArgs e ) {
count++;
BuildCanvas();
}
private static void BuildCanvas() {
Canvas c = new Canvas();
Line line = new Line();
line.X1 = 1;
line.Y1 = 1;
line.X2 = 100;
line.Y2 = 100;
line.Width = 100;
c.Children.Add( line );
c.Measure( new Size( 300, 300 ) );
c.Arrange( new Rect( 0, 0, 300, 300 ) );
}
}
</code></pre>
| 23,375
|
<p>SQL Server 2005.</p>
<p>I'm adding Foreign Key constraints to the database of an application that allegedly didn't need them. Naturally, the data has become unreliable and there are orphaned entries in the foreign key field.</p>
<p>Setup:<br/>
Two tables, TableUser and TableOrder.
TableUser has Primary Key 'UserID', and TableOrder has Foreign Key 'UserID'.</p>
<p>How do I find the rows where TableOrder.UserID has no matching entry in TableUser.UserID?</p>
<p>For example, TableOrder.UserID has a value of 250, but there is no matching TableUser.UserID key for 250.</p>
|
<p>Here's one way:</p>
<pre><code>select * from TableOrder where UserID not in (select UserID from TableUser);
</code></pre>
<p>There are many different ways to write this sort of query.</p>
|
<p>There were no FK Constraints in the tables to begin with. The were used like FK and PK but not coded -- the belief was that they were unnecessary overhead. So we have all the columns, but no coded constraints. When I went to put them in so that they would be enforced, I discovered that there were lots of violations.</p>
<p>Your question highlights the problem. They are not unnecessary overhead, they prevent people from general database asshattery.</p>
<p>Both Greg and Brad's answers helped me out.</p>
| 32,422
|
<p>Sample data:
!!Part|123456,ABCDEF,ABC132!!</p>
<p>The comma delimited list can be any number of any combination of alphas and numbers </p>
<p>I want a regex to match the entries in the comma separated list:</p>
<p>What I have is:
!!PART\|(\w+)(?:,{1}(\w+))*!!</p>
<p>Which seems to do the job, the thing is I want to retrieve them in order into an ArrayList or similar so in the sample data I would want:</p>
<ul>
<li>1 - 132456</li>
<li>2 - ABCDEF</li>
<li>3 - ABC123</li>
</ul>
<p>The code I have is:</p>
<pre><code>string partRegularExpression = @"!!PART\|(\w+)(?:,{1}(\w+))*!!"
Match match = Regex.Match(tag, partRegularExpression);
ArrayList results = new ArrayList();
foreach (Group group in match.Groups)
{
results.Add(group.Value);
}
</code></pre>
<p>But that's giving me unexpected results. What am I missing?</p>
<p>Thanks</p>
<p><strong>Edit:</strong>
A solution would be to use a regex like !!PART\|(\w+(?:,??\w+)*)!! to capture the comma separated list and then split that as suggested by Marc Gravell</p>
<p>I am still curious for a working regex for this however :o)</p>
|
<p>You can either use split:</p>
<pre><code>string csv = tag.Substring(7, tag.Length - 9);
string[] values = csv.Split(new char[] { ',' });
</code></pre>
<p>Or a regex:</p>
<pre><code>Regex csvRegex = new Regex(@"!!Part\|(?:(?<value>\w+),?)+!!");
List<string> valuesRegex = new List<string>();
foreach (Capture capture in csvRegex.Match(tag).Groups["value"].Captures)
{
valuesRegex.Add(capture.Value);
}
</code></pre>
|
<p>The following code</p>
<pre><code>string testString = "!!Part|123456,ABCDEF,ABC132!!";
foreach(string component in testString.Split("|!,".ToCharArray(),StringSplitOptions.RemoveEmptyEntries) )
{
Console.WriteLine(component);
}
</code></pre>
<p>will give the following output</p>
<pre><code>Part
123456
ABCDEF
ABC132
</code></pre>
<p>This has the advantage of making the comma separated part of the string match up with the index numbers you (possibly accidentally incorrectly) specified in the original question (1,2,3).</p>
<p>HTH</p>
<p>-EDIT- forgot to mention, this may have drawbacks if the format of each string is not as expected above, but then again it would break just as easily without stupendously complex regex too.</p>
| 48,089
|
<p>I am getting the following error when I post back a page from the client-side. I have JavaScript code that modifies an asp:ListBox on the client side.</p>
<p>How do we fix this?</p>
<p>Error details below:</p>
<pre><code>Server Error in '/XXX' Application.
--------------------------------------------------------------------------------
Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.]
System.Web.UI.ClientScriptManager.ValidateEvent(String uniqueId, String argument) +2132728
System.Web.UI.Control.ValidateEvent(String uniqueID, String eventArgument) +108
System.Web.UI.WebControls.ListBox.LoadPostData(String postDataKey, NameValueCollection postCollection) +274
System.Web.UI.WebControls.ListBox.System.Web.UI.IPostBackDataHandler.LoadPostData(String postDataKey, NameValueCollection postCollection) +11
System.Web.UI.Page.ProcessPostData(NameValueCollection postData, Boolean fBeforeLoad) +353
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1194
--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1433; ASP.NET Version:2.0.50727.1433
</code></pre>
|
<p>The problem is that ASP.NET does not get to know about this extra or removed listitem.
You got an number of options (listed below):</p>
<ul>
<li>Disable eventvalidation (bad idea, because you lose a little of security that come with very little cost).</li>
<li>Use ASP.NET Ajax UpdatePanel. (Put the listbox in the Updatepanel and trigger a update, if you add or remove listbox. This way viewstate and related fields get updates and eventvalidation will pass.)</li>
<li>Forget client-side and use the classic postback and add or remove the listitems server-side.</li>
</ul>
<p>I hope this helps. </p>
|
<p>Check you data of binded your controls. Some invalid data corrupt ValidateEvent.</p>
| 28,336
|
<p>On my current project, I came across our master DB script. Taking a closer look at it, I noticed that all of our original primary keys have a data type of <strong>numeric(38,0)</strong>
We are currently running SQL Server 2005 as our primary DB platform.</p>
<p>For a little context, we support both Oracle and SQL Server as our back-end. In Oracle, our primary keys have a data type of <strong>number(38,0).</strong></p>
<p>Does anybody know of possible side-effects and performance impact of such implementation? I have always advocated and implemented <em>int</em> or <em>bigint</em> as primary keys and would love to know if numeric(38,0) is a better alternative.</p>
|
<p>Well, you <em>are</em> spending more data to store numbers that you will never really reach.</p>
<p>bigint goes up to 9,223,372,036,854,775,807 in 8 Bytes</p>
<p>int goes up to 2,147,483,647 in 4 bytes</p>
<p>A NUMERIC(38,0) is going to take, if I am doing the math right, 17 bytes.</p>
<p>Not a huge difference, but: smaller datatypes = more rows in memory (or fewer pages for the same # of rows) = fewer disk I/O to do lookups (either indexed or data page seeks). Goes the same for replication, log pages, etc.</p>
<p>For SQL Server: INT is an IEEE standard and so is easier for the CPU to compare, so you get a slight performance increase by using INT vs. NUMERIC (which is a packed decimal format). (Note in Oracle, if the current version matches the older versions I grew up on, ALL datatypes are packed so an INT inside is pretty much the same thing as a NUMERIC( x,0 ) so there's no performance difference)</p>
<p>So, in the grand scheme of things -- if you have lots of disk, RAM, and spare I/O, use whatever datatype you want. If you want to get a little more performance, be a little more conservative.</p>
<p>Otherwise at this point, I'd leave it as it is. No need to change things.</p>
|
<p>Barring the storage considerations and some initial confusion from future DBAs, I don't see any reason why NUMERIC(38,0) would be a bad idea. You're allowing for up to 9.99 x 10^38 records in your table, which you will certainly never reach. My quick digging into this didn't turn up any glaring reason not to use it. I suspect that your only potential issue will be the storage space consumed by that, but seeing as how storage space is so cheap, that shouldn't be an issue.</p>
<p>I've seen this a fair number of times in Oracle databases since it's a pretty big default value that you don't need to think about when you're creating a table, similar to using INT or BIGINT by default in SQL Server.</p>
| 36,316
|
<p>Using Awk I want to match the <em>entire</em> record using a regular expression. By default the regular expression matching is for parts of a record.</p>
<p>The ideal solution would:</p>
<ul>
<li>Be general for all fields, regardless of the field separator used.</li>
<li>Not treat the entire input as a single field and parse it manually using string functions.</li>
<li>Work in a general way and not be specific to gawk for example.</li>
</ul>
<p>However any and all solutions are of interest as long as they <strong>use Awk without calls to external programs</strong>.</p>
<p>An example, I have:</p>
<pre><code>$ ls
indata.txt t1.awk
$ cat indata.txt
a1010_
1010_
1010_b
$ cat t1.awk
/[01]*_[01]*/ { print $0 }
</code></pre>
<p>I get:</p>
<pre><code>$ awk -f t1.awk indata.txt
a1010_
1010_
1010_b
</code></pre>
<p>This is the result I am seeking:</p>
<pre><code>$ awk -f t1.awk indata.txt
1010_
</code></pre>
|
<p>You just need to add a beginning and end anchor to your regex:</p>
<pre><code>/^[01]*_[01]*$/ { print $0 }
</code></pre>
|
<pre><code>$ gawk '/^[01]*_[01]*$/' indata.txt
1010_
</code></pre>
| 45,002
|
<p>I was looking at the Java code for <code>LinkedList</code> and noticed that it made use of a static nested class, <code>Entry</code>.</p>
<pre><code>public class LinkedList<E> ... {
...
private static class Entry<E> { ... }
}
</code></pre>
<p>What is the reason for using a static nested class, rather than an normal inner class?</p>
<p>The only reason I could think of, was that Entry doesn't have access to instance variables, so from an OOP point of view it has better encapsulation. </p>
<p>But I thought there might be other reasons, maybe performance. What might it be?</p>
<p>Note. I hope I have got my terms correct, I would have called it a static inner class, but I think this is wrong: <a href="http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html" rel="noreferrer">http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html</a></p>
|
<p>The Sun page you link to has some key differences between the two:</p>
<blockquote>
<p>A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.<br>
...</p>
<p>Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. <strong>In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.</strong></p>
</blockquote>
<p>There is no need for <code>LinkedList.Entry</code> to be top-level class as it is <em>only</em> used by <code>LinkedList</code> (there are some other interfaces that also have static nested classes named <code>Entry</code>, such as <code>Map.Entry</code> - same concept). And since it does not need access to LinkedList's members, it makes sense for it to be static - it's a much cleaner approach.</p>
<p>As <a href="https://stackoverflow.com/a/253507/4249">Jon Skeet points out</a>, I think it is a better idea if you are using a nested class is to start off with it being static, and then decide if it really needs to be non-static based on your usage.</p>
|
<p>Adavantage of inner class--</p>
<ol>
<li>one time use</li>
<li>supports and improves encapsulation</li>
<li>readibility </li>
<li>private field access</li>
</ol>
<p>Without existing of outer class inner class will not exist.</p>
<pre><code>class car{
class wheel{
}
}
</code></pre>
<p>There are four types of inner class.</p>
<ol>
<li>normal inner class</li>
<li>Method Local Inner class</li>
<li>Anonymous inner class</li>
<li>static inner class</li>
</ol>
<p>point --- </p>
<ol>
<li>from static inner class ,we can only access static member of outer class.</li>
<li>Inside inner class we cananot declare static member .</li>
<li><p>inorder to invoke normal inner class in static area of outer class.</p>
<p><code>Outer 0=new Outer();
Outer.Inner i= O.new Inner();</code></p></li>
<li><p>inorder to invoke normal inner class in instance area of outer class.</p>
<p><code>Inner i=new Inner();</code></p></li>
<li><p>inorder to invoke normal inner class in outside of outer class.</p>
<p><code>Outer 0=new Outer();
Outer.Inner i= O.new Inner();</code></p></li>
<li><p>inside Inner class This pointer to inner class.</p>
<p><code>this.member-current inner class
outerclassname.this--outer class</code></p></li>
<li><p>for inner class applicable modifier is -- public,default, </p>
<p><code>final,abstract,strictfp,+private,protected,static</code></p></li>
<li><p>outer$inner is the name of inner class name.</p></li>
<li><p>inner class inside instance method then we can acess static and instance field of outer class.</p></li>
</ol>
<p>10.inner class inside static method then we can access only static field of </p>
<p>outer class.</p>
<pre><code>class outer{
int x=10;
static int y-20;
public void m1() {
int i=30;
final j=40;
class inner{
public void m2() {
// have accees x,y and j
}
}
}
}
</code></pre>
| 31,600
|
<p>I am wondering any efficient way to hide our Silverlight code. I know there are some obfuscators available but it looks like people can hack that too. Anybody have any success on this front?</p>
|
<p>Pragma No-Cache on the page hosting the silverlight application will prevent the the browser from caching the xap, instead it will read it by streaming from the web server. That will make it harder for peeps to get the xap. Obfuscation will make it harder still.</p>
<p>Also make sure the app is hosted in https, have authentication take place outside the main application. This way the xap stream is encoded on the way down.</p>
|
<p>You cannot hide (at least not non-trivially) XAP files. But you can obfuscate them. Obfuscation is not a definitive answer, but its a start and can give pretty good protection. </p>
| 14,105
|
<p>I have Visual Studio 2008 and the Windows SDK for Windows Server 2008 and .NET Framework 3.5
installed. I believe that is the latest platform SDK.</p>
<p>I'm trying to build a signed dll to be installed in SxS.
All the tutorials explain to use a tool called pktextract.exe which is part of the SDK, but I can't seem to find the tool. All the other tools such as makecert, mt, makecat exist.</p>
<p>Was pktextract replaced by some other tool in the latest version of the sdk?</p>
<p>Thanks for the help.</p>
|
<p>I have a visual Basic program with Visual Studio 2008 that uses an Access 2007 database and was receiving the same error. I found some threads that advised changing the advanced compile configuration to x86 found in the programs properties if you're running a 64 bit system. So far I haven't had any problems with my program since. </p>
|
<p>I've got the same error on a fully updated Windows Vista Family 64bit with a .NET application that I've compiled to 32 bit only - the program is installed in the programx86 folder on 64 bit machines. It fails with this error message even with 2007 access database provider installed, with/wiothout the SP2 of the same installed, IIS installed and app pool set for 32bit app support... yes I've tried every solution everywhere and still no success. </p>
<p>I switched my app to ACE OLE DB.12.0 because JET4.0 was failing on 64bit machines - and it's no better :-/ The most promising thread I've found was this: </p>
<p><a href="http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/" rel="nofollow noreferrer">http://ellisweb.net/2010/01/connecting-to-excel-and-access-files-using-net-on-a-64-bit-server/</a> </p>
<p>but when you try to install the 64 bit "2010 Office System Driver Beta: Data Connectivity Components" it tells you that you can't install the 64 bit version without uninstalling all 32bit office applications... and installing the 32 bit version of 2010 Office System Driver Beta: Data Connectivity Components doesn't solve the initial problem, even with "Microsoft.ACE.OLEDB.12.0" as provider instead of "Microsoft.ACE.OLEDB.14.0" which that page (and others) recommend.</p>
<p>My next attempt will be to follow this post:</p>
<p>The issue is due to the wrong flavor of OLEDB32.DLL and OLEDB32r.DLL being registered on the server. If the 64 bit versions are registered, they need to be unregistered, and then the 32 bit versions registered instead. To fix this, unregister the versions located in %Program Files%/Common Files/System/OLE DB. Then register the versions at the same path but in the %Program Files (x86)% directory.</p>
<p>Has anyone else had so much trouble with both JET4.0 and OLEDB ACE providers on 64 bit machines? Has anyone found a solution if none of the others work?</p>
| 29,516
|
<p>I have two collections which have property <code>Email</code> in both collections. I need to get a list of the items in the first list where <code>Email</code> does not exist in the second list. With SQL I would just use "not in", but I do not know the equivalent in LINQ. How is that done?</p>
<p>So far I have a join, like...</p>
<pre><code>var matches = from item1 in list1
join item2 in list2 on item1.Email equals item2.Email
select new { Email = list1.Email };
</code></pre>
<p>But I cannot join since I need the difference and the join would fail. I need some way of using Contains or Exists I believe. I just have not found an example to do that yet.</p>
|
<p>I don't know if this will help you but..</p>
<pre><code>NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );
</code></pre>
<p>from <a href="https://web.archive.org/web/20120321161927/https://www.programminglinq.com/blogs/marcorusso/archive/2008/01/14/the-not-in-clause-in-linq-to-sql.aspx" rel="noreferrer">The NOT IN clause in LINQ to SQL</a> by <a href="https://web.archive.org/web/20110805143247/http://introducinglinq.com/blogs/marcorusso/default.aspx" rel="noreferrer">Marco Russo</a></p>
|
<p>I did not test this with <a href="http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework#LINQ_to_Entities" rel="nofollow">LINQ to Entities</a>:</p>
<pre><code>NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where !dc.Orders.Any(o => o.CustomerID == c.CustomerID)
select c;
</code></pre>
<p>Alternatively:</p>
<pre><code>NorthwindDataContext dc = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dc.Customers
where dc.Orders.All(o => o.CustomerID != c.CustomerID)
select c;
foreach (var c in query)
Console.WriteLine( c );
</code></pre>
| 22,224
|
<p>I really enjoy having "pretty" URLs (e.g. <code>/Products/Edit/1</code> instead of <code>/products.aspx?productID=1</code>) but I'm at a loss on how to do this for pages that let you search by a large number of variables.</p>
<p>For instance, let's say you have a page that lets a user search for all products of a particular type with a certain name and near a specific address. Would you do this with really long "pretty" URLs</p>
<pre><code>/Products/Search/Type/{producttype}/Name/{name}/Address/{address}
</code></pre>
<p>or just resort to using url params</p>
<pre><code>/Products/Search?productType={producttype}&name={name}&address={address}
</code></pre>
|
<p>You can get the "pretty" urls, but not through the prettiest of means..</p>
<p>You can set up your url to be something like:</p>
<pre><code>/Products/Search/Type/{producttype}/Name_{name}/Address_{address}
</code></pre>
<p>Then a <a href="http://www.workingwith.me.uk/articles/scripting/mod_rewrite" rel="nofollow noreferrer">mod_rewrite</a> rule something like:</p>
<pre><code>RewriteRule ^Products/Search/Type/([a-z]+)(.*)?$ product_lookup.php?type=$1&params=$2 [NC,L]
</code></pre>
<p>This will give you 2 parameters in your <code>product_lookup</code> file:</p>
<pre><code>$type = {producttype}
$params = "/Name_{name}/Address_{address}"
</code></pre>
<p>You can then implement some logic in your <code>product_lookup.php</code> file to loop through <code>$params</code>, splitting it up on the "/", tokenising it according to whatever is before the "_", and then using the resulting parameters in your search as normal, e.g.</p>
<pre><code>// Split request params first on /, then figure out key->val pairs
$query_parts = explode("/", $params);
foreach($params as $param)
{
$param_parts = explode("_", $param);
// Build up associative array of params
$query[$param_parts[0]] = $param_parts[1];
}
// $query should now contain the search parameters in an assoc. array, e.g.
// $query['Name'] = {name};
</code></pre>
<p>Having the parameters as "pretty" urls rather than POSTs enables users to bookmark particular searches more easily.</p>
<p>An example of this in action is
<code><a href="http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/" rel="nofollow noreferrer">http://www.property.ie/property-for-sale/dublin/ashington/price_200000-550000/beds_1/</a></code>
- the user's selected params are denoted by the "_" (price range and beds) which can be translated internally into whichever param format you need, whilst keeping a nice readable url.</p>
<p>The code above is a trivial example without error checking (rogue delimiters etc in input) but should give you an idea of where to start. </p>
<p>It also assumes a LAMP stack (Apache for mod_rewrite and PHP) but could be done along the same lines using asp.net and <a href="https://stackoverflow.com/questions/60857/modrewrite-equivalent-for-iis-70">an IIS mod_rewrite equivalent</a>.</p>
|
<p>You can find an answer about <strong>Routing in .NET</strong> here:</p>
<p><a href="https://stackoverflow.com/questions/125826/what-is-the-best-method-to-achieve-dynamic-url-rewriting-in-aspnet#126426">What is the best method to achieve dynamic URL Rewriting in ASP.Net?</a></p>
<p>There you can find different resources on the subject.</p>
| 15,664
|
<p>EDIT: It seems to be something with having the two queues in the same schema.</p>
<p>I’m trying to experiment with queue propagation but I’m not seeing records in the destination queue. But that could easily be because I don’t have all the pieces in place.</p>
<p>Does anyone have a test case they could post? I’ll include what I tried below. I found the troubleshooting in the docs a little light and the propagation is such a black box, it’s hard to know why this isn’t moving.</p>
<p>Here’s what I have; no laughing.</p>
<hr>
<pre><code>CREATE OR REPLACE TYPE test_payload AS OBJECT(
test_id NUMBER,
test_dt DATE);
DECLARE
subscriber SYS.aq$_agent;
BEGIN
--- Create Originating Queue and start it
DBMS_AQADM.create_queue_table( queue_table => 'Test_MQT', queue_payload_type => 'Test_Payload',
multiple_consumers => TRUE ); --- multiple subscriber
DBMS_AQADM.create_queue( 'Test_Q', 'Test_MQT' );
DBMS_AQADM.start_queue( queue_name => 'Test_Q' );
--- Create Destination Queue and start it
DBMS_AQADM.create_queue_table( queue_table => 'Dest_MQT', queue_payload_type => 'Test_Payload',
multiple_consumers => TRUE );
DBMS_AQADM.create_queue( 'Dest_Q', 'Dest_MQT' );
DBMS_AQADM.start_queue( queue_name => 'Dest_Q' );
--- Add Subscriber and schedule propagation
subscriber := SYS.aq$_agent( 'test_local_sub', 'Dest_Q', NULL );
DBMS_AQADM.add_subscriber( queue_name => 'Test_Q', subscriber => subscriber );
DBMS_AQADM.schedule_propagation( queue_name => 'Test_Q', destination_queue => 'Dest_Q' );
END;
DECLARE
enqueue_options DBMS_AQ.enqueue_options_t;
message_properties DBMS_AQ.message_properties_t;
message_handle RAW( 16 );
MESSAGE test_payload;
BEGIN
MESSAGE := test_payload( 2, SYSDATE );
DBMS_AQ.enqueue( queue_name => 'Test_Q', enqueue_options => enqueue_options,
message_properties => message_properties, payload => MESSAGE, msgid => message_handle );
COMMIT;
END;
DECLARE
dequeue_options DBMS_AQ.dequeue_options_t;
message_properties DBMS_AQ.message_properties_t;
message_handle RAW( 16 );
MESSAGE test_payload;
BEGIN
dequeue_options.navigation := DBMS_AQ.first_message;
DBMS_AQ.dequeue( queue_name => 'Dest_Q', dequeue_options => dequeue_options,
message_properties => message_properties, payload => MESSAGE, msgid => message_handle );
DBMS_OUTPUT.put_line( 'Test_ID: ' || MESSAGE.test_id );
DBMS_OUTPUT.put_line( 'Test_Date: ' || MESSAGE.test_dt );
COMMIT;
END;
</code></pre>
|
<p>Perhaps you need to enable it?</p>
<pre><code>DBMS_AQADM.ENABLE_PROPAGATION_SCHEDULE(queue_name => 'Test_Q');
</code></pre>
|
<p>You might want to read thru this Tom Kyte thread on AQ:</p>
<p><a href="http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8760267539329#tom1246632800346467977" rel="nofollow noreferrer">http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:8760267539329#tom1246632800346467977</a></p>
| 26,192
|
<p>How does one dynamically load a new report from an embedded resource? I have created a reporting project that contains a report as an embedded resource. I added a second report file and use the following code to switch reports:</p>
<pre><code>this.reportViewer1.LocalReport.ReportEmbeddedResource = "ReportsApplication2.Report2.rdlc";
this.reportViewer1.LocalReport.Refresh();
this.reportViewer1.RefreshReport();
</code></pre>
<p>When this code executes, the original report remains visible in the report viewer.</p>
<p>I have also tried using</p>
<pre><code>LocalReport.LoadReportDefinition
</code></pre>
<p>but had the same result.</p>
|
<p>The answer: you have to call </p>
<pre><code><ReportViewer>.Reset();
</code></pre>
<p>prior to changing the value of ReportEmbeddedResource or calling LoadReportDefinition.</p>
<p>After you do so, you'll also have to call </p>
<pre><code><ReportViewer>.LocalReport.DataSources.Add( ... );
</code></pre>
<p>to re-establish the data sources.</p>
|
<p>a better way to reference your reports is by using the default value of ReportEmbeddedResource, <strong>don't hard code</strong> it just change the name of the report.</p>
<pre><code>//choose which report to load
string reportEmbeddedResource = this.orderReportViewer.LocalReport.ReportEmbeddedResource;
//remove the extention .rdlc
reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));
//remove name of current report ex: .invoice.rdlc
reportEmbeddedResource = reportEmbeddedResource.Remove(reportEmbeddedResource.LastIndexOf('.'));
//clear current reportEmbeddedResource
this.orderReportViewer.Reset();
if (_retailReceip)
{
this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + ".PrintReceipt.rdlc";
}
else
{
this.orderReportViewer.LocalReport.ReportEmbeddedResource = reportEmbeddedResource + ".PrintOrder.rdlc";
}
</code></pre>
| 19,711
|
<p>I am working on a project where I search through a large text file (large is relative, file size is about 1 Gig) for a piece of data. I am looking for a token and I want a dollar value immediately after that token. For example,</p>
<p>this is the token 9,999,999.99</p>
<p>So here's is how I am approaching this problem. After a little analysis it appears that the token is usually near the end of the file so I thought I would start searching from the end of the file. Here is the code I have so far (vb.net):</p>
<pre><code> Dim sToken As String = "This is a token"
Dim sr As New StreamReader(sFileName_IN)
Dim FileSize As Long = GetFileSize(sFileName_IN)
Dim BlockSize As Integer = CInt(FileSize / 1000)
Dim buffer(BlockSize) As Char
Dim Position As Long = -BlockSize
Dim sBuffer As String
Dim CurrentBlock As Integer = 0
Dim Value As Double
Dim i As Integer
Dim found As Boolean = False
While Not found And CurrentBlock < 1000
CurrentBlock += 1
Position = -CurrentBlock * BlockSize
sr.BaseStream.Seek(Position, SeekOrigin.End)
i = sr.ReadBlock(buffer, 0, BlockSize)
sBuffer = New String(buffer)
found = SearchBuffer(sBuffer, sToken, Value)
End While
</code></pre>
<p>GetFileSize is a function that returns the filesize. SearchBuffer is a function that will search a string for the token. I am not familiar with regular expressions but will explore it for that function.</p>
<p>Basically I read in a small chunk of the file search it and if I don't find it load another chunk and so on...</p>
<p>Am I on the right track or is there a better way? </p>
|
<p>I think you've got the right idea in chunking the file. You may want to read chunks in at line breaks rather than a set number of bytes, though. In your current implementation, if the token lies on a 1000 byte boundary it could get cut in half, preventing you from finding it. The same thing could cause the data to be cut off as well.</p>
|
<p>If you're going to use chunks, it would be wise to use blocks which are multiples of 512 bytes long, and seek on a 512 byte alignment, because that will tend to be more efficient in accessing the disk (which ultimately will be in 512 byte blocks).</p>
<p>There may be other granularities even better than that, but 512 would be a good start.</p>
| 31,262
|
<p>My team is developing a large java application which extensively queries a MySQL database (in different classes and modules).
I'd like to known if there is a pattern that allows me to be notified at compile time if there are queries that refer to a wrong table structure (for instance if I remove or add a field on a table and the query string refers to it), in order to prevent runtime errors.
This should work also for JOIN queries.</p>
|
<p>There's an open-source tool called DODS (Data Object Design Studio) that could do what you want. The DODS tool was originally part of the Enhydra Java application server project, and since the company backing that project went kablooey in 2002, DODS has been hosted and maintained at ObjectWeb. Anyway, it's open-source (LGPL).</p>
<p><a href="http://forge.objectweb.org/projects/dods" rel="nofollow noreferrer">http://forge.objectweb.org/projects/dods</a></p>
<p>The concept is that you describe your schema in an XML file, and DODS generates Java POJO classes with which you can query and manipulate the database tables. Of course every time you change your schema, you need to run DODS again to re-generate the ORM classes, and recompile your app against them. </p>
<p>But the result is that if a table or column disappears, and your app is querying database metadata that no longer exists, you do get a compile-time error, because your code is now calling a corresponding class or method that no longer exists.</p>
|
<p>I would say that the simple answer is "no". The more complete answer is "yes, to some degree", depending on your willingness to jump through hoops.</p>
<p>Unless you have a java representation of your database schema you will never be able to get compile time notification if your queries are wrong (these classes can be generated). Also, you must use these classes to build your queries, so the method you use today (query strings) must be abandoned. To be able to use the java classes to build your queries, you must also use tricks. <a href="http://code.google.com/p/liquidform/" rel="nofollow noreferrer">LiquidForm</a> uses the required tricks to build JPA queries, but I have not seen a similar library for constructing SQL queries (LiquidForm is new and quite brilliant). You would actually have to build a similar library yourself. So, as you see, getting compile time warnings when constructing SQLs is hard, but not impossible (only nearly impossible). But even if you should be able to create what I suggest, your java representation of the schema must be updated immediately after a schema change, so the generation of java classes would have to be built into your IDE or build tool.</p>
<p>I would suggest you rather have good unit tests that will notice when your queries become illegal as a result of schema change. This is the most common way to achieve what you want. Also, should you decide to "upgrade" to JPA, you could use LiquidForm to get what you want.</p>
| 48,560
|
<p>Was wondering if it is recomended to pass a database connection object around(to other modules) or let the method (in the other module) take care of setting it up. I am leaning toward letting the method set it up as to not have to check the state of the connection before using it, and just having the caller pass any needed data to the calling method that would be needed to setup the connection. </p>
|
<p>Personally I like to use tightly scoped connections; open them late, use them, and close them (in a "using" block, all within the local method). Connection pooling will deal with re-using the connection in most cases, so there is no real overhead in this approach.</p>
<p>The main advantage in passing connections <em>used</em> to be so that you could pass the transaction around; however, <a href="https://stackoverflow.com/questions/224689/transactions-in-net#224702"><code>TransactionScope</code></a> is a simpler way of sharing a transaction between methods.</p>
<p>Since the classes are implementation specific, I'd write each to open it's own native transaction. Otherwise, you can use the ado.net factory methods to create the appropriate type from the config file (the provider name).</p>
|
<p>I would use the web.config</p>
<pre><code><configuration>
<connectionStrings>
<add name="conn1" providerName="System.Data.SqlClient" connectionString="string here" />
<add name="conn2" providerName="System.Data.SqlClient" connectionString="string here" />
</connectionStrings>
</configuration>
</code></pre>
<p>Then you can reference it from anywhere in the application</p>
| 31,342
|
<p>I am working on a design spec for a new application that will be heavily workflow driven.</p>
<p>Before I re-invent the wheel, is there a decent lightweight workflow engine that plugs into ASP.NET already around?</p>
<p>Basically, I'm looking for something that handles moving through a defined set of workflow pages while handling state management automatically.</p>
<p>If this isn't around already, I'll definitely try to abstract the engine from my app and put it on codeplex, as it would be really handy.</p>
<p>Any suggestions?</p>
<p>Note: .NET 2.0, so no WWF, though I think WWF is overkill for my needs.</p>
<p>EDIT: Seems like there is a legitimate need for this, and there isn't a product out there...So I might build this.</p>
<p>Here is what I'm picturing:</p>
<ul>
<li>Custom Page class called WebFlowPage</li>
<li>All WebFlowPage's are registered in a Workflow mapper.</li>
<li>Each WebFlowPage has some form of state object.</li>
<li>A HttpHandler handles picking the appropriate WebFlowPage based upon the workflow, and populating it from the state object.</li>
</ul>
|
<p>Is the workflow dynamic, or static?</p>
<p>If the workflows are simple, you could roll your own workflow engine.
In certain situations, it can be fairly simple, and just a couple of data tables to handle the rules, processing and state.</p>
<p>Alot of workflow engines are built for large scale processing (credit card applications, for example). For small scale, you should at least consider your own, which would eliminate the overhead and dependency of/on an engine.</p>
|
<p>I don't think there is a workflow engine that will automatically handle state for you, but if you are moving through a set of pages like a process such as checkout on an ecommerce site, perhaps the ASP.NET wizard control could help you?</p>
| 40,768
|
<p>I'd like to know how to - if even possible - reflect what method calls are executed inside the method during execution. I'm especially interested in either external method calls (that is, methods in other classes) or calling some specific method like getDatabaseConnection().</p>
<p>My intention would be to monitor predefined objects' actions inside methods and execute additional code if some specific conditions are met like some method is called with specific values. The monitor would be completely external class or a set of classes with no direct access to the object to be monitored by no other way than reflection.</p>
|
<p><a href="http://www.eclipse.org/aspectj/" rel="nofollow noreferrer">Aspect J</a> will solve your problem.</p>
<p>Try to define a pointcut like this: </p>
<pre><code>pointcut profilling(): execution(public * *(..)) && (
within(com.myPackage..*) ||
</code></pre>
<p>In this way you will catch all the call to any public method within the package com.myPackage. Add as many within clauses you need.</p>
<p>Then add the following code:</p>
<pre><code>Object around(): profilling() {
//Do wherever you need before method call
proceed();
//Do wherever you need after method call
}
</code></pre>
<p>IF you want to learn something more about aspectJ follow this <a href="http://www.eclipse.org/aspectj/doc/released/progguide/index.html" rel="nofollow noreferrer">guide</a>.</p>
|
<p>I'd expect <a href="http://jakarta.apache.org/bcel/index.html" rel="nofollow noreferrer">BCEL</a> to be able to do this. From the web site:</p>
<blockquote>
<p>The Byte Code Engineering Library is
intended to give users a convenient
possibility to analyze, create, and
manipulate (binary) Java class files
(those ending with .class).</p>
</blockquote>
<p>The "analyze" part being the important bit here. The JavaDoc isn't visible on the web site (as far as I can see) so I can't easily be sure whether or not it'll help you, but it's a reasonable starting point.</p>
| 25,985
|
<p>Any idea anyone? Is it possible that we specify the name of the form input field?
How to go about doing that?</p>
|
<p>More generally, all JSF components have an ID.
If you don't provide one, JSF will create an automatic ID, using the format j<code>_</code>idXXX (<em>XXX</em> is a incremented number).</p>
<p>Some components implement the javax.faces.component.NamingContainer interface, in particular <code><h:form></code>.
This means that all children of this component will have their ID prefixed by the ID of this container, separated by a ':'.
So, in the example:</p>
<pre><code><h:form id="myForm">
<h:inputText id="myInput" .../>
</h:form>
</code></pre>
<p>the <em>real</em> ID of the input (i.e. the ID of the HTML input object) will be <strong>myForm:myInput</strong>.</p>
|
<p>For most pages which contain a view, form and some components, the clientID will be the colon seperated string contained the form-id and component-id. Example:</p>
<p>
</p>
<p>The input text client ID would be "myForm:myInputText". If you have nested within a subview, then that will be the first thing in the list, for example:</p>
<p>
</p>
<p>Now the input text client ID would be "mySubview:myForm:myInputText". </p>
| 33,230
|
<p>When I try to build my project I get the following message in the build window :</p>
<p><strong>========== Build: 0 succeeded or up-to-date, 0 failed, 1 skipped ==========</strong></p>
<p>I tried rebuilding , then building again , but it doesn't help . Is there a way to view more detailed messages ? The "skipped" part doesn't give me any info on what's wrong . I am using Visual Studio 2005 Professional Edition .</p>
|
<p>Check with the configuration manager like CMS said and make sure that you have the right platform set. A lot of the time when you use something like the MS Application Blocks the default platform is set to Itanium.</p>
|
<p>I generally run into that when the PC is low on resources (RAM), after closing things the build runs fine.</p>
| 47,738
|
<p>What do you think is the best way for obtaining the results of the work of a thread? Imagine a Thread which does some calculations, how do you warn the main program the calculations are done?</p>
<p>You could poll every X milliseconds for some public variable called "job finished" or something by the way, but then you'll receive the results later than when they would be available... the main code would be losing time waiting for them. On the other hand, if you use a lower X, the CPU would be wasted polling so many times.</p>
<p>So, what do you do to be aware that the Thread, or some Threads, have finished their work?</p>
<p>Sorry if it looks similar to this other <a href="https://stackoverflow.com/questions/289434/how-to-make-a-java-thread-wait-for-another-threads-output">question</a>, that's probably the reason for the <em>eben</em> answer, I suppose. What I meant was running lots of threads and know when all of them have finished, without polling them.</p>
<p>I was thinking more in the line of sharing the CPU load between multiple CPU's using batches of Threads, and know when a batch has finished. I suppose it can be done with <strong>Future</strong>s objects, but that blocking <em><strong>get</strong></em> method looks a lot like a hidden lock, not something I like.</p>
<p>Thanks everybody for your support. Although I also liked the answer by <em><strong>erickson</strong></em>, I think <em><strong>saua</strong></em>'s the most complete, and the one I'll use in my own code.</p>
|
<p>Don't use low-level constructs such as threads, unless you absolutely need the power and flexibility.</p>
<p>You can use a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html" rel="noreferrer">ExecutorService</a> such as the <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html" rel="noreferrer">ThreadPoolExecutor</a> to <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)" rel="noreferrer">submit()</a> <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Callable.html" rel="noreferrer">Callables</a>. This will return a <a href="http://java.sun.com/javase/6/docs/api/java/util/concurrent/Future.html" rel="noreferrer">Future</a> object.</p>
<p>Using that <code>Future</code> object you can easily check if it's done and get the result (including a blocking <code>get()</code> if it's not yet done).</p>
<p>Those constructs will greatly simplify the most common threaded operations.</p>
<p>I'd like to clarify about the blocking <code>get()</code>:</p>
<p>The idea is that you want to run some tasks (the <code>Callable</code>s) that do some work (calculation, resource access, ...) where you don't need the result <i>right now</i>. You can just depend on the <code>Executor</code> to run your code whenever it wants (if it's a <code>ThreadPoolExecutor</code> then it will run whenever a free Thread is available). Then at some point in time you probably <i>need</i> the result of the calculation to continue. At this point you're supposed to call <code>get()</code>. If the task already ran at that point, then <code>get()</code> will just return the value immediately. If the task didn't complete, then the <code>get()</code> call will wait until the task is completed. This is usually desired since you can't continue without the tasks result anyway.</p>
<p>When you don't need the value to continue, but would like to know about it if it's already available (possibly to show something in the UI), then you can easily call <code>isDone()</code> and only call <code>get()</code> if that returns <code>true</code>).</p>
|
<p>As noted by saua: use the constructs offered by java.util.concurrent. If you're stuck with a pre 1.5 (or 5.0) JRE, you ,might resort to kind of rolling your own, but you're still better of by using a backport: <a href="http://backport-jsr166.sourceforge.net/" rel="nofollow noreferrer">http://backport-jsr166.sourceforge.net/</a></p>
| 45,926
|
<p>I have a silverlight 2 beta 2 application that accesses a WCF web service. Because of this, it currently can only use basicHttp binding. The webservice will return fairly large amounts of XML data. This seems fairly wasteful from a bandwidth usage standpoint as the response, if zipped, would be smaller by a factor of 5 (I actually pasted the response into a txt file and zipped it.). </p>
<p>The request does have the "Accept-Encoding: gzip, deflate" - Is there any way have the WCF service gzip (or otherwise compress) the response?</p>
<p>I did find this <a href="http://www.vistax64.com/indigo/113763-wcf-client-j2ee-server-using-gzip.html" rel="noreferrer">link</a> but it sure seems a bit complex for functionality that should be handled out-of-the-box IMHO.</p>
<p>OK - at first I marked the solution using the System.IO.Compression as the answer as I could never "seem" to get the IIS7 dynamic compression to work. Well, as it turns out:</p>
<ol>
<li><p>Dynamic Compression on IIS7 <strong>was</strong> working al along. It is just that Nikhil's Web Developer Helper plugin for IE did not show it working. My guess is that since SL hands the web service call off to the browser, that the browser handles it "under the covers" and Nikhil's tool never sees the compressed response. I was able to confirm this by using Fiddler which monitors traffic external to the browser application. In fiddler, the response was, in fact, gzip compressed!!</p></li>
<li><p>The other problem with the System.IO.Compression solution is that System.IO.Compression does not exist in the Silverlight CLR.</p></li>
</ol>
<p>So from my perspective, the EASIEST way to enable WCF compression in Silverlight is to enable Dynamic Compression in IIS7 and write no code at all.</p>
|
<p>I didn't see a native way for WCF to do compression when doing a WCF project recently. I just used the System.IO.Compression namespace and made a quick compressor. Here's the code i used</p>
<pre><code>public static class CompressedSerializer
{
/// <summary>
/// Decompresses the specified compressed data.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="compressedData">The compressed data.</param>
/// <returns></returns>
public static T Decompress<T>(byte[] compressedData) where T : class
{
T result = null;
using (MemoryStream memory = new MemoryStream())
{
memory.Write(compressedData, 0, compressedData.Length);
memory.Position = 0L;
using (GZipStream zip= new GZipStream(memory, CompressionMode.Decompress, true))
{
zip.Flush();
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
result = formatter.Deserialize(zip) as T;
}
}
return result;
}
/// <summary>
/// Compresses the specified data.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="data">The data.</param>
/// <returns></returns>
public static byte[] Compress<T>(T data)
{
byte[] result = null;
using (MemoryStream memory = new MemoryStream())
{
using (GZipStream zip= new GZipStream(memory, CompressionMode.Compress, true))
{
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(zip, data);
}
result = memory.ToArray();
}
return result;
}
}
</code></pre>
<p>then i just had my services take in a byte array as an input, like such</p>
<pre><code>void ReceiveData(byte[] data);
</code></pre>
<p>Worked out well for me. </p>
|
<p>It should also be noted that you may need to add the mime type to <code>applicationHost.config</code> under <code><httpCompression><dynamicTypes></code> section in addition to enabling compression for the site:</p>
<pre><code><add mimeType="application/soap+msbin1" enabled="true" />
</code></pre>
<p>If certain dynamic responses are not being compressed (and some are) it could be a mime type issue. Use Fiddler to get the specifics associated with the request. Failed request tracing may be useful in determining whether or not IIS is even attempting to compression the response. If compression is correctly configured you will see a <code>NO_MATCHING_CONTENT_TYPE</code> in the <strong>complete trace</strong> section of the trace output.</p>
| 3,129
|
<p>In a C++ project, compilation dependencies can make a software project difficult to maintain. What are some of the best practices for limiting dependencies, both within a module and across modules?</p>
|
<ul>
<li><a href="http://en.wikipedia.org/wiki/Forward_declaration" rel="noreferrer">Forward Declarations</a></li>
<li><a href="http://en.wikipedia.org/wiki/Abstract_interface" rel="noreferrer">Abstract Interfaces</a></li>
<li><a href="http://en.wikipedia.org/wiki/Opaque_pointer" rel="noreferrer">The Pimpl Idiom</a></li>
</ul>
|
<p>I think you need to be very careful and considerate about this. Generally, you can limit dependencies by separating the code and using abstract interfaces (eg: function pointers or an object equivalent), but separation generally adds fragility. For example, you can call a module through a generic abstract interface to reduce the dependency on the actual object implementation, but you have to update the interface in sync with the object itself, or the code will fail at run-time.</p>
<p>I would say it's important to structure large projects in modules with a well-defined hierarchy, but within each module don't go overboard with breaking apart code to limit dependencies. If you're going for improved maintenance, you have to balance reducing dependencies with reducing code fragility.</p>
| 22,848
|
<p>How would you reference the models (Accord, CRV, Prius, etc) in this structure?
Is this a bad structure to be able to extract the makes...then use a make to get the models...then use the model to get the options?</p>
<pre><code>var cars = [
{
"makes" : "Honda",
"models" : [
{'Accord' : ["2dr","4dr"]} ,
{'CRV' : ["2dr","Hatchback"]} ,
{'Pilot' : ["base","superDuper"] }
]
},
{
"makes" : "Toyota",
"models" : [
{'Prius' : ["green","reallyGreen"]} ,
{'Camry' : ["sporty","square"]} ,
{'Corolla' : ["cheap","superFly"] }
]
}
];
</code></pre>
<p>Thanks</p>
|
<p>The structure:</p>
<pre><code>var cars = [
{ name: 'Honda', models: [
{ name: 'Accord', features: ['2dr', '4dr'] },
{ name: 'CRV', features: ['2dr', 'Hatchback'] },
{ name: 'Pilot', features: ['base', 'superDuper'] }
]},
{ name: 'Toyota', models: [
{ name: 'Prius', features: ['green', 'superGreen'] },
{ name: 'Camry', features: ['sporty', 'square'] },
{ name: 'Corolla', features: ['cheap', 'superFly'] }
]}
];
</code></pre>
<p>I wrote about the traversal and everything else <a href="https://stackoverflow.com/questions/180451/using-javascript-and-jquery-to-populate-related-select-boxes-with-array-structu#180926">here</a>.</p>
|
<p>If I were you, I wouldn't lump all your data into one big multidimensional array/object literal mess like that. I'd encapsulate each object and use methods to access the data. It'll mess with your brain a lot less.</p>
| 21,817
|
<p>I have applied a <code>Formatter</code> to a <code>JFormattedTextField</code> using a <code>FormatterFactory</code>, when a user clicks into the text field I want to select the contents. </p>
<p>A focus listener does not work as expected because the formatter gets called, which eventually causes the value to be reset which ultimately de-selects the fields contents. I think what is happening is that after the value changes, the Caret moves to the rightmost position and this deselects the field.</p>
<p>Does anyone have any knowledge of how to get around this and select the fields contents correctly?</p>
|
<p>Quick and dirty workaround is to use
EventQueue.invokeLater from your focusListener.</p>
<pre><code> EventQueue.invokeLater(new Runnable(){
public void run() { yourTextField.selectAll();}
});
</code></pre>
|
<p>which jdk are you using - any chance this is a bug in it?</p>
| 20,823
|
<p>What's the best way to identify if a string (is or) might be UTF-8 encoded? The Win32 API <code>IsTextUnicode</code> isn't of much help here. Also, the string will not have an UTF-8 BOM, so that cannot be checked for. And, yes, I know that only characters above the ASCII range are encoded with more than 1 byte.</p>
|
<p><a href="http://www.mozilla.org/projects/intl/chardet.html" rel="nofollow noreferrer">chardet</a> character set detection developed by Mozilla used in FireFox. <a href="http://mxr.mozilla.org/mozilla/source/intl/chardet/" rel="nofollow noreferrer">Source code</a></p>
<p><a href="http://jchardet.sourceforge.net/" rel="nofollow noreferrer">jchardet</a> is a java port of the source from mozilla's automatic charset detection algorithm. </p>
<p><a href="http://www.conceptdevelopment.net/Localization/NCharDet/" rel="nofollow noreferrer">NCharDet</a> is a .Net (C#) port of a Java port of the C++ used in the Mozilla and FireFox browsers.</p>
<p><a href="http://www.codeproject.com/KB/recipes/DetectEncoding.aspx" rel="nofollow noreferrer">Code project C#</a> sample that uses Microsoft's <a href="http://msdn.microsoft.com/en-us/library/aa767865(VS.85).aspx" rel="nofollow noreferrer">MLang</a> for character encoding detection.</p>
<p><a href="http://utrac.sourceforge.net/" rel="nofollow noreferrer">UTRAC </a> is a command line tool and library written in c++ to detect string encoding</p>
<p><a href="http://cpdetector.sourceforge.net/link.shtml" rel="nofollow noreferrer">cpdetector</a> is a java project used for encoding detection</p>
<p><a href="http://chsdet.sourceforge.net/" rel="nofollow noreferrer">chsdet</a> is a delphi project, and is a stand alone executable module for automatic charset / encoding detection of a given text or file.</p>
<p>Another useful post that points to a lot of libraries to help you determine character encoding <a href="http://fredeaker.blogspot.com/2007/01/character-encoding-detection.html" rel="nofollow noreferrer">http://fredeaker.blogspot.com/2007/01/character-encoding-detection.html</a></p>
<p>You could also take a look at the related question <a href="https://stackoverflow.com/questions/373081/how-can-i-best-guess-the-encoding-when-the-bom-byte-order-mark-is-missing">How Can I Best Guess the Encoding when the BOM (Byte Order Mark) is Missing?</a>, it has some useful content.</p>
|
<p>As an add-on to the previous <a href="https://stackoverflow.com/a/19308773/2215591">answer</a> about the Win32 mlang DetectInputCodepage() API, here's how to call it in C:</p>
<pre><code>#include <Mlang.h>
#include <objbase.h>
#pragma comment(lib, "ole32.lib")
HRESULT hr;
IMultiLanguage2 *pML;
char *pszBuffer;
int iSize;
DetectEncodingInfo lpInfo[10];
int iCount = sizeof(lpInfo) / sizeof(DetectEncodingInfo);
hr = CoInitialize(NULL);
hr = CoCreateInstance(&CLSID_CMultiLanguage, NULL, CLSCTX_INPROC_SERVER, &IID_IMultiLanguage2, (LPVOID *)&pML);
hr = pML->lpVtbl->DetectInputCodepage(pML, 0, 0, pszBuffer, &iSize, lpInfo, &iCount);
CoUninitialize();
</code></pre>
<p>But the test results are very disappointing:</p>
<ul>
<li>It can't distinguish between French texts in CP 437 and CP 1252, even though the text is completely unreadable if opened in the wrong code page.</li>
<li>It can detect text encoded in CP 65001 (UTF-8), but not text in UTF-16, which is wrongly reported as CP 1252 with good confidence!</li>
</ul>
| 49,407
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.