Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a cms which stores comments against articles. These comments can be both threaded and non threaded. Although technically they are the same just with the reply column left blank when it's not threaded. My application works on sqlLite, MySQL and pgsql so I need fairly standard SQL.
I currently have a comment table
```
comment_id
article_id
user_id
comment
timestamp
thread (this is the reply column)
```
My question is to figure out how to best represent the threaded comments in the database. Perhaps in a separate table that supports the tree set without the content and a simple table to hold the text? Perhaps in the way it already is? Perhaps another way?
If the comments are un-threaded I can easily just order by the timestamp.
If they are threaded I sort like this
```
ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))
```
As you can see from the ORDER BY, the commenting queries will not ever use an index as function based indexes only really live in Oracle. Help me have lightening fast comment pages. | I really like how [Drupal](http://drupal.org/) solves this problem. It assigns a thread id to each comment. This id starts at 1 for the first comment. If a reply is added to this comment, the id `1.1` is assigned to it. A reply to comment `1.1` is given the thread id `1.1.1`. A sibling of comment `1.1` is given the thread id `1.2`. You get the idea. Calculating these thread ids can be done easily with one query when a comment is added.
When the thread is rendered, all of the comments that belong to the thread are fetched in a single query, sorted by the thread id. This gives you the threads in the ascending order. Furthermore, using the thread id, you can find the nesting level of each comment, and indent it accordingly.
```
1
1.1
1.1.1
1.2
1.2.1
```
There are a few issues to sort out:
* If one component of the thread id grows to 2 digits, sorting by thread id will not produce the expected order. An easy solution is ensuring that all components of a thread id are padded by zeros to have the same width.
* Sorting by descending thread id does not produce the expected descending order.
Drupal solves the first issue in a more complicated way using a numbering system called vancode. As for the second issue, it is solved by appending a backslash (whose ASCII code is higher than digits) to thread ids when sorting by descending order. You can find more details about this implementation by checking the source code of the [comments module](http://drupalcode.org/project/drupal.git/blob/95b676c8de:/modules/comment/comment.module#l757) (see the big comment before the function comment\_get\_thread). | I know the answer is a bit late, but for tree data use a closure table, it is the proper relational way.
<http://www.slideshare.net/billkarwin/models-for-hierarchical-data>
It describes 4 methods:
* Adjcency list (the simple parent foreign key)
* Path enumeration (the Drupal strategy mentioned in the accepted answer)
* Nested sets
* Closure table (storing ancestor/descendant facts in a separate relation [table], with a possible distance column)
The last option has advantages of easy CRUD operations compared to the rest. The cost is space, which is O(n^2) size in the number tree nodes in the worst case, but probably not so bad in practice. | Fast Relational method of storing tree data (for instance threaded comments on articles) | [
"",
"sql",
"database-design",
"tree",
"database-agnostic",
"data-storage",
""
] |
I'm trying to accomplish simply adding a css class to a div on alternate rows in my `<itemtemplate/>` without going to the overhead of including a full blown `<alternatingitemtemplate/>` which will force me to keep a lot of markup in sync in the future.
I've seen a solution such as <http://blog.net-tutorials.com/2009/04/02/how-to-alternate-row-color-with-the-aspnet-repeater-control/> which I'm tempted to use but this still doesn't "smell" right to me.
Has anyone else got a more maintainable and straightforward solution? Ideally I'd like to be able to do something like:
```
<asp:repeater id="repeaterOptions" runat="server">
<headertemplate>
<div class="divtable">
<h2>Other Options</h2>
</headertemplate>
<itemtemplate>
<div class="item <%# IsAlternatingRow ? "dark" : "light" %>">
```
But I can't figure out how to implement `IsAlternatingRow` - even with extension methods. | There is no need to manage your own variable (either an incrementing counter or a boolean); you can see if the built-in [`ItemIndex`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeateritem.itemindex.aspx) property is divisible by two, and use that to set a css class:
```
class="<%# Container.ItemIndex % 2 == 0 ? "" : "alternate" %>"
```
This has the benefit of being completely based in your UI code (ascx or aspx file), and doesn't rely on JavaScript. | C#
```
class="<%# Container.ItemIndex % 2 == 0 ? "" : "alternate" %>"
```
VB
```
class="<%# iif(Container.ItemIndex Mod 2 = 0,"","alternate") %>"
``` | ASP.NET repeater alternate row highlighting without full blown <alternatingitemtemplate/> | [
"",
"c#",
"asp.net",
"data-binding",
"extension-methods",
"repeater",
""
] |
Context: .NET 3.5, VS2008. I'm not sure about the title of this question, so feel free to comment about the title, too :-)
Here's the scenario: I have several classes, say Foo and Bar, all of them implement the following interface:
```
public interface IStartable
{
void Start();
void Stop();
}
```
And now I'd like to have a container class, which gets an IEnumerable<IStartable> as an argument in its constructor. This class, in turn, should also implement the IStartable interface:
```
public class StartableGroup : IStartable // this is the container class
{
private readonly IEnumerable<IStartable> startables;
public StartableGroup(IEnumerable<IStartable> startables)
{
this.startables = startables;
}
public void Start()
{
foreach (var startable in startables)
{
startable.Start();
}
}
public void Stop()
{
foreach (var startable in startables)
{
startable.Stop();
}
}
}
```
So my question is: how can I do it without manually writing the code, and without code generation? In other words, I'd like to have somethig like the following.
```
var arr = new IStartable[] { new Foo(), new Bar("wow") };
var mygroup = GroupGenerator<IStartable>.Create(arr);
mygroup.Start(); // --> calls Foo's Start and Bar's Start
```
Constraints:
* No code generation (that is, no real textual code at compile time)
* The interface has only void methods, **with or without arguments**
Motivation:
* I have a pretty large application, with a lot of plugins of various interfaces. Manually writing a "group container" class for each interface "overloads" the project with classes
* Manually writing the code is error prone
* Any additions or signature updates to the IStartable interface will lead to (manual) changes in the "group container" class
* Learning
I understand that I have to use reflection here, but I'd rather use a robust framework (like Castle's [DynamicProxy](http://www.castleproject.org/dynamicproxy/index.html) or [RunSharp](http://www.codeproject.com/KB/dotnet/runsharp.aspx)) to do the wiring for me.
Any thoughts? | This isn't pretty, but it seems to work:
```
public static class GroupGenerator
{
public static T Create<T>(IEnumerable<T> items) where T : class
{
return (T)Activator.CreateInstance(Cache<T>.Type, items);
}
private static class Cache<T> where T : class
{
internal static readonly Type Type;
static Cache()
{
if (!typeof(T).IsInterface)
{
throw new InvalidOperationException(typeof(T).Name
+ " is not an interface");
}
AssemblyName an = new AssemblyName("tmp_" + typeof(T).Name);
var asm = AppDomain.CurrentDomain.DefineDynamicAssembly(
an, AssemblyBuilderAccess.RunAndSave);
string moduleName = Path.ChangeExtension(an.Name,"dll");
var module = asm.DefineDynamicModule(moduleName, false);
string ns = typeof(T).Namespace;
if (!string.IsNullOrEmpty(ns)) ns += ".";
var type = module.DefineType(ns + "grp_" + typeof(T).Name,
TypeAttributes.Class | TypeAttributes.AnsiClass |
TypeAttributes.Sealed | TypeAttributes.NotPublic);
type.AddInterfaceImplementation(typeof(T));
var fld = type.DefineField("items", typeof(IEnumerable<T>),
FieldAttributes.Private);
var ctor = type.DefineConstructor(MethodAttributes.Public,
CallingConventions.HasThis, new Type[] { fld.FieldType });
var il = ctor.GetILGenerator();
// store the items
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Stfld, fld);
il.Emit(OpCodes.Ret);
foreach (var method in typeof(T).GetMethods())
{
var args = method.GetParameters();
var methodImpl = type.DefineMethod(method.Name,
MethodAttributes.Private | MethodAttributes.Virtual,
method.ReturnType,
Array.ConvertAll(args, arg => arg.ParameterType));
type.DefineMethodOverride(methodImpl, method);
il = methodImpl.GetILGenerator();
if (method.ReturnType != typeof(void))
{
il.Emit(OpCodes.Ldstr,
"Methods with return values are not supported");
il.Emit(OpCodes.Newobj, typeof(NotSupportedException)
.GetConstructor(new Type[] {typeof(string)}));
il.Emit(OpCodes.Throw);
continue;
}
// get the iterator
var iter = il.DeclareLocal(typeof(IEnumerator<T>));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldfld, fld);
il.EmitCall(OpCodes.Callvirt, typeof(IEnumerable<T>)
.GetMethod("GetEnumerator"), null);
il.Emit(OpCodes.Stloc, iter);
Label tryFinally = il.BeginExceptionBlock();
// jump to "progress the iterator"
Label loop = il.DefineLabel();
il.Emit(OpCodes.Br_S, loop);
// process each item (invoke the paired method)
Label doItem = il.DefineLabel();
il.MarkLabel(doItem);
il.Emit(OpCodes.Ldloc, iter);
il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator<T>)
.GetProperty("Current").GetGetMethod(), null);
for (int i = 0; i < args.Length; i++)
{ // load the arguments
switch (i)
{
case 0: il.Emit(OpCodes.Ldarg_1); break;
case 1: il.Emit(OpCodes.Ldarg_2); break;
case 2: il.Emit(OpCodes.Ldarg_3); break;
default:
il.Emit(i < 255 ? OpCodes.Ldarg_S
: OpCodes.Ldarg, i + 1);
break;
}
}
il.EmitCall(OpCodes.Callvirt, method, null);
// progress the iterator
il.MarkLabel(loop);
il.Emit(OpCodes.Ldloc, iter);
il.EmitCall(OpCodes.Callvirt, typeof(IEnumerator)
.GetMethod("MoveNext"), null);
il.Emit(OpCodes.Brtrue_S, doItem);
il.Emit(OpCodes.Leave_S, tryFinally);
// dispose iterator
il.BeginFinallyBlock();
Label endFinally = il.DefineLabel();
il.Emit(OpCodes.Ldloc, iter);
il.Emit(OpCodes.Brfalse_S, endFinally);
il.Emit(OpCodes.Ldloc, iter);
il.EmitCall(OpCodes.Callvirt, typeof(IDisposable)
.GetMethod("Dispose"), null);
il.MarkLabel(endFinally);
il.EndExceptionBlock();
il.Emit(OpCodes.Ret);
}
Cache<T>.Type = type.CreateType();
#if DEBUG // for inspection purposes...
asm.Save(moduleName);
#endif
}
}
}
``` | It's not as clean an interface as the reflection based solution, but a very simple and flexible solution is to create a ForAll method like so:
```
static void ForAll<T>(this IEnumerable<T> items, Action<T> action)
{
foreach (T item in items)
{
action(item);
}
}
```
And can be called like so:
```
arr.ForAll(x => x.Start());
``` | How can I write a generic container class that implements a given interface in C#? | [
"",
"c#",
"generics",
"reflection",
"interface",
"containers",
""
] |
I have a couple Windows computers on my network that will be running a python script. A different set of configuration options should be used in the script depending on which computer is running this script.
How would I get that computer name in the python script?
Let's say the script was running on a computer named DARK-TOWER, I'd like to write something like this:
```
>>> python.library.get_computer_name()
'DARK-TOWER'
```
Is there a standard or third party library I can use? | It turns out there are three options (including the two already answered earlier):
```
>>> import platform
>>> import socket
>>> import os
>>> platform.node()
'DARK-TOWER'
>>> socket.gethostname()
'DARK-TOWER'
>>> os.environ['COMPUTERNAME'] # WORK ONLY ON WINDOWS
'DARK-TOWER'
``` | ```
import socket
socket.gethostname()
``` | Getting name of windows computer running python script? | [
"",
"python",
"windows",
"networking",
""
] |
Can I disable right click on my web page without using JavaScript? I ask this because most browsers allow user to disable JavaScript.
If not, how do I use JavaScript to disable right click? | You can do that with JavaScript by adding an event listener for the "contextmenu" event and calling the [`preventDefault()`](https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault) method:
```
document.addEventListener('contextmenu', event => event.preventDefault());
```
That being said: **DON'T DO IT.**
Why? Because it achieves nothing other than annoying users. Also many browsers have a security option to disallow disabling of the right click (context) menu anyway.
Not sure why you'd want to. If it's out of some misplaced belief that you can protect your source code or images that way, think again: you can't. | **DON'T**
Just, don't.
No matter what you do, you can't prevent users from having full access to every bit of data on your website. Any Javascript you code can be rendered moot by simply turning off Javascript on the browser (or using a plugin like NoScript). Additionally, there's no way to disable the ability of any user to simply "view source" or "view page info" (or use wget) for your site.
It's not worth the effort. It won't actually work. It will make your site actively hostile to users. They will notice this and stop visiting. There is no benefit to doing this, only wasted effort and lost traffic.
Don't.
**Update:** It seems this little topic has proven quite controversial over time. Even so, I stand by this answer to this question. Sometimes the correct answer is advice instead of a literal response.
People who stumble on this question in hopes of finding out how to create *custom* context menus should look elsewhere, such as these questions:
* [Making custom right-click context menus for my web-app](https://stackoverflow.com/questions/4495626/making-custom-right-click-context-menus-for-my-web-app), which relies on jQuery
* [How to add a custom right-click menu to a webpage](https://stackoverflow.com/questions/4909167/how-to-add-a-custom-right-click-menu-to-a-webpage), which uses pure javascript/html | How do I disable right click on my web page? | [
"",
"javascript",
""
] |
Which Java SOAP XML object serialization library would you recommend for **Java object exchange** with other platforms / languages (.NET, Delphi)?
Communication scenarios could look like this:
* Java object writer -> SOAP XML text -> .NET or Delphi object reader
* .NET or Delphi object writer -> SOAP XML text -> Java object reader
I know there is the XStream XML serialization library and JSON as alternative solutions, however since Delphi and .Net have built-in support for SOAP XML serialized objects, this would offer a 'standardized' way with support for advanced features like nested objects, arrays and so on.
**Edit:**
Meanwhile, I found **JAXB** - (<https://jaxb.dev.java.net/>), **JAXMe**, and **JiBX** - Binding XML to Java Code(<http://jibx.sourceforge.net/>). But they do not generate SOAP serialized XML by default.
A possible solution would be a web service library which is able to run without a HTTP server, and offers a simple file interface for the SOAP XML content (not a complete request, just a serialized object). **Axis 2** and **CXF** look very interesting. | I prefer JAX-WS (with JAXB 2.1 databinding) over the other liberaries I've used (JAX-RPC, Axis 1 and 2, but not XFire). The JAXB 2 databinding uses generics, which makes for a pleasant mapping of properties with a maxoccurs > 1. JAX-WS itself is reasonably well documented and provides a reasonably good API. The method and parameter annotations can get a bit out of hand in some cases - XML hell in annotation form. It usually isn't so bad.
One of the nice aspects of the JAX-WS stack is project Metro, which Sun co-developed with Microsoft and interoperates well with the web service support .NET 3.0, going so far as to implement MTOM in a workable fashion. | I would recommend [CXF](http://cxf.apache.org). It is a very good services stack and includes JAXB data binding and JAX-WS support. You may want to look at an open source integration platform like [Mule](http://www.mulesource.org) that includes CXF (also supports Axis and XStream) if you need more advanced transformation and routing of your messages. It is lightweight and can be embedded or run without an app server. | Which SOAP XML object serialization library for Java would you recommend? | [
"",
"java",
".net",
"delphi",
"xml-serialization",
"soap-serialization",
""
] |
I have a simple web service call, generated by a .NET (C#) 2.0 Windows app, via the web service proxy generated by Visual Studio, for a web service also written in C# (2.0). This has worked for several years, and continues to do so at the dozen or so places where it is running.
A new installation at a new site is running into a problem. When attempting to invoke the web service, it fails with the message saying:
> Could not establish a trust relationship for the SSL/TLS secure
> channel
The URL of the web service uses SSL (https://) -- but this has been working for a long time (and continues to do so) from many other locations.
Where do I look? Could this be a security issue between Windows and .NET that is unique to this install? If so, where do I set up trust relationships? I'm lost! | Thoughts (based on pain in the past):
* do you have DNS and line-of-sight to the server?
* are you using the correct name from the certificate?
* is the certificate still valid?
* is a badly configured load balancer messing things up?
* does the new ~~server~~ machine have the clock set correctly (i.e. so that the UTC time is correct [ignore local time, it is largely irrelevent]) - this certainly matters for WCF, so may impact regular SOAP?
* is there a certificate trust chain issue? if you browse from the server to the soap service, can you get SSL?
* related to the above - has the certificate been installed to the correct location? (you may need a copy in Trusted Root Certification Authorities)
* is the server's machine-level proxy set correctly? (which different to the user's proxy); see proxycfg for XP / 2003 (not sure about Vista etc) | The following snippets will fix the case where there is something wrong with the SSL certificate on the server you are calling. For example, it may be self-signed or the host name between the certificate and the server may not match.
**This is dangerous** if you are calling a server outside of your direct control, since you can no longer be as sure that you are talking to the server you think you're connected to. However, if you are dealing with internal servers and getting a "correct" certificate is not practical, use the following to tell the web service to ignore the certificate problems and bravely soldier on.
The first two use lambda expressions, the third uses regular code. The first accepts any certificate. The last two at least check that the host name in the certificate is the one you expect.
... hope you find it helpful
```
//Trust all certificates
System.Net.ServicePointManager.ServerCertificateValidationCallback =
((sender, certificate, chain, sslPolicyErrors) => true);
// trust sender
System.Net.ServicePointManager.ServerCertificateValidationCallback
= ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));
// validate cert by calling a function
ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
// callback used to validate the certificate in an SSL conversation
private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
bool result = cert.Subject.Contains("YourServerName");
return result;
}
``` | Could not establish trust relationship for SSL/TLS secure channel -- SOAP | [
"",
"c#",
".net",
"ssl",
"trust",
""
] |
I'm developing a small swing application, and I'm not sure if I should use the
printStackTrace().
If I get an exception I show a user via JOptionPane a message, e.g: file not found etc.
But at the same time, I'm using the printStackTrace(), I wasn't sure about neither showing the stack trace to a user nor not to print anything...just in case it would be needed.
Can I leave the printStackTrace there or why not to?
thank you for advice. | Log stack traces to a log file they wont mean anything to the end user anyway
Print meaningful error messages to users.
i.e File not found etc | A better idea is to replace those with the use of any Logging API, like [Log4J](http://logging.apache.org/log4j/1.2/index.html). And of course, as Paul mentioned, show the user meaningful error messages where ever appropriate. | Is it good to use printStackTrace() in swing program? | [
"",
"java",
"exception",
""
] |
What is the recommended approach to naming base classes? Is it prefixing the type name with "**Base**" or "**Abstract**" or would we just suffix it with "Base"?
Consider the following:
type: `ViewModel` e.g. *MainViewModel*, *ReportViewModel*
base class: `BaseViewModel` or `ViewModelBase` or `AbstractViewModel`
Also consider:
type: `Product` e.g. *VirtualProduct*, *ExpiringProduct*
base class: `BaseProduct` or `ProductBase` or `AbstractProduct`
Which do you think is more standard?
```
class Entity : EntityBase
{
}
```
or
```
class Entity : BaseEntity
{
}
``` | There are examples in the Framework with the Base suffix, e.g. `System.Configuration.Provider.ProviderBase`, `System.Web.SessionState.SessionStateStoreProviderBase`.
But by no means all abstract base classes in the Framework follow this convention (e.g. `System.Data.Common.DbParameter`, `System.Data.Common.DbCommand`).
Personally I would avoid using the suffix *unless* I wanted to emphasize the fact that it's an abstract class and felt that otherwise users of the class might expect the name to indicate a concrete implementation. | None of the above. Consider what purpose your base class provides; name it that. For example, the base class of Automobile and Bicycle could be Vehicle.
If you're creating base classes just to have a base class of one class, and with no purpose or reason other than that, you're probably doing something wrong. | C# Class naming convention: Is it BaseClass or ClassBase or AbstractClass | [
"",
"c#",
"naming-conventions",
"base-class",
""
] |
I have a slider with values ranging from 0 to 100.
I want to map them to a range from 100 to 10,000,000.
I've seen some functions scattered around the net but they're all in C++.
I need it in Javascript.
Any ideas? | You can use a function like this:
```
function logslider(position) {
// position will be between 0 and 100
var minp = 0;
var maxp = 100;
// The result should be between 100 an 10000000
var minv = Math.log(100);
var maxv = Math.log(10000000);
// calculate adjustment factor
var scale = (maxv-minv) / (maxp-minp);
return Math.exp(minv + scale*(position-minp));
}
```
The resulting values match a logarithmic scale:
```
js> logslider(0);
100.00000000000004
js> logslider(10);
316.22776601683825
js> logslider(20);
1000.0000000000007
js> logslider(40);
10000.00000000001
js> logslider(60);
100000.0000000002
js> logslider(100);
10000000.000000006
```
The reverse function would, with the same definitions for `minp`, `maxp`, `minv`, `maxv` and `scale`, calculate a slider position from a value like this:
```
function logposition(value) {
// set minv, ... like above
// ...
return (Math.log(value)-minv) / scale + minp;
}
```
All together, wrapped in a class and as a functional code snippet, it would look like this:
```
// Generic class:
function LogSlider(options) {
options = options || {};
this.minpos = options.minpos || 0;
this.maxpos = options.maxpos || 100;
this.minlval = Math.log(options.minval || 1);
this.maxlval = Math.log(options.maxval || 100000);
this.scale = (this.maxlval - this.minlval) / (this.maxpos - this.minpos);
}
LogSlider.prototype = {
// Calculate value from a slider position
value: function(position) {
return Math.exp((position - this.minpos) * this.scale + this.minlval);
},
// Calculate slider position from a value
position: function(value) {
return this.minpos + (Math.log(value) - this.minlval) / this.scale;
}
};
// Usage:
var logsl = new LogSlider({maxpos: 20, minval: 100, maxval: 10000000});
$('#slider').on('change', function() {
var val = logsl.value(+$(this).val());
$('#value').val(val.toFixed(0));
});
$('#value').on('keyup', function() {
var pos = logsl.position(+$(this).val());
$('#slider').val(pos);
});
$('#value').val("1000").trigger("keyup");
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input value or use slider:
<input id="value" />
<input id="slider" type="range" min="0" max="20" />
``` | Not quite answering the question, but for people interested, the reverse maping the last line is
```
return (Math.log(value)-minv)/scale + min;
```
just to document.
NOTE the value must be > 0. | Logarithmic slider | [
"",
"javascript",
"slider",
"logarithm",
""
] |
I'm a little stuck, it's due to my inexperience with html/css and iframes.
Basically, I've got a LH column, which is my menu. and a RH column which house's my content. the RH column is a iframe.
The problem is i can't get the height of the iframe to equal 100%, it's constrained by the height of the LH column.
See below;
<http://www.therussianfrostfarmers.com/>
it's driving me nuts, its seems so simple to fix.
Here's a portion of the relevant html;
```
<div id='wrapper'>
<div id='header'>
<img src="images/titleBart.gif" alt="rff"/>
</div>
<div id='menu'>
<div class='container'>
<%obj_itop%>
<plug:front_index />
<%obj_ibot%>
</div>
</div>
<div id='content'>
<!-- text and image -->
<plug:front_exhibit />
<!-- end text and image -->
</div>
<div class='clear-both'>
<!-- -->
</div>
</div>
```
and the corrosponding CSS;
```
#wrapper {
margin: 0 auto;
width:950px;
text-align: left;
background: #fff;
height:100% !important;
}
.clear-both { clear: both; }
#content {
width: 760px;
margin: 20px 0 0 190px;
padding:0;
height: 100% !important;
overflow: auto;
}
#menu {
width: 170px;
position:absolute;
margin:0;
padding:0;
overflow: auto;
}
.container {
margin:0;
padding:0;
}
```
Any help would be much appreciated,
thanks cam | The iFrame will need to resized using javascript - you can do it fairly easily using something like the below:
```
<body onload="resizeFrame(document.getElementById('myframe'))">
<iframe id="myframe" src="http://www.example.com/foo.html" />
<script type=”text/javascript”>
function resizeFrame(f)
{
// Get height of iframe once it has loaded content and then
// use this for the iframe height in parent doc
f.style.height = f.contentWindow.document.body.scrollHeight + “px”;
}
</script>
```
The above will evaluate the height of the rendered content in the iframe, take that height and then use it as the height of the iframe container.
Note, the above will work if your iframed content is on the same domain as the containing page. If it isn't, you'll run into security restrictions due to the [same origin policy](http://en.wikipedia.org/wiki/Same_origin_policy), which is a [little trickier to get around](https://stackoverflow.com/questions/153152/resizing-an-iframe-based-on-content/362564#362564)! | I'm not 100% sure on this, but I'm fairly certain that there is no way to do this without using JavaScript to dynamically size the iFrame. And if there is, it probably isn't easy.
It's happening because '100%' in CSS terms only takes up as much space as it can *of what is already on the page*. Since you have a left-hand column already, 100% will only go to the size of that column. | two column layout, left col height constrains right col height, don't know why...? | [
"",
"php",
"html",
"css",
"iframe",
""
] |
Some code for context:
```
class WordTable
{
public:
WordTable();
~WordTable();
List* GetListByAlphaKey(char key);
void AddListByKey(char key);
bool ListExists(char key);
bool WordExists(string word);
void AddWord(string word);
void IncrementWordOccurances(string word);
void Print();
private:
List *_listArray[33];
int _GetIndexByKey(char key);
};
class TableBuilder
{
public:
TableBuilder();
~TableBuilder();
void AnalyzeStream(fstream &inputStream);
void PrintResults();
private:
void _AnalyzeCursor(string data);
bool _WordIsValid(string data);
WordTable* _WordTable;
};
struct Element {
public:
string Word;
int Occurances;
Element* Next;
};
class List
{
public:
List();
~List();
Element* AddElement(string word);
void DeleteElement(Element* element);
void Print();
void Delete();
Element* First;
bool WordExists(string word);
void IncrementWordOccurances(string word);
private:
void _PrintElementDetails(Element* element);
};
```
**Requirements**
I must analyze text, building array of linked lists (where array contains list for each letter; list contains every word found in text), then print out results.
**Problem**
I can`t initialize array of lists in WordTable.cpp. I know that i've misunderstood something, but i got no ideas and time. Anyone?
*P.s. Yeah, that's a homework. STOP giving me advices about best practices, please... :)* | An initialization for `_listArray` would look like this:
```
WordTable::WordTable() {
for (int i=0; i<33; i++)
_listArray[i] = new List();
}
```
You don't really say what exactly the problem is so I'm not sure if this helps... | It's because you're creating an array of pointers to lists. Either change it to List \_listArray[33]; or initialize it like so:
```
for ( int i = 0; i < 33; ++i ) {
_listArray[i] = new List();
}
// and to access methods
_listArray[i]->AddElement( "word" );
``` | Array of linked lists in C++ | [
"",
"c++",
"arrays",
"linked-list",
""
] |
first time poster and TDD adopter. :-) I'll be a bit verbose so please bear with me.
I've recently started developing SOAP based web services using the Apache CXF framework, Spring and Commons Chain for implementing business flow. The problem I'm facing here is with testing the web services -- testing as in Unit testing and functional testing.
My first attempt at Unit testing was a complete failure. To keep the unit tests flexible, I used a Spring XML file to keep my test data in. Also, instead of creating instances of "components" to be tested, I retrieved them from my Spring Application context. The XML files which harbored data quickly got out of hand; creating object graphs in XML turned out to be a nightmare. Since the "components" to be tested were picked from the Spring Application Context, each test run loaded *all* the components involved in my application, the DAO objects used etc. Also, as opposed to the concept of unit test cases being centralized or concentrated on testing only the component, my unit tests started hitting databases, communicating with mail servers etc. Bad, really bad.
I knew what I had done wrong and started to think of ways to rectify it. Following an advice from one of the posts on this board, I looked up Mockito, the Java mocking framework so that I could do away with using real DAO classes and mail servers and just mock the functionality.
With unit tests a bit under control, this brings me to my second problem; the dependence on data. The web services which I have been developing have very little logic but heavy reliance on data. As an example, consider one of my components:
```
public class PaymentScheduleRetrievalComponent implements Command {
public boolean execute(Context ctx) {
Policy policy = (Policy)ctx.get("POLICY");
List<PaymentSchedule> list = billingDAO.getPaymentStatementForPolicy(policy);
ctx.put("PAYMENT_SCHEDULE_LIST", list);
return false;
}
}
```
A majority of my components follow the same route -- pick a domain object from the context, hit the DAO [we are using iBatis as the SQL mapper here] and retrieve the result.
So, now the questions:
- How are DAO classes tested esp when a single insertion or updation might leave the database in a "unstable" state [in cases where let's say 3 insertions into different tables actually form a single transaction]?
- What is the de-facto standard for functional testing web services which move around a lot of data i.e. mindless insertions/retrievals from the data store?
Your personal experiences/comments would be greatly appreciated. Please let me know in case I've missed out some details on my part in explaining the problem at hand.
-sasuke | I would recommend an in-memory database for running your unit tests against, such as HSQL. You can use this to create your schema on the fly (for example if you are using Hibernate, you can use your XML mappings files), then insert/update/delete as required before destroying the database at the end of your unit test. At no time will your test interfere with your actual database.
For you second problem (end-to-end testing of web services), I have successfully unit tested CXF-based services in the past. The trick is to publish your web service using a light-weight web server at the beginning of your test (Jetty is ideal), then use CXF to point a client to your web service endpoint, run your calls, then finally shut down the Jetty instance hosting your web service once your unit test has completed.
To achive this, you can use the JaxWsServerFactoryBean (server-side) and JaxWsProxyFactoryBean (client-side) classes provided with CXF, see this page for sample code:
<http://cwiki.apache.org/CXF20DOC/a-simple-jax-ws-service.html#AsimpleJAX-WSservice-Publishingyourservice>
I would also give a big thumbs up to SOAP UI for doing functional testing of your web service. JMeter is also extremely useful for stress testing web services, which is particularity important for those services doing database lookups. | I would stay well away from the "Context as global hashmap" 'pattern' if I were you.
Looks like you are testing your persistence mapping...
You might want to take a look at: [testing persistent objects without spring](http://www.time4tea.net/wiki/display/MAIN/Testing+Persistent+Objects+Without+Spring) | End to End testing of Webservices | [
"",
"java",
"testing",
"service",
""
] |
Is there a cross-platform way of getting the path to the *`temp`* directory in Python 2.6?
For example, under Linux that would be `/tmp`, while under XP `C:\Documents and settings\[user]\Application settings\Temp`. | That would be the [tempfile](http://docs.python.org/library/tempfile.html) module.
It has functions to get the temporary directory, and also has some shortcuts to create temporary files and directories in it, either named or unnamed.
Example:
```
import tempfile
print tempfile.gettempdir() # prints the current temporary directory
f = tempfile.TemporaryFile()
f.write('something on temporaryfile')
f.seek(0) # return to beginning of file
print f.read() # reads data back from the file
f.close() # temporary file is automatically deleted here
```
For completeness, here's how it searches for the temporary directory, according to the [documentation](https://docs.python.org/3/library/tempfile.html#tempfile.gettempdir):
> 1. The directory named by the `TMPDIR` environment variable.
> 2. The directory named by the `TEMP` environment variable.
> 3. The directory named by the `TMP` environment variable.
> 4. A platform-specific location:
> * On *RiscOS*, the directory named by the `Wimp$ScrapDir` environment variable.
> * On *Windows*, the directories `C:\TEMP`, `C:\TMP`, `\TEMP`, and `\TMP`, in that order.
> * On all other platforms, the directories `/tmp`, `/var/tmp`, and `/usr/tmp`, in that order.
> 5. As a last resort, the current working directory. | This should do what you want:
```
print(tempfile.gettempdir())
```
For me on my Windows box, I get:
```
c:\temp
```
and on my Linux box I get:
```
/tmp
``` | Cross-platform way of getting temp directory in Python | [
"",
"python",
"cross-platform",
"temporary-directory",
""
] |
Am not sure if what I am doing is absolutely correct. But here goes:
1. User logins into chat via web-based interface
2. User is informed of updates via Comet
3. User enters details which goto a PHP file which further connects to a Jabber server
Now the problem is that when the user wants to send a message, it's simple, run php in which i connect to jabber server and send the message. The problem arises when I am waiting for a message. Cause if I login and check messages and disconnect, on the other users end I will show up as disconnected.
Am I approaching this problem in a wrong way? Should I directly connect to the Jabber server (via javascript) instead of a PHP layer in between? How to recieve messages via PHP? | this is an inherent problem (or feature) with http - there are no lasting connections (not really). you need a workaround, there is no real solution.
you could do it with java or flash, but that's not really nice (javascript 4tw!).
the other possibility would be to create an intermediate client what translates connections between the browser and the webserver to connections between the webserver and the jabber server. *messy, but possible.*
or maybe there is an API that helps with this.
**directly connecting to the jabber server via javascript**
i possibly slept through the latest ajax-inventions, but afaik you can only communicate with the host the source-html file comes from (ignoring greasmonkey and addons). *no different domains, no different ports, period.* unless you're going to teach your jabber server how to serve your chatpage-html to the browser, this will get problematic. moreover, staying connected doesn't even work, because that would require multipart-responses. those are only supported by mozilla, and *this is why the ugly duckling COMET even exists in the first place.* comet itself is a workaround to avoid the inability to hold connections while transfering data. | I haven't tried it out, but you might want to look at [xmpphp](http://code.google.com/p/xmpphp/). Secondly, you might want to consider keeping the user logged in to the XMPP server (aka a Jabber server) for as long as they're logged in to your website. You probably want to have a timeout of some kind in case they leave your website and don't come back.
As for whether or not you should connect via JavaScript, I don't see why you couldn't. I would suggest that you go for whatever seems the simplest to you. You might want to check out [Strophe](http://code.stanziq.com/strophe/), which I hear good things about, for that case.
The only XMPP library that I've used extensively though is [headstock](http://trac.defuze.org/wiki/headstock), but that requires using [python](http://www.python.org) and [Kamaelia](http://www.kamaelia.org/Home). | PHP Jabber: if I login and check messages and disconnect, on the other users end I will show up as disconnected | [
"",
"php",
"chat",
"xmpp",
""
] |
Or is it all about semantics? | Short answer: no, they are exactly the same.
Guess it could in theory depend on the compiler; a really broken one might do something slightly different but I'd be surprised.
Just for fun here are two variants that compile down to exactly the same assembly code for me using x86 gcc version 4.3.3 as shipped with Ubuntu. You can check the assembly produced on the final binary with [objdump](http://linux.die.net/man/1/objdump) on linux.
```
int main()
{
#if 1
int i = 10;
do { printf("%d\n", i); } while(--i);
#else
int i = 10;
for (; i; --i) printf("%d\n", i);
#endif
}
```
**EDIT:** Here is an "oranges with oranges" while loop example that also compiles down to the same thing:
```
while(i) { printf("%d\n", i); --i; }
``` | If your for and while loops do the same things, the machine code generated by the compiler should be (nearly) the same.
For instance in some testing I did a few years ago,
```
for (int i = 0; i < 10; i++)
{
...
}
```
and
```
int i = 0;
do
{
...
i++;
}
while (i < 10);
```
would generate exactly the same code, or (and Neil pointed out in the comments) with one extra jmp, which won't make a big enough difference in performance to worry about. | Is there any performance difference between for() and while()? | [
"",
"c++",
"c",
"performance",
"for-loop",
"while-loop",
""
] |
In a web app I'm working on, I'm capturing onBeforeUnload to ask the user whether he *really* wants to exit.
Now, if he decides to stay, there are a number of things I'd like to do.
What I'm trying to figure out is that he actually chose to stay.
I can of course declare a SetTimeout for "x" seconds, and if that fires, then it would mean the user is still there (because we didn't get unloaded). The problem is that the user can take any time to decide whether to stay or not...
I was first hoping that while the dialog was showing, SetTimeout calls would not fire, so I could set a timeout for a short time and it'd only fire if the user chose to stay. However, timeouts **do** fire while the dialog is shown, so that doesn't work.
Another idea I tried is capturing mouseMoves on the window/document. While the dialog is shown, mouseMoves indeed don't fire, except for one weird exception that really applies to my case, so that won't work either.
Can anyone think of other way to do this?
Thanks!
---
(In case you're curious, the reason capturing mouseMove doesn't work is that I have an IFrame in my page, containing a site from another domain. If at the time of unloading the page, the focus is within the IFrame, while the dialog shows, then I get the MouseMove event firing ONCE when the mouse moves from inside the IFrame to the outside (at least in Firefox). That's probably a bug, but still, it's very likely that'll happen in our case, so I can't use this method). | What I ended up doing was hooking into the click event for my document, and once I received a click I considered the user had stayed.
It's not a good solution, in most cases (if you are a DiggBar) you'll have lots of false negatives (people will have stayed and you'll never know it), but in our case it made perfect sense, because people interact heavily with our site, not only with the framed sites.
Esentially, my code does this...
```
function OnBeforeUnload() {
Event.observe(document, "click", UserStayed);
if (IConsiderTheIFrameMightBeTryingToPopOut) {
return "The site is trying to escape. Do you want to stay?";
}
}
function UserStayed() {
Event.stopObserving(document, "click", UserStayed);
// New we know the user is still with us for sure.
}
``` | I've been researching this question online for the past few days and the answer, invariably, is "no" you cannot tell, for sure, that a user stayed or left (other than the fact that your app quits working if the user leaves). I hate "no" answers. I came up with the following utility.
```
var OnBeforeUnload = (function(){
var
FDUM = new Function,
AFFIRM = function(){ return true; };
var _reg = function(msg,opts){
opts = opts || {};
var
pid = null,
pre = typeof opts.prefire == 'function' ? opts.prefire : FDUM,
callback = typeof opts.callback == 'function' ? opts.callback : FDUM,
condition = typeof opts.condition == 'function' ? opts.condition : AFFIRM;
window.onbeforeunload = function(){
return condition() ? (pre(),setTimeout(function(){ pid = setTimeout(callback,20); },1),msg) : void 0;
}
window.onunload = function(){ clearTimeout(pid); };
}
var _unreg = function(){ window.onbeforeunload = null; }
return {
register : _reg,
unregister : _unreg
};
})();
```
So, a call such as
```
OnBeforeUnload.register('Hello!',{
condition:function_that_returns_true_to_fire_event_false_to_ignore,
prefire:function_to_call_on_page_exit_attempt,
callback:function_to_call_if_user_stays
});
```
condition will be called within the handler to see if it should activate or not. If so, prefire is executed before the popup is shown to the user (you may want to pause a video) and callback will occur ONLY if the user stays.
My logic was to initiate a setTimeout in the body of the event handler. The setTimeout will not execute until the user presses one of the buttons. After they do, it fires immediately. The setTimeout in this case does not call the callback, but a proxy function that executes another timeout for the callback with a delay of 20ms. If the user stays on the page, the callback executes. If not, then another handler is attached to onunload which clears the timeout that will call the callback, ensuring that the callback is never called. I've only had the chance to check it in Firefox, IE and Chrome, but it has worked thus far in all three without a hiccup.
I hope this helps people as frustrated as I was by the patent "no" given universally to this question. This code may not be perfect, but I think it's on the right track. | Detecting whether user stayed after prompting onBeforeUnload | [
"",
"javascript",
"onbeforeunload",
""
] |
I have a zip file containing a folder structure like
* main-folder/
+ subFolder1/
+ subFolder2/
+ subFolder3/
- file3.1
- file3.2
I would like to rename folder `main-folder` to let's say `versionXY` inside that very zip file using Java.
Is there a simpler way than extracting the whole zip file and recreating a new one using the new folder names? | Zip is an archive format, so mutating generally involves rewriting the file.
Some particular features of zip also get in the way (zip is full of "features"). As well as the central directory at the end of the archive, each component file is preceded by its file name. Zip doesn't have a concept of directories - file names are just strings that happen to include `"/"` characters (and substrings such as `"../"`.
So, you really need to copy the file using `ZipInputStream` and `ZipOutputStream`, renaming as you go. If you really wanted to you could rewrite the file in place doing your own buffering. The process does cause the contents to be recompressed as the standard API has no means of obtaining the data in compressed form.
**Edit:** @Doval points out that @megasega's [answer](https://stackoverflow.com/a/39038523/4725) uses [Zip File System Provider](https://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html) in NIO, new (relative to this answer) in Java SE 7. It's performance will likely be not great, as were the archive file systems in RISC OS' GUI of thirty years ago. | I think you'll be able to find help for this task using the [Commons Compress](http://commons.apache.org/compress/), especially [ZipArchiveEntry](http://commons.apache.org/compress/apidocs/org/apache/commons/compress/archivers/zip/ZipArchiveEntry.html) | Renaming a File/Folder inside a Zip File in Java? | [
"",
"java",
"zip",
"rename",
""
] |
I would like to store large dataset generated in Python in a Django model. My idea was to pickle the data to a string and upload it to FileField of my model. My django model is:
```
#models.py
from django.db import models
class Data(models.Model):
label = models.CharField(max_length=30)
file = models.FileField(upload_to="data")
```
In my Python program I would like to do the following:
```
import random, pickle
data_entry = Data(label="somedata")
somedata = [random.random() for i in range(10000)]
# Next line does NOT work
#data_entry.file.save(filename, pickle.dumps(somedata))
```
How should I modify the last line to store `somedata` in `file` preserving the paths defined with `upload_to` parameter? | **NOTE: *See other answers and comments below*** - old info and broken links removed (can't delete a once-accepted answer).
Marty Alchin has a section on this in chapter 3 of Pro Django, [review here](http://ericholscher.com/blog/2009/jan/21/review-pro-django-marty-alchin/). | Based on the answers to the questions I came up with the following solution:
```
from django.core.files.base import ContentFile
import pickle
content = pickle.dumps(somedata)
fid = ContentFile(content)
data_entry.file.save(filename, fid)
fid.close()
```
All of it is done on the server side and and users are NOT allowed to upload pickles. I tested it and it works all fine, but I am open to any suggestions. | How do I upload pickled data to django FileField? | [
"",
"python",
"django",
"file",
"upload",
"pickle",
""
] |
I have an AJAX application that downloads a JSON object and uses the data to add rows to an HTML <table> using Javascript DOM functions. It works perfectly... except in Internet Explorer. IE doesn't give any sort of error, and I've verified as best as I can that the code is being executed by the browser, but it simply has no effect. I created this quick and dirty page to demonstrate the problem:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>
<table id="employeetable">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</table>
<script type="text/javascript">
function addEmployee(employeeName, employeeJob) {
var tableElement = document.getElementById("employeetable");
if (tableElement) {
var newRow = document.createElement("tr");
var nameCell = document.createElement("td");
var jobCell = document.createElement("td");
nameCell.appendChild(document.createTextNode(employeeName));
jobCell.appendChild(document.createTextNode(employeeJob));
newRow.appendChild(nameCell);
newRow.appendChild(jobCell);
tableElement.appendChild(newRow);
alert("code executed!");
}
}
setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>
</body></html>
```
I haven't tried IE 8, but both IE 7 and IE 6 do not show the additional rows that are supposedly being added. I can't fathom why. Does anyone know a good workaround to this problem, or am I perhaps doing something wrong? | You need to create a TBODY element to add your new TR to and then add the TBODY to your table, like this:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head><title></title></head><body>
<table id="employeetable">
<tr>
<th>Name</th>
<th>Job</th>
</tr>
</table>
<script type="text/javascript">
function addEmployee(employeeName, employeeJob) {
var tableElement = document.getElementById("employeetable");
if (tableElement) {
var newTable = document.createElement('tbody'); // New
var newRow = document.createElement("tr");
var nameCell = document.createElement("td");
var jobCell = document.createElement("td");
nameCell.appendChild(document.createTextNode(employeeName));
jobCell.appendChild(document.createTextNode(employeeJob));
newRow.appendChild(nameCell);
newRow.appendChild(jobCell);
newTable.appendChild(newRow); // New
tableElement.appendChild(newTable); // New
alert("code executed!");
}
}
setTimeout("addEmployee(\"Bob Smith\", \"CEO\");", 1000);
setTimeout("addEmployee(\"John Franks\", \"Vice President\");", 2000);
setTimeout("addEmployee(\"Jane Doe\", \"Director of Marketing\");", 3000);
</script>
</body></html>
``` | Apparently, in IE you need to append your row to the TBody element, not the Table element...
See discussion at [Ruby-Forum](http://www.ruby-forum.com/topic/139836).
Expanding on the discussion there, the <table> markup is generally done without explicit <thead> and <tbody> markup, but the <tbody> ELEMENT is where you actually need to add your new row, as <table> does not contain <tr> elements directly. | Can't dynamically add rows to a <TABLE> in IE? | [
"",
"javascript",
"ajax",
"internet-explorer",
"cross-browser",
"html-table",
""
] |
Say we have two tables in an MS Access db:
Service Users:
```
| ID | Name | Other details... |
| 1 | Joe | Blah... |
| 2 | Fred | Qwerty... |
| 3 | Bob | Something else...|
```
Teams providing services:
```
| ID | TeamID | UserID |
| 1 | T1 | 1 |
| 2 | T2 | 1 |
| 3 | T2 | 2 |
| 4 | T3 | 2 |
| 5 | T3 | 3 |
```
I need to produce a summary query that produces a single row for each user, with the first several teams (by TeamID) assigned sitting in separate columns. Like:
Query:
```
| UserID | Name | Team1 | Team2 |
| 1 | Joe | T1 | T2 |
| 2 | Fred | T2 | T3 |
| 3 | Bob | T3 | Null |
```
I can get the Team1 column using max() from a sub select query, but I'm having a complete mental block on how to achieve Team2, Team3, etc. (Yes, I know that if there are more teams assigned to a user than I create columns the query will lose that information: that isn't a concern).
Edit: To clarify, the number of columns in the query will be fixed (in the actual query, there will always be 7). If there are less teams than columns the additional columns should be Null (as in example). If there are more teams than columns, only the first 7 teams will be shown in this summary.
Edit 2 - Possible solution which doesn't work...:
I tried...
```
SELECT UserTable.ID As UID, UserTable.Name,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
ORDER BY TeamID) As Team1
FROM UserTable
```
... which works fine. Unfortunately...
```
SELECT UserTable.ID As UID, UserTable.Name,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
ORDER BY TeamID) As Team1,
(SELECT TOP 1 TeamID FROM TeamTable WHERE UserTable.ID = TeamTable.UserID
AND TeamID <> Team1 ORDER BY TeamID) As Team2
FROM UserTable
```
... throws up a parameter box for Team1. An ideas on how to skip the first/second/etc... values from an jet query? | First, you need a query to assign a number from 1 to N to the teams associated to a user:
```
SELECT UserID, TeamID,
(SELECT count(*) FROM TeamTable t2 WHERE t2.TeamID <= TeamTable.TeamID and t2.UserID=TeamTable.UserID) AS position
FROM TeamTable
ORDER BY TeamID
```
Let's call this query TeamList.
Now, you can use this query in the main query, by calling it 7 times, each time filtering a different position:
```
SELECT UserTable.ID As UID, UserTable.Name,
(SELECT TeamID FROM TeamList WHERE UserTable.ID = TeamList.UserID AND position=1) As Team1,
(SELECT TeamID FROM TeamList WHERE UserTable.ID = TeamList.UserID AND position=2) As Team2,
[...]
FROM UserTable
```
You could assemble all this in a single query, but it's more practical to define the TeamList query and calling it multiple times.
Also note that this way the numbering is based on the order of TeamID. You can choose another order by changing the TeamList query, but the field you choose must have different unique values for each Team (or the <= comparison will generate wrong numbers).
Obviously, with a big number of rows performance would be terrible, but for a few hundreds it could be acceptable. You have to try. | A crosstab query should suit.
Query 1: Called TeamUser
```
SELECT Teams.UserID, ServiceUsers.SName, Teams.TeamID
FROM ServiceUsers
INNER JOIN Teams ON ServiceUsers.ID = Teams.UserID;
```
Crosstab
```
TRANSFORM First(TeamUser.TeamID) AS FirstOfTeamID
SELECT TeamUser.UserID, TeamUser.SName
FROM TeamUser
GROUP BY TeamUser.UserID, TeamUser.SName
PIVOT TeamUser.TeamID;
```
EDIT in response to comments
It should be possible to combine the two queries and to use a union query to reduce the number of entries.
```
TRANSFORM First(t.ATeamID) AS FirstOfATeamID
SELECT t.UserID, s.SName
FROM (SELECT Teams.UserID, First(Teams.ID) AS FirstOfID,
First(Teams.TeamID) AS ATeamID, "1st" As TeamCount
FROM Teams
GROUP BY Teams.UserID
UNION
SELECT Teams.UserID, First(Teams.ID) AS FirstOfID,
First(Teams.TeamID) AS ATeamID, "2nd" As TeamCount
FROM Teams
WHERE ID Not In (SELECT First(Teams.ID)
FROM Teams GROUP BY Teams.UserID)
GROUP BY Teams.UserID) t
INNER JOIN ServiceUsers s ON t.UserID = s.ID
GROUP BY t.UserID, s.SName
PIVOT t.TeamCount
``` | Flatten relational data for summary/export | [
"",
"sql",
"ms-access",
""
] |
I've made an image upload script using the `move_uploaded_file` function. This function seems to overwrite any preexisting file with the new one. So, I need to check if the target location already has a file. If it does then I need to append something to the filename(before the extension so that the file name is still valid) so the filename is unique. I'd like to have the change be minimal instead of something like appending the datetime, if possible.
How can I do this with PHP? | When uploading files I will nearly always rename them. Typically there will be some kind of database record for that file. I use the ID of that to guarantee uniqueness of the file. Sometimes I'll even store what the client's original filename was in the database too but I'll never keep it or the temporary name because there is no guarantee that information is good, that your OS will support it or that it's unique (which is your issue).
So just rename it to some scheme of your own devising. That's my advice.
If you don't have any database reference, then you could use [file\_exists()](http://au.php.net/file_exists) for this but there's no guarantee that between the time of checking if something exists and moving it that something else won't use that same filename that you'll then overwrite. This is a classic [race condition](http://en.wikipedia.org/wiki/Race_condition). | <https://www.php.net/manual/en/function.file-exists.php> | I made an upload script in PHP. How do I avoid overwriting files? | [
"",
"php",
""
] |
I'm writing a console utility to do some processing on files specified on the commandline, but I've run into a problem I can't solve through Google/Stack Overflow. If a full path, including drive letter, is specified, how do I reformat that path to be relative to the current working directory?
There must be something similar to the VirtualPathUtility.MakeRelative function, but if there is, it eludes me. | If you don't mind the slashes being switched, you could [ab]use `Uri`:
```
Uri file = new Uri(@"c:\foo\bar\blop\blap.txt");
// Must end in a slash to indicate folder
Uri folder = new Uri(@"c:\foo\bar\");
string relativePath =
Uri.UnescapeDataString(
folder.MakeRelativeUri(file)
.ToString()
.Replace('/', Path.DirectorySeparatorChar)
);
```
## As a function/method:
```
string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
{
folder += Path.DirectorySeparatorChar;
}
Uri folderUri = new Uri(folder);
return Uri.UnescapeDataString(folderUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
}
``` | You can use `Environment.CurrentDirectory` to get the current directory, and `FileSystemInfo.FullPath` to get the full path to any location. So, fully qualify both the current directory and the file in question, and then check whether the full file name starts with the directory name - if it does, just take the appropriate substring based on the directory name's length.
Here's some sample code:
```
using System;
using System.IO;
class Program
{
public static void Main(string[] args)
{
string currentDir = Environment.CurrentDirectory;
DirectoryInfo directory = new DirectoryInfo(currentDir);
FileInfo file = new FileInfo(args[0]);
string fullDirectory = directory.FullName;
string fullFile = file.FullName;
if (!fullFile.StartsWith(fullDirectory))
{
Console.WriteLine("Unable to make relative path");
}
else
{
// The +1 is to avoid the directory separator
Console.WriteLine("Relative path: {0}",
fullFile.Substring(fullDirectory.Length+1));
}
}
}
```
I'm not saying it's the most robust thing in the world (symlinks could probably confuse it) but it's probably okay if this is just a tool you'll be using occasionally. | Getting path relative to the current working directory? | [
"",
"c#",
"file-io",
""
] |
I'm trying to place a control that I have created on my `Canvas`. The idea is to be able to dynamically add them on the fly. Like on a button click or at the end of a `DispatchTimer`. I have the following, but it doesn't work:
```
FirstCircleControl mc = new FirstCircleControl();
Canvas.SetLeft(mc, 100);
Canvas.SetTop(mc, 100);
```
I don't see any control appear... | You need to add the control to the `Canvas` first.
```
yourCanvas.Children.Add(mc)
``` | Placing a control inside a canvas or grid is a two-step process.
1. Add the control to the container's child collection
2. Set the control's location within the container
You've got the 2nd step, but are missing the first.
**For a canvas**
```
Button childButton = new Button();
LayoutCanvas.Children.Add(childButton);
Canvas.SetLeft(childButton, 120);
Canvas.SetTop(childButton, 120);
```
**For a grid**
```
Button childButton = new Button();
LayoutGrid.Children.Add(childButton);
Grid.SetRow(childButton, 2);
Grid.SetColumn(childButton, 2);
``` | How do you dynamically place a control on a canvas in Silverlight? | [
"",
"c#",
"silverlight",
"canvas",
""
] |
i really love the jquery validation plugins, look neat stylish and accessible, but as you know JavaScript can be turned off and boom your user can enter what ever he wants, therefore you should validate on server too, so what is the best approach here ?
do double validation one with jquery and one on server side or is there a better solid secure way ? | The only way to go is to validate with jQuery and then do the same validation again on the server side.
Client side validation is only for making your application more user friendly. So validate the fields that will save the user some round-trips to the server and that will contribute to a better user experience.
Always validate on the server side. This protects you from attacks to your application. It also helps from feeding erroneous input to your code. | Well double validation is probably the only way to go - if the user disables javascript, then no validation will be executed on the client side, therefore you MUST have server side validation.
On the other hand - for the convenience of most users - there should be a client side validation mechanism so that round-trips to the server are minimized. | how to Validate Client Side with jquery and Server side at same time? | [
"",
"c#",
"asp.net",
"jquery",
""
] |
How can I find the number of arguments of a Python function? I need to know how many normal arguments it has and how many named arguments.
Example:
```
def someMethod(self, arg1, kwarg1=None):
pass
```
This method has 2 arguments and 1 named argument. | The previously accepted answer has been [*deprecated*](https://docs.python.org/3/library/inspect.html#inspect.getargspec) as of `Python 3.0`. Instead of using `inspect.getargspec` you should now opt for the `Signature` class which superseded it.
Creating a Signature for the function is easy via the [`signature` function](https://docs.python.org/3/library/inspect.html#inspect.signature):
```
from inspect import signature
def someMethod(self, arg1, kwarg1=None):
pass
sig = signature(someMethod)
```
Now, you can either view its parameters quickly by `str`ing it:
```
str(sig) # returns: '(self, arg1, kwarg1=None)'
```
or you can also get a mapping of attribute names to parameter objects via `sig.parameters`.
```
params = sig.parameters
print(params['kwarg1']) # prints: kwarg1=20
```
Additionally, you can call `len` on `sig.parameters` to also see the number of arguments this function requires:
```
print(len(params)) # 3
```
Each entry in the `params` mapping is actually a [`Parameter` object](https://docs.python.org/3/library/inspect.html#inspect.Parameter) that has further attributes making your life easier. For example, grabbing a parameter and viewing its default value is now easily performed with:
```
kwarg1 = params['kwarg1']
kwarg1.default # returns: None
```
similarly for the rest of the objects contained in `parameters`.
---
As for Python `2.x` users, while `inspect.getargspec` *isn't* deprecated, the language will soon be :-). The `Signature` class isn't available in the `2.x` series and won't be. So you still need to work with [`inspect.getargspec`](https://docs.python.org/3/library/inspect.html#inspect.getargspec).
As for transitioning between Python 2 and 3, if you have code that relies on the interface of `getargspec` in Python 2 and switching to `signature` in `3` is too difficult, *you do have the valuable option* of using [`inspect.getfullargspec`](https://docs.python.org/3/library/inspect.html#inspect.getfullargspec). It offers a similar interface to `getargspec` (a single callable argument) in order to grab the arguments of a function while also handling some additional cases that `getargspec` doesn't:
```
from inspect import getfullargspec
def someMethod(self, arg1, kwarg1=None):
pass
args = getfullargspec(someMethod)
```
As with `getargspec`, `getfullargspec` returns a `NamedTuple` which contains the arguments.
```
print(args)
FullArgSpec(args=['self', 'arg1', 'kwarg1'], varargs=None, varkw=None, defaults=(None,), kwonlyargs=[], kwonlydefaults=None, annotations={})
``` | ```
import inspect
inspect.getargspec(someMethod)
```
see [the inspect module](http://docs.python.org/library/inspect.html#classes-and-functions) | How can I find the number of arguments of a Python function? | [
"",
"python",
"function",
""
] |
Wonder if anyone can help me understand how to sum up the column of single column, ie a list of costs into one total cost.
I have been looking into this, and I think I'm on the right lines in undertsanding i need to sum the query, treat it as a subquery. However I'm not having much luck - do I need to give the subquery an alias, or is it a straight case of wrapping the query in a sum?
Here is the working query I want to sum up, all my attempts at sum left out for clarity!
```
SELECT TICKET_TYPE.PRICE AS TOTALSALES, RESERVATION.RESERVATION_ID,
CINEMA.LOCATION, PERFORMANCE.PERFORMANCE_DATE
FROM RESERVATION, TICKET, TICKET_TYPE, CINEMA, PERFORMANCE
WHERE TICKET_TYPE.TICKET_TYPE_ID = TICKET.TICKET_TYPE_ID
AND TICKET.RESERVATION_ID = RESERVATION.RESERVATION_ID
AND RESERVATION.PERFORMANCE_ID = PERFORMANCE.PERFORMANCE_ID
AND CINEMA.LOCATION = 'sometown'
AND PERFORMANCE.PERFORMANCE_DATE = to_date('01/03/2009','DD/MM/yyyy');
```
some of the data...
```
TOTALSALES RESERVATION_ID LOCATION PERFORMANCE_DATE
2.8 1 sometown 01-MAR-09
3.5 2 sometown 01-MAR-09
2.8 3 sometown 01-MAR-09
2.8 3 sometown 01-MAR-09
2.8 3 sometown 01-MAR-09
2 4 sometown 01-MAR-09
2.8 5 sometown 01-MAR-09
```
Thanks ! | Try:
You need to include a group by if you want the totals per ID.
```
SELECT SUM(TICKET_TYPE.PRICE) AS TOTALSALES
, RESERVATION.RESERVATION_ID
, CINEMA.LOCATION
, PERFORMANCE.PERFORMANCE_DATE
FROM RESERVATION
, TICKET
, TICKET_TYPE
, CINEMA
, PERFORMANCE
WHERE TICKET_TYPE.TICKET_TYPE_ID = TICKET.TICKET_TYPE_ID
AND TICKET.RESERVATION_ID = RESERVATION.RESERVATION_ID
AND RESERVATION.PERFORMANCE_ID = PERFORMANCE.PERFORMANCE_ID
AND CINEMA.LOCATION = 'sometown'
AND PERFORMANCE.PERFORMANCE_DATE = to_date('01/03/2009','DD/MM/yyyy');
GROUP BY RESERVATION.RESERVATION_ID
```
\*\*\*\* pretty much the same answer as above, I need to get better at refreshing before posting\*\*\*\* | You can sum a single column with
select sum(mycolumn) from mytable
When you mix aggregators (e.g., sum(), count()) in the select list with fields then you change the meaning of the query. You have to include a GROUP BY clause and the clause must contain every non-aggregate part of the select list.
You could do the sum, by itself, in a nested subquery then include that output in the outer select... | oracle - sum on a subquery? | [
"",
"sql",
"oracle",
""
] |
I'm having trouble keeping my app responsive to user actions. Therefore, I'd like to split message processing between multiple threads.
Can I simply create several threads, reading from the same message queue in all of them, and letting which ever one is able process each message?
If so, how can this be accomplished?
If not, can you suggest another way of resolving this problem? | You cannot have more than one thread which interacts with the message pump or any UI elements. That way lies madness.
If there are long processing tasks which can be farmed out to worker threads, you can do it that way, but you'll have to use another thread-safe queue to manage them. | If this were later in the future, I would say use the Asynchronous Agents APIs (plug for what I'm working on) in [the yet to be released Visual Studio 2010](http://blogs.msdn.com/nativeconcurrency) however what I would say given todays tools is to separate the work, specifically in your message passing pump you want to do as little work as possible to identify the message and pass it along to another thread which will process the work (hopefully there isn't Thread Local information that is needed). Passing it along to another thread means inserting it into a thread safe queue of some sort either locked or lock-free and then setting an event that other threads can watch to pull items from the queue (or just pull them directly). You can look at using a 'work stealing queue' with a thread pool for efficiency.
This will accomplish getting the work off the UI thread, to have the UI thread do additional work (like painting the results of that work) you need to generate a windows message to wake up the UI thread and check for the results, an easy way to do this is to have another 'work ready' queue of work objects to execute on the UI thread. imagine an queue that looks like this: `threadsafe_queue<function<void(void)>` basically you can check if it to see if it is non-empty on the UI thread, and if there are work items then you can execute them inline. You'll want the work objects to be as short lived as possible and preferably not do *any* blocking at all.
Another technique that can help if you are still seeing jerky movement responsiveness is to either ensure that you're thread callback isn't executing longer that 16ms and that you aren't taking any locks or doing any sort of I/O on the UI thread. There's a series of tools that can help identify these operations, the most freely available is the ['windows performance toolkit'](http://msdn.microsoft.com/en-us/performance/default.aspx). | Processing messages is too slow, resulting in a jerky, unresponsive UI - how can I use multiple threads to alleviate this? | [
"",
"c++",
"windows",
"multithreading",
"winapi",
"message-queue",
""
] |
I have this string in PHP:
```
$string = "name=Shake & Bake&difficulty=easy";
```
For which I want to parse into array:
```
Array
(
[name] => Shake & Bake
[difficulty] => easy
)
```
NOT:
```
Array
(
[name] => Shake
[difficulty] => easy
)
```
What is the most efficient way to do this ? | There's probably a more effective way of doing this, but try
```
$foo = 'name=Shake & Bake&difficulty=easy';
$pairs = preg_split('{&(?=[^\s])}',$foo);
//$pairs = preg_split('/&(?=[^\s])/',$foo); //equivalent, using different delimiters.
//$pairs = preg_split('%&(?=[^\s])%',$foo); //equivalent, using different delimiters.
$done = Array();
foreach($pairs as $keyvalue){
$parts = preg_split('{=}',$keyvalue);
$done[$parts[0]] = $parts[1];
}
print_r($done);
```
PHP's regex engine is PCRE, and it supports look ahead assertions. Googling around for PCRE, PHP, RegEx, look ahead assertions and zero width assertions should give you more than you ever want to know on the subject. | Regular expressions seems to be the best way to do this.
```
<html>
<head>
<title>Test params</title>
</head>
<body>
<?php
test_build('a=b');
test_build('blah=foo&foo=foo2');
test_build('blah=foo&foo&foo2=foo3&foo');
function test_build($string) {
echo "<p>Testing: $string</p>\n";
$params = build_params($string);
if ($params) {
echo "<ul>\n";
foreach ($params as $k => $v) {
echo "<li>'$k' => '$v'</li>\n";
}
echo "</ul>\n";
} else {
echo "<p>Found no parameters.</p>\n";
}
}
function build_params($string) {
preg_match_all('!([^=&]+)=([^=]*)(?=(&|$))!', $string, $matches);
$ret = array();
for ($i=0; $i<sizeof($matches[1]); $i++) {
$ret[$matches[1][$i]] = $matches[2][$i];
}
return $ret;
}
?>
</body>
</html>
```
Output:
```
Testing: a=b
* 'a' => 'b'
Testing: blah=foo&foo=foo2
* 'blah' => 'foo'
* 'foo' => 'foo2'
Testing: blah=foo&foo&foo2=foo3&foo
* 'blah' => 'foo&foo'
* 'foo2' => 'foo3&foo'
``` | Parse string with = and & as delimiters, but not all & are delimiters with look ahead | [
"",
"php",
"string",
"associative-array",
"text-parsing",
""
] |
How to create a windows registry watcher application using .Net,
I want this application to watch all the registry hooks and fire an event when a value change, this event will tell the **old and new value** for that value.
Thats possible? how? need just the idea or where to start | Take a look at [RegistryMonitor - a .NET wrapper class for RegNotifyChangeKeyValue](http://www.codeproject.com/Articles/4502/RegistryMonitor-a-NET-wrapper-class-for-RegNotifyC). | .Net framework does not contain embedded class to watch the registry.
But you still can use wrapped WinAPI calls or WMI interface (see [example](http://www.codeproject.com/KB/system/WMI_RegistryMonitor.aspx)) | How to create a windows registry watcher? | [
"",
"c#",
".net",
"vb.net",
"registry",
""
] |
I'm looking at adding logging to an application, and I'm considering using Kiwi syslogd and a freeware library (clSyslog) to send logging messages to the daemon. I briefly looked at log4c, and found compiling it with VC++ would take me more time than I had.
What tools do you use and recommend for logging messages? | In C++ I use a lot of [log4cxx](http://logging.apache.org/log4cxx/index.html).. Don't see why it's a problem to compile, works like champ. It brings lots of benefits. To name just a few - you can re-direct your log statements into syslog or windows event log without ever touching your code base - just change configuration. | Rolled my own -- this is especially useful for cross-platform stuff. You can take a look at [Boost.Log](http://sourceforge.net/projects/boost-log). Note this was rejected when submitted and hence not part of the standard distribution. AFAIK, the author had plans to rewrite this though. | Which Logging tools do you use for Windows? | [
"",
"c++",
"windows",
"logging",
""
] |
Please see code below. The destructors are never called. Anyone know why and how this can be rectified?
```
public partial class Form1 : Form
{
private Goo goo;
public Form1()
{
InitializeComponent();
goo = Goo.GetInstance();
}
}
public class Goo
{
private foo f = new foo();
private static Goo goo;
private Goo()
{}
public static Goo GetInstance()
{
if(goo!=null)
{
goo = new Goo();
}
return goo;
}
~Goo()
{
}
}
class foo
{
~foo()
{
}
}
``` | Objects referenced by static fields are not simply finalized unless you clear (set to `null`) the field - and even then it is non-deterministic and not guaranteed. Static fields count as root objects.
When (and why) would you expect this to be collected/finalized? It is still accessible... | Objects referenced by static fields are always reachable (assuming no class unloading or any other GC funkiness) and will never be collected. | Static instance, desctructor never called | [
"",
"c#",
"static",
"instance",
"destructor",
""
] |
I have downloaded the latest build of pyscopg2 and have tried to build and install it using the directions provided. However i always get an error saying that 'w' is undeclared. Does anybody have any experience with this? | This is an error that crops up when the build tools cannot find your Postgresql libraries. It means one of three things:
1. You don't have postgresql installed on your system. If so, download and build postgres, or download a pre-built psycopg2 binary for OS X.
2. You have postgresql installed on your system, but you installed from a binary package and therefore don't have the necessary libraries that psycopg2 needs. In this case, download and build postgres.
3. More commonly, though, this means that you have built postgres on your system and just need to instruct psycopg2 how to find the `pg_config` binary so that it can configure the compilation. Either:
a. put the path to pg\_config in your shell path (it's usually at `/usr/local/pgsql/bin/` if you built postgres from source using the defaults.
b. or, edit the `setup.cfg` file in the psycopg2 source folder and provide the full path to `pg_config` on the line that starts with `pg_config=`. Be sure to uncomment this line by removing the hash symbol at the front. If you built postgres using the defaults, the line will look something like:
`pg_config=/usr/local/pgsql/bin/pg_config` | using MacPorts on Snow Leopard
```
pg_config=/opt/local/lib/postgresql90/bin/pg_config
``` | Problem installing pyscopg2 on Mac OS X | [
"",
"python",
"database",
"django",
"macos",
""
] |
Currently I use '`ln`' command via `Runtime.exec()`. It works fine. The only problem is that in order to do this fork, we need twice the heap space of the application. My app is a 64 bit app with heap size around 10Gigs and thus its runs out of swap space. I couldn't find any configuration that could fix this.
I also want not to use JNI for the same.
Also I had heard somewhere that this facility will soon be provided in java 7. | you could try [JNA](https://github.com/twall/jna/) in place of JNI (JNA has some clear advantages over JNI); yes, check the [JSR 203](http://jcp.org/en/jsr/detail?id=203) | It’s easy in Java 7 using [createLink](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#createLink(java.nio.file.Path,%20java.nio.file.Path)):
```
Files.createLink(Paths.get("newlink"), Paths.get("existing"));
``` | Creating a Hard Link in java | [
"",
"java",
"operating-system",
""
] |
Here is a sample code:
```
public class TestIO{
public static void main(String[] str){
TestIO t = new TestIO();
t.fOne();
t.fTwo();
t.fOne();
t.fTwo();
}
public void fOne(){
long t1, t2;
t1 = System.nanoTime();
int i = 10;
int j = 10;
int k = j*i;
System.out.println(k);
t2 = System.nanoTime();
System.out.println("Time taken by 'fOne' ... " + (t2-t1));
}
public void fTwo(){
long t1, t2;
t1 = System.nanoTime();
int i = 10;
int j = 10;
int k = j*i;
System.out.println(k);
t2 = System.nanoTime();
System.out.println("Time taken by 'fTwo' ... " + (t2-t1));
}
```
}
This gives the following output:
100
Time taken by 'fOne' ... 390273
100
Time taken by 'fTwo' ... 118451
100
Time taken by 'fOne' ... 53359
100
Time taken by 'fTwo' ... 115936
Press any key to continue . . .
Why does it take more time (significantly more) to execute the same method for the first time than the consecutive calls?
I tried giving `-XX:CompileThreshold=1000000` to the command line, but there was no difference. | There are several reasons. The JIT (Just In Time) compiler may not have run. The JVM can do optimizations that differ between invocations. You're measuring elapsed time, so maybe something other than Java is running on your machine. The processor and RAM caches are probably "warm" on subsequent invocations.
You really need to make multiple invocations (in the thousands) to get an accurate per method execution time. | The issues mentioned by [Andreas](https://stackoverflow.com/questions/804620/java-why-do-two-consecutive-calls-to-the-same-method-yield-different-times-for-e/804694#804694) and the unpredictability of JIT are true, but still one more issue is the **class loader**:
The first call to `fOne` differs radically from the latter ones, because that is what makes the first call to `System.out.println`, which means that is when the class loader will from disk or file system cache (usually it's cached) all the classes that are needed to print the text. Give the parameter `-verbose:class` to the JVM to see how many classes are actually loaded during this small program.
I've noticed similar behavior when running unit tests - the first test to call a big framework takes much longer (in case of Guice about 250ms on a C2Q6600), even though the test code would be the same, because the first invocation is when hundreds of classes are loaded by the class loader.
Since your example program is so short, the overhead probably comes from the very early JIT optimizations and the class loading activity. The garbage collector will probably not even start before the program has ended.
---
**Update:**
Now I found a reliable way to find out what is *really* taking the time. Nobody had yet found out it, although it's closely related to class loading - it was **dynamic linking of native methods**!
I modified the code as follows, so that the logs would show when the tests begin and end (by looking when those empty marker classes are loaded).
```
TestIO t = new TestIO();
new TestMarker1();
t.fOne();
t.fTwo();
t.fOne();
t.fTwo();
new TestMarker2();
```
The command for running the program, with the right [JVM parameters](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) that show what is really happening:
```
java -verbose:class -verbose:jni -verbose:gc -XX:+PrintCompilation TestIO
```
And the output:
```
* snip 493 lines *
[Loaded java.security.Principal from shared objects file]
[Loaded java.security.cert.Certificate from shared objects file]
[Dynamic-linking native method java.lang.ClassLoader.defineClass1 ... JNI]
[Loaded TestIO from file:/D:/DEVEL/Test/classes/]
3 java.lang.String::indexOf (166 bytes)
[Loaded TestMarker1 from file:/D:/DEVEL/Test/classes/]
[Dynamic-linking native method java.io.FileOutputStream.writeBytes ... JNI]
100
Time taken by 'fOne' ... 155354
100
Time taken by 'fTwo' ... 23684
100
Time taken by 'fOne' ... 22672
100
Time taken by 'fTwo' ... 23954
[Loaded TestMarker2 from file:/D:/DEVEL/Test/classes/]
[Loaded java.util.AbstractList$Itr from shared objects file]
[Loaded java.util.IdentityHashMap$KeySet from shared objects file]
* snip 7 lines *
```
And the reason for that time difference is this: `[Dynamic-linking native method java.io.FileOutputStream.writeBytes ... JNI]`
We can also see, that the JIT compiler is not affecting this benchmark. There are only three methods which are compiled (such as `java.lang.String::indexOf` in the above snippet) and they all happen before the `fOne` method is called. | Why do two consecutive calls to the same method yield different times for execution? | [
"",
"java",
"benchmarking",
"microbenchmark",
""
] |
I am working with Google App Engine and Python.
I have a model with Items.
Immediately after I insert an item with item.put()
I want to get it's key and redirect to a page using this key.
Something like:
```
redirectUrl = "/view/key/%s/" % item.key
self.redirect(redirectUrl)
``` | Thanks for the initiative Scott Kirkwood.
I was actually missing the ()
```
redirectUrl = "/view/key/%s/" % item.key()
self.redirect(redirectUrl)
```
Good to know that in google datastore you don't need to use anything like Scope\_identity, but you can just get the item.key() just after item.put().. | Also, item.put() returns the key as the result, so it's hardly ever necessary to fetch that key immediately again -- just change your sequence, e.g
```
item.put()
redirectUrl = "/view/key/%s/" % item.key()
```
into
```
k = item.put()
redirectUrl = "/view/key/%s/" % k
``` | How to get last inserted item key in Google App Engine | [
"",
"python",
"google-app-engine",
""
] |
I am looking for a parser generator for Java that does the following: My language project is pretty simple and only contains a small set of tokens.
Output in pure READABLE Java code so that I can modify it (this why I wouldn't use ANTLR)
Mature library, that will run and work with at least Java 1.4
I have looked at the following and they might work: JavaCC, jlex, Ragel? | You should use [Rats](http://www.cs.nyu.edu/rgrimm/xtc/rats.html)... This way, you don't have to separate lexer and parser and then if you want to extend your project that will be trivial. It's in java and then you can process your AST in Java... | Maybe you're looking for parser *combinators* instead of parser *generators*? See [this paper](http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.29.1452) and [JParsec](http://jparsec.codehaus.org/).
It's a really bad idea to edit generated parser code--it's a lot easier to edit the grammar file and then recompile it. Unless you're doing it for educational purposes, in which case ANTLR prides itself in generating pretty readable code for such a powerful parser generator. | Parser, Generator for Java with the following requirements | [
"",
"java",
"parsing",
"parser-generator",
"javacc",
""
] |
If i iterate over a STL container i sometimes need to know if the current item is the last one in the sequence. Is there a better way, then doing something like this? Can i somehow convert rbegin()?
```
std::vector<int> myList;
// ....
std::vector<int>::iterator lastit = myList.end();
lastit--;
for(std::vector<int>::iterator it = myList.begin(); it != myList.end(); it++) {
if(it == lastit)
{
// Do something with last element
}
else
{
// Do something with all other elements
}
``` | Try the following
```
std::vector<int>::iterator it2 = (++it);
if ( it2 == myList.end() ) {
...
}
```
The following should work as well
```
if ( it+1 == myList.end() ) {
// it is last
...
}
``` | Maybe you can iterate backwards (use `rbegin`/`rend`) and put your special task before the loop or replace the end check with `it != lastit` and put the special handling after the loop | How do you determine the last valid element in a STL-Container | [
"",
"c++",
"stl",
""
] |
Since starting at a new company I've noticed that they use unity cpp files for the majority of our solution, and I was wondering if anyone is able to give me a definitive reason as to why and how these speed up the build process? I would've thought that editing one cpp file in the unity files will force recompilation of all of them. | Very similar question and good answers here: [#include all .cpp files into a single compilation unit?](https://stackoverflow.com/questions/543697/include-all-cpp-files-into-a-single-compilation-unit)
The summary seems to be that less I/O overhead is the major benefit.
See also [The Magic Of Unity Builds](http://buffered.io/posts/the-magic-of-unity-builds/) as linked in the above question as well. | Lee Winder posted his experiences with the Unity Builds - [The Evils of Unity Builds](http://web.archive.org/web/20161021225056/https://engineering-game-dev.com/2009/12/15/the-evils-of-unity-builds/)
His conclusion is:
> Unity builds. I don’t like them. | The benefits / disadvantages of unity builds? | [
"",
"c++",
"build-process",
"compilation",
""
] |
I'd like to get all the element name from a xml file, for example the xml file is,
```
<BookStore>
<BookStoreInfo>
<Address />
<Tel />
<Fax />
<BookStoreInfo>
<Book>
<BookName />
<ISBN />
<PublishDate />
</Book>
<Book>
....
</Book>
</BookStore>
```
I would like to get the element's name of "BookName". "ISBN" and "PublishDate " and only those names, not include " BookStoreInfo" and its child node's name
I tried several ways, but doesn't work, how can I do it? | Well, with `XDocument` and LINQ-to-XML:
```
foreach(var name in doc.Root.DescendantNodes().OfType<XElement>()
.Select(x => x.Name).Distinct())
{
Console.WriteLine(name);
}
```
There are lots of similar routes, though. | Using XPath
```
XmlDocument xdoc = new XmlDocument();
xdoc.Load(something);
XmlNodeList list = xdoc.SelectNodes("//BookStore");
```
gives you a list with all nodes in the document named BookStore | C# how can I get all elements name from a xml file | [
"",
"c#",
"xml",
""
] |
I'm fooling around with the XNA framework.
To help me around I made a helper class that looks like this:
```
ActorHolder
+ SpriteBatch (SpriteBatch)
+ ContentManager (ContentManager)
- drawables (IList<IDrawable>)
- updatables (IList<IUpdatable>)
+ ActorHolder(GraphicsDevice, ContentManager)
+ Draw(GameTime)
+ Update(GameTime)
+ AddActor(IActor)
+ RemoveActor(IActor)
+ GetCollidingActors(IActor)
```
Now I want to unit test this class. But as you see my constructor needs a graphics device and a contentmanager. While I think this makes sence in my application, it doesn't in my tests.
Should I mock these two just in order to unit test or is my design flawed?
--UPDATE--
I found a link to a project that might help out: <http://scurvytest.codeplex.com/>
Don't have any xp with it yet as coding has to make room for social life a bit.
--Note--
Excuse me my UML French, my company doesn't use it so I never used it except back at school. | I am "mocking" the graphics device by actually creating a real one on an invisible window. Performance is surprisingly good - 12 seconds for about 1500 tests.
It allows me to test code which requires a graphics device and do some basic verification (eg. is the right texture set, has the vertex buffer been selected, etc.). This could be improved by using the reference rasterizer with the DirectX Debug Runtime to do more intensive checking.
If I need to verify what gets sent to the graphics device, I create an interface through which the code-under-test can send the vertices - which can then be easily mocked with standard mock object frameworks.
Check this question for another discussion about mocking XNA graphics device dependent classes: [Mocking Texture2D](https://stackoverflow.com/questions/1308560/xna-mocking-texture2d)
Here are the classes I'm using to "mock" using a real graphics device:
[MockedGraphicsDeviceService.cs](https://devel.nuclex.org/framework/browser/graphics/Nuclex.Graphics/trunk/Source/MockedGraphicsDeviceService.cs?rev=1046), [MockedGraphicsDeviceService.Test.cs](https://devel.nuclex.org/framework/browser/graphics/Nuclex.Graphics/trunk/Source/MockedGraphicsDeviceService.Test.cs?rev=1046)
(edit: fixed broken links) | This seems like a very valid usage scenario for mocking. I don't think there is a flaw in this design -
One reason mocking exists is to help with filling in resource requirements of an interface that are not available at testing time, such as remote objects, or in your case, the graphics resources. Mocking the graphics device and content manager seems appropriate here, to me. | Unit testing XNA: Do I need to Mock my GraphicsDevice | [
"",
"c#",
".net",
"unit-testing",
"xna",
""
] |
In PHP, I know there is no official way to delete items once they have been put into an array. But there must be a "best-method" solution to my problem. I believe this may lie in the `array_filter` function.
Essentially, I have a shopping cart object that stores items in a hashtable. Imagine you can only ever buy one of any item at a time.
I do
```
add_item(1);
add_item(2);
remove_item(1);
```
`get_count()` still returns 2.
```
var $items;
function add_item($id) {
$this->items[$id] = new myitem($id);
}
function remove_item($id) {
if ($this->items[$id]) {
$this->items[$id] = false;
return true;
} else {
return false;
}
}
function get_count() {
return count($this->items);
}
```
What do people think is the best method to use in get\_count? I can't figure out the best way to use array\_filter that simply doesn't return false values (without writing a seperate callback).
Thanks :) | No official way? Sure there is! [Unset](https://www.php.net/unset)!
```
<?php
class foo
{
var $items = array();
function add_item($id) {
$this->items[$id] = new myitem($id);
}
function remove_item($id)
{
unset( $this->items[$id] );
}
function get_count() {
return count($this->items);
}
}
class myitem
{
function myitem( $id )
{
// nothing
}
}
$f = new foo();
$f->add_item( 1 );
$f->add_item( 2 );
$f->remove_item( 1 );
echo $f->get_count();
```
Also, is this PHP4? Because if not, you should look into some of the SPL stuff like [ArrayObject](https://www.php.net/manual/en/class.arrayobject.php) or at least the the [Countable](https://www.php.net/manual/en/class.countable.php) and [ArrayAccess](https://www.php.net/manual/en/class.arrayaccess.php) interfaces.
## EDIT
Here's a version using the interfaces directly
```
<?php
class foo implements ArrayAccess, Countable
{
protected $items = array();
public function offsetExists( $offset )
{
return isset( $this->items );
}
public function offsetGet( $offset )
{
return $this->items[$offset];
}
public function offsetSet( $offset, $value )
{
$this->items[$offset] = $value;
}
public function offsetUnset( $offset )
{
unset( $this->items[$offset] );
}
public function count()
{
return count( $this->items );
}
public function addItem( $id )
{
$this[$id] = new myitem( $id );
}
}
class myitem
{
public function __construct( $id )
{
// nothing
}
}
$f = new foo();
$f->addItem( 1 );
$f->addItem( 2 );
unset( $f[1] );
echo count( $f );
```
And here's a version as an implementation of ArrayObject
```
<?php
class foo extends ArrayObject
{
public function addItem( $id )
{
$this[$id] = new myitem( $id );
}
}
class myitem
{
public function __construct( $id )
{
// nothing
}
}
$f = new foo();
$f->addItem( 1 );
$f->addItem( 2 );
unset( $f[1] );
echo count( $f );
``` | ```
if ($this->items[$id]) {
```
May return a warning, should use array\_key\_exists or isset.
unset() seems cleaner than assigning false when removing an item (will also get rid of your count problem). | PHP - Delete Item from Hash Table (array) using array_filter | [
"",
"php",
"arrays",
"array-filter",
""
] |
Our application allows you to save any file type into the MS SQL DB as a blob/image. I now have to provide the feature to search for text within files. Similar to the standard Windows "find in files" search.
What is the best way of achieving this? I've used a StreamReader to read all text from the file and then used Regex to do a match. Just not sure if this is the most efficient way to search within files.
Thanks | You should look into SQL Server's full text searching feature.
Here are some good articles:
> [Full-Text Search](http://msdn.microsoft.com/en-us/library/ms142571.aspx)
> [SQL Server Full Text Search](http://en.wikipedia.org/wiki/SQL_Server_Full_Text_Search)
> [SQL Server Full-Text Indexing](http://www.developer.com/db/article.php/3446891)
I think you will find that trying to pull back many large records from the database and then searching them in memory to be quite inefficient. This is an area where your RDBMS excels, and if configured correctly, can make your life a lot simpler. | You will probably save a lot of time if you use full text search in the sql server ? That will let you query the files as well as handle some very complex queries. It is able to search inside blobs using iFilters (like microsoft frontpage)
This is a good primer to the basics <http://aspalliance.com/1512_understanding_full_text_search_in_sql_server_2005> .
Doing it this way you can leverage the work MS did in full text search; and gain from their interfaces if your file types are not supported (most comment document formats are supported directly or but their producer doc, docx, xls, pdf etc) | Find text in files (C#) | [
"",
"c#",
"search",
""
] |
Basic question: How do I load an Excel template for use with POI and then save it to an XLS file?
*Edit:*
The answer is:
```
FileInputStream inputStream = new FileInputStream(new File(templateFile));
Workbook workbook = new HSSFWorkbook(inputStream);
```
(Just load the template as a workbook and then write the workbook as an XLS file elsewhere.) | Have you tried loading it up as a standard .xls using POI, amending it and then saving it ?
This is the approach I've used for inserting macros in a POI-generated .xls. I create the file with the macro (admittedly as an .xls) and then load it into my app, populate with data and save as a newly-created .xls. That all worked fine. | You can directly load an .xls that will act as the template, and modify it.
```
POIFSFileSystem fs = new POIFSFileSystem(
new FileInputStream("template.xls"));
HSSFWorkbook wb = new HSSFWorkbook(fs, true);
```
Will load an xls, preserving its structure (macros included). You can then modify it,
```
HSSFSheet sheet1 = wb.getSheet("Data");
...
```
and then save it.
```
FileOutputStream fileOut = new FileOutputStream("new.xls");
wb.write(fileOut);
fileOut.close();
```
Hope this helps. | Using Excel templates with Apache POI | [
"",
"java",
"excel",
"apache-poi",
""
] |
This is my first StackOverflow question so be nice! :-)
I recently came across the following example in some C# source code:
```
public IFoo GetFooInstance()
{
#IF DEBUG
return new TestFoo();
#ELSE
return new Foo();
#ENDIF
}
```
Which lead me to these questions:
1. Is the use of "#IF DEBUG" unofficially deprecated? If not what is considered to be a good implementation of its use?
2. Using a class factory and/or tools like MOQ, RhinoMocks, etc how could the above example be implemented? | Using an IoC container, the entire function becomes redundant, instead of calling GetFooInstance you'd have code similar to:
```
ObjectFactory.GetInstance<IFoo>();
```
The setup of your IoC container could be in code or through a configuration file. | Nope. We use it all the time to sprinkle diagnostic information in our assemblies. For example I have the following shortcut used when debugging:
```
#if DEBUG
if( ??? ) System.Diagnostics.Debugger.Break();
#endif
```
Where I can change ??? to any relevant expresion like Name == "Popcorn". etc. This ensures that none of the debugging code leaks into the release build. | Is '#IF DEBUG' deprecated in modern programming? | [
"",
"c#",
""
] |
What's a high performance hashing library that's also cross platform for C/C++. For algorithms such as MD5, SHA1, CRC32 and Adler32.
I initially had the impression that Boost had these, but apparently not (yet).
The most promising one I have found so far is Crypto++, any other suggestions? <http://www.cryptopp.com/> This seems to be quite comprehensive. | For usual crypto hashes (MD?, SHA? etc.), [openssl](https://www.openssl.org/) is the most portable and probably fastest. None of the hashes you mentioned are good for high performance data structures like hash tables. The recommended hash functions for these data structures these days are: FNV, Jenkins and MurmurHash. | QT [seem to implement](http://doc.trolltech.com/4.3/qcryptographichash.html) MD4, MD5 and SHA1 | Fast Cross-Platform C/C++ Hashing Library | [
"",
"c++",
"c",
"cross-platform",
"hash",
""
] |
I have a small python script which i use everyday......it basically reads a file and for each line i basically apply different string functions like strip(), replace() etc....im constanstly editing the file and commenting to change the functions. Depending on the file I'm dealing with, I use different functions. For example I got a file where for each line, i need to use line.replace(' ','') and line.strip()...
What's the best way to make all of these as part of my script? So I can just say assign numbers to each functions and just say apply function 1 and 4 for each line. | First of all, many string functions – including strip and replace – are [deprecated](http://docs.python.org/library/string.html#deprecated-string-functions "Deprecated string functions"). The following answer uses string methods instead. (Instead of `string.strip(" Hello ")`, I use the equivalent of `" Hello ".strip()`.)
Here's some code that will simplify the job for you. The following code assumes that whatever methods you call on your string, that method will return another string.
```
class O(object):
c = str.capitalize
r = str.replace
s = str.strip
def process_line(line, *ops):
i = iter(ops)
while True:
try:
op = i.next()
args = i.next()
except StopIteration:
break
line = op(line, *args)
return line
```
The `O` class exists so that your highly abbreviated method names don't pollute your namespace. When you want to add more string methods, you add them to `O` in the same format as those given.
The `process_line` function is where all the interesting things happen. First, here is a description of the argument format:
* The first argument is the string to be processed.
* The remaining arguments must be given in pairs.
+ The first argument of the pair is a string method. Use the shortened method names here.
+ The second argument of the pair is a list representing the arguments to that particular string method.
The `process_line` function returns the string that emerges after all these operations have performed.
Here is some example code showing how you would use the above code in your own scripts. I've separated the arguments of `process_line` across multiple lines to show the grouping of the arguments. Of course, if you're just hacking away and using this code in day-to-day scripts, you can compress all the arguments onto one line; this actually makes it a little easier to read.
```
f = open("parrot_sketch.txt")
for line in f:
p = process_line(
line,
O.r, ["He's resting...", "This is an ex-parrot!"],
O.c, [],
O.s, []
)
print p
```
Of course, if you very specifically wanted to use numerals, you could name your functions `O.f1`, `O.f2`, `O.f3`… but I'm assuming that wasn't the spirit of your question. | It is possible to map string operations to numbers:
```
>>> import string
>>> ops = {1:string.split, 2:string.replace}
>>> my = "a,b,c"
>>> ops[1](",", my)
[',']
>>> ops[1](my, ",")
['a', 'b', 'c']
>>> ops[2](my, ",", "-")
'a-b-c'
>>>
```
But maybe string descriptions of the operations will be more readable.
```
>>> ops2={"split":string.split, "replace":string.replace}
>>> ops2["split"](my, ",")
['a', 'b', 'c']
>>>
```
Note:
Instead of using the `string` module, you can use the `str` type for the same effect.
```
>>> ops={1:str.split, 2:str.replace}
``` | Defining dynamic functions to a string | [
"",
"python",
""
] |
A requirement of the product that we are building is that its URL endpoints are semantically meaningful to users in their native language. This means that we need UTF-8 encoded URLs to support every alphabet under the sun.
We would also not like to have to provide installation configuration documentation for every application server and version that we support, so it would be nice if we could accomplish this in-code. This might not be possible, since by the time that the Servlet has received the request, its been encoded by the App server, etc.
I've gotten this working (for my first use case using ISO-Latin non-US ASCII characters) by reconstituting the request's path info with:
```
String pathInfoEncoded = new String(httpServletRequest.getPathInfo().getBytes(), "UTF-8");
```
and then parsing that.
However, this doesn't work after redirecting from a POST to a GET using sendRedirect(). The request's path comes in already escaped (so ö is encoded as %F6) and my method above doesn't work.
So I guess my question is am I going about this all wrong? And if so, whats the antidote to my ignorance? :)
Update : found the solution. The problem is that the Servlet API has some weird behaviour with regards to URL encoding before sending the redirect. You have to URL-encode (escape the UTF-8 characters) BEFORE you call sendRedirect(). The encodeRedirectURL() method doesn't do it for you.
This page discusses it: <http://www.whirlycott.com/phil/2005/05/11/building-j2ee-web-applications-with-utf-8-support/> | found the solution. The problem is that the Servlet API has some weird behaviour with regards to URL encoding before sending the redirect. You have to URL-encode (escape the UTF-8 characters) BEFORE you call sendRedirect(). The encodeRedirectURL() method doesn't do it for you.
This page discusses it: <http://www.whirlycott.com/phil/2005/05/11/building-j2ee-web-applications-with-utf-8-support/> | A couple things to investigate and experiment with:
* Have a look at your ./conf/server.xml file and ensure that the connector has the URIEncoding attribute set to "UTF-8".
E.g.:
```
<Connector port="8080"
protocol="HTTP/1.1"
URIEncoding="UTF-8"/>
```
* Use some sort of browser-based tool (E.g.: [TamperData](https://addons.mozilla.org/en-US/firefox/addon/966) for FireFox) to see what your browser is sending to the server--it very well may be escaping it for you. If this is the case, you can use [URL.decode()](http://java.sun.com/j2se/1.5.0/docs/api/java/net/URLDecoder.html) it on the server.
* Instead of using Response.redirect(), manually set the headers and response code.
E.g.:
```
response.setHeader("Location", myUtf8unencodedUrl);
response.setStatus(response.SC_MOVED_TEMPORARILY);
```
No promises, but this is what I would try out if it were me. :) | Configuring Tomcat 5.5 to UTF-8 encode all sendRedirect() redirections? | [
"",
"java",
"web-applications",
"servlets",
"utf-8",
"url-encoding",
""
] |
I was wondering if there was a way to determine the height/width of a browser.
What i'm trying to do is set a height on a div to 500px when the browser size is 1024x768, and for anything lower i'd like to set it to 400px. | If you are using jQuery 1.2 or newer, you can simply use these:
```
$(window).width();
$(document).width();
$(window).height();
$(document).height();
```
From there it is a simple matter to decide the height of your element. | ```
$(function(){
$(window).resize(function(){
var h = $(window).height();
var w = $(window).width();
$("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
});
});
```
Scrollbars etc have an effect on the window size so you may want to tweak to desired size. | Change Height based on Browser Size/Resize | [
"",
"javascript",
"jquery",
"browser",
"screen",
""
] |
So say I'm using BeautifulSoup to parse pages and my code figures out that there are at least 7 pages to a query.
The pagination looks like
```
1 2 3 4 5 6 7 Next
```
If I paginate all the way to 7, sometimes there are more than 7 pages, so that if I am on page 7, the pagination looks like
```
1 2 3 7 8 9 10 Next
```
So now, I know there are at least 3 more pages. I am using an initial pass to figure out how many pages i.e. get\_num\_pages returns 7
What I am doing is iterating over items on each page so I have something like
```
for page in range(1,num_pages + 1):
# do some stuff here
```
Is there a way to dynamically update the range if the script figures out there are more than 7 pages? I guess another approach is to keep a count and as I get to page 7, handle that separately. I'm looking for suggestions and solutions for the best way to approach this. | You could probably çreate a generator that has mutable state that determines when it terminates... but what about something simple like this?
```
page = 1
while page < num_pages + 1:
# do stuff that possibly updates num_pages here
page += 1
``` | Here's a code free answer, but I think it's simple if you take advantage of what beautiful soup lets you do:
To start with, on the first page you have somewhere the page numbers & links; from your question they look like this:
```
1 2 3 4 5 6 7 [next]
```
Different sites handle paging differently, some give a link to jump to beginning/end, but on yours you say it looks like this after the first 7 pages:
```
1 2 3 ... 7 8 9 10 [next]
```
Now, at some point, you will get to the end, it's going to look like this:
```
1 2 3 ... 20 21 22 23
```
Notice there's no [next] link.
So forget about generators and ranges and keeping track of intermediate ranges, etc. Just do this:
1. use beautiful soup to identify the page # links on a given page, along with the next button.
2. Every time you see a [next] link, follow it and reparse with beautiful soup
3. When you hit a page where there is no next link, the last # page link is the total number of pages. | Dynamically change range in Python? | [
"",
"python",
"beautifulsoup",
""
] |
I've got a project with a rather messy VCL codebase built on Borland C++ Builder 6. I intend to rewrite most parts of it since it's hardly maintainable in it's current state. I'm looking for a good and free alternative to VCL. It is a Windows-only closed source commercial project.
So main requirements are:
1. Free for commercial closed-source projects
2. Manage Windows GUI. Other components (db links and stuff) not required
3. Be extendible (so one could write my own GUI components based on existing ones)
4. Be STL-friendly.
Please post your suggestions, with pros and cons if possible.
## EDIT
Thanks for all the answers. I've decided to go with Qt as it has some other nice features like Qt Linguist translation suite. | Try [Qt](https://www.qt.io/). Its LGPL so it can be used in closed source software. It provides widgets, networking functions, database access, web rendering via WebKit, animations and many more. Its documentation is one of the best of its kind. | Check out [wxWidgets](http://www.wxwidgets.org). Its design is a little old-fashioned, but when you start with it and use the most recent version it should be quite STL friendly. It is free for commercial use, and even when you don't intend to use its cross-platform capabilities it may be a good library for you to write a Windows GUI. | A good (and free) VCL GUI alternative | [
"",
"c++",
"windows",
"user-interface",
"c++builder",
"vcl",
""
] |
Ok, I'll try and keep this short, sweet and to-the-point.
We do massive GeoIP updates to our system by uploading a MASSIVE CSV file to our PHP-based CMS. This thing usually has more than 100k records of IP address information. Now, doing a simple import of this data isn't an issue at all, but we have to run checks against our current regional IP address mappings.
This means that we must validate the data, compare and split overlapping IP address, etc.. And these checks must be made for each and every record.
Not only that, but I've just created a field mapping solution that would allow other vendors to implement their GeoIP updates in different formats. This is done by applying rules to IPs records within the CSV update.
For instance a rule might look like:
if 'countryName' == 'Australia' then send to the 'Australian IP Pool'
There might be multiple rules that have to be run and each IP record must apply them all. For instance, 100k records to check against 10 rules would be 1 million iterations; not fun.
We're finding 2 rules for 100k records takes up to 10 minutes to process. I'm fully aware of the bottleneck here which is the shear amount of iterations that must occur for a successful import; just not fully aware of any other options we may have to speed things up a bit.
Someone recommended splitting the file into chunks, server-side. I don't think this is a viable solution as it adds yet another layer of complexity to an already complex system. The file would have to be opened, parsed and split. Then the script would have to iterate over the chunks as well.
So, question is, considering what I just wrote, what would the BEST method be to speed this process up a bit? Upgrading the server's hardware JUST for this tool isn't an option unfortunately, but they're pretty high-end boxes to begin with.
Not as short as I thought, but yeah. Halps? :( | Perform a BULK IMPORT into a database (SQL Server's what I use). The BULK IMPORT takes seconds literally, and 100,000 records is peanuts for a database to crunch on business rules. I regularly perform similar data crunches on a table with over 4 million rows and it doesn't take the 10 minutes you listed.
EDIT: I should point out, yeah, I don't recommend PHP for this. You're dealing with raw DATA, use a DATABASE.. :P | The simple key to this is keeping as much work out of the inner loop as possible.
Simply put, anything you do in the inner loop is done "100K times", so doing nothing is best (but certainly not practical), so doing as little possible is the next best bet.
If you have the memory, for example, and it's practical for the application, defer any "output" until after the main processing. Cache any input data if practical as well. This works best for summary data or occasional data.
Ideally, save for the reading of the CSV file, do as little I/O as possible during the main processing.
Does PHP offer any access to the Unix mmap facility, that is typically the fastest way to read files, particularly large files.
Another consideration is to batch your inserts. For example, it's straightforward to build up your INSERT statements as simple strings, and ship them to the server in blocks of 10, 50, or 100 rows. Most databases have some hard limit on the size of the SQL statement (like 64K, or something), so you'll need to keep that in mind. This will dramatically reduce your round trips to the DB.
If you're creating primary keys through simple increments, do that en masses (blocks of 1000, 10000, whatever). This is another thing you can remove from your inner loop.
And, for sure, you should be processing all of the rules at once for each row, and not run the records through for each rule. | Best practices for iterating over MASSIVE CSV files in PHP | [
"",
"php",
"csv",
""
] |
I am trying to create a simple mouseover effect using a combination of mouseover, mouseout, addClass, and removeClass. Basically, when the user mouses over an element, I want to apply a different border (1px dashed gray). The initial state is "1px solid white". I have a class called "highlight" which simply has "border: 1px dashed gray" in it. I want to add that class onmouseover and remove it on onmouseout but I am unable to get the effect I want unless I use !important within the "highlight" class. | It sounds as though you've got the javascript working fine as is, but it's just a problem with the [specificity of your CSS rules](http://htmldog.com/guides/cssadvanced/specificity/), which is why `!important` makes it work.
You just have to make your highlighted css rules more specific than the non-highlighted rules.
```
#someItem ul li { /* Specificity = 102 */
border-color: white;
}
.highlight { /* Specificity = 10 -- not specific enough! */
border-color: grey;
}
#someItem ul li.highlight { /* Specificity = 112 -- this will work */
border-color: grey;
}
```
---
**Edit with further explanation:**
Let's say the relevant parts of your HTML look like this:
```
<div id="someItem">
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
</div>
```
and you have this CSS:
```
#someItem ul li {
border: 1px solid white;
}
.highlight {
border-color: grey;
}
```
Currently, all the list items in the `ul` in `#someItem div` will have a white border, and nothing has the class `highlight` so nothing's grey.
Through whatever means you want (in your case a hover event in jQuery), you add a class to one of the items:
```
$(this).addClass('highlight');
```
The HTML will now look something like this:
```
<div id="someItem">
<ul>
<li>Item 1</li>
<li class="highlight">Item 2</li>
<li>Item 3</li>
</ul>
</div>
```
So far, your Javascript and HTML are working fine, but you don't see a grey border! The problem is your CSS. When the browser is trying to decide how to style the element, it looks at all the different selectors which target an element and the styles defined in those selectors. If there are two different selectors both defining the same style (in our case, the border colour is contested), then it has to decide which style to apply and which to ignore. It does this by means of what is known as "Specificity" - that is, how specific a selector is. As outlined in the [HTML Dog article](http://htmldog.com/guides/cssadvanced/specificity/), it does this by assigning a value to each part of your selector, and the one with the highest score wins. The points are:
* element selector (eg: "ul", "li", "table") = 1 point
* class selector (eg: ".highlight", ".active", ".menu") = 10 points
* id selector (eg: "#someItem", "#mainContent") = 100 points
There are some more rules, eg: the keyword `!important` and also inline styles, but that's mostly irrelevant for this, uhh... "lesson". The only other thing you should know is that if two selectors have the same specificity, then the one defined later in the file wins.
Going back to your problem, given the CSS we had before, we can see why it's still not got a grey border:
```
#someItem ul li = id + element + element = 100 + 1 + 1 = 102 points
.highlight = class = 10 points
```
As mentioned earlier, the solution is to create a more specific selector:
```
#someItem ul li.highlight
= id + element + element + class
= 100 + 1 + 1 + 10
= 112 points
```
And to answer your question in the comments, you don't need to change any of your javascript or HTML for this to work. If you break down that selector, what it's saying is:
> Look for the element with id "someItem", inside that look for a ul element, and then an li element which has the class "highlight" on it.
...and now, given the simple `.addClass()` call that you made earlier, the `li` satisfies these conditions, so the border should turn grey. | From Jquery 1.3.3 you'll be able to do this a little simpler. There will be an [enhanced version of .toggleClass()](http://brandonaaron.net/blog/2009/05/6/jquery-edge-enhanced-toggleclass) available which will be very powerful.
If you don't need to break this out into a function then from 1.3.3 you'll be able to simply do:
```
$(".myclass").hover(function(){ $(this).toggleClass('highlight'); });
```
If you're having to include !important then your highlight class may need to be more specific (see [CSS Specificity](http://htmldog.com/guides/cssadvanced/specificity/)). | mouseover() mouseout() jQuery add/removeClass problem | [
"",
"javascript",
"jquery",
"css",
"rollover",
""
] |
I have a simple windows application in C# with 3 forms.
first form is main form (its name is FrmMain), second is FrmData and third is FrmShow.
In main form (FrmMain) I have created an instance from second form (FrmData) and show it :
```
public partial class FrmMain : Form
{
public Form FrmModifyData; //for FrmData
int PersonCode;
public FrmMain()
{
InitializeComponent();
}
private void btnShowDataForm_Click(object sender, EventArgs e)
{
FrmModifyData= new FrmData();
FrmModifyData.ShowDialog();
}
}
```
but I can't access from FrmModifyData to FrmMain fields like *PersonCode* .
How can I access to creator object's field?
Note: I'm a beginner.
thanks. | You would need to add a property to your FrmModifyData class to take an instance of the FrmMain class. Then you can do this:
```
FrmModifyData = new FrmData();
FrmModifyData.ParentData = this;
FrmModifyData.ShowDialog();
```
Then inside FrmModifyData you would have access to the public members of FrmMain. Obviously this is kind of quick and dirty and not very reusable so i would suggest adding more explicit properties to FrmModifyData with only the data you need to use. | If you want to access PersonCode field, you should declare it as public. No visibility modifier will make it private, hence not accesible from other casses. | Access to creator object | [
"",
"c#",
"forms",
"object",
""
] |
maybe i am wrong but i seriously i don't like the current structure of MVC application, and i think on big projects it will cause trouble to maintain.
so is there a way to group related Controllers,Views, Models together, like if i have gallery Module i want all it's Controllers, Views, Models to be grouped under Gallery Folder. | [Areas](http://blog.codeville.net/2008/11/05/app-areas-in-aspnet-mvc-take-2/) sound like what you are looking for. This will let you group controllers/views/etc. Unless I misunderstood the question? | Phil Haack [discussed this here](http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx), it's the same issue I've faced and have yet to overcome correctly. | Grouping Views, Controllers, Models in MVC | [
"",
"c#",
"asp.net-mvc",
""
] |
What is the best way to run a windows service as a console?
My current idea is to pass in an "/exe" argument and do the work of the windows service, then calling Application.Run().
The reason I'm doing this is to better debug a windows service and allow easier profiling of the code. The service is basically hosting .NET remoted objects. | This is how I do it. Give me the same .exe for console app and service. To start as a console app it needs a command line parameter of -c.
```
private static ManualResetEvent m_daemonUp = new ManualResetEvent(false);
[STAThread]
static void Main(string[] args)
{
bool isConsole = false;
if (args != null && args.Length == 1 && args[0].StartsWith("-c")) {
isConsole = true;
Console.WriteLine("Daemon starting");
MyDaemon daemon = new MyDaemon();
Thread daemonThread = new Thread(new ThreadStart(daemon.Start));
daemonThread.Start();
m_daemonUp.WaitOne();
}
else {
System.ServiceProcess.ServiceBase[] ServicesToRun;
ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Service() };
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
}
``` | The Code Project site had a great [article](http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx) showing how to run a Windows Service in the Visual Studio debugger, no console app needed. | Running a windows service in a console | [
"",
"c#",
".net",
""
] |
I know you can use a .net reflector to view code created with .net but if I put something in the comments for my own personal reminder is that compiled in the exe as well.
I don't intend to release the source code for my application and i know the 100% safe bet is to just remove everything I don't want out but I was just wondering if someone could reverse engineer my comments. | Comments are ignored by the compiler. They will not be put into the output executable. | No, comments are not in the compiled executable. | comments compiled into .exe in .net? | [
"",
"c#",
".net",
"compiler-construction",
"comments",
""
] |
I need to delete the latest browser history entry for [this reason](https://stackoverflow.com/questions/821359/reload-an-iframe-without-adding-to-the-history), but any other functions exposed by JS that manipulate (add/remove) history entries for the current page/tab, are also welcome. | Can you use location.replace on the IFrame? | I highly doubt that there is a way. The `window.history` object provides read-only access to the browsing history for security reasons. | Manipulate the session history with JavaScript | [
"",
"javascript",
"url",
"browser",
"browser-history",
""
] |
In IE, you can onreadystatechange. There's onload, but I read [scary things](https://stackoverflow.com/questions/198892/img-onload-doesnt-work-well-in-ie7). jQuery wraps up the DOM's load event quite nicely with "ready". It seems likely I am just ignorant of another nice library's implementation of image loading.
The context is that I am generating images dynamically (via server callbacks) that can take some time download. In my IE-only code I set the src of the img element, then when the onreadystatechange event fires with the "complete" status, I add it to the DOM so the user sees it.
I'd be happy with a "native" JavaScript solution, or a pointer to a library that does the work. There's so many libraries out there and I'm sure this is a case of me just not knowing about the right one. That said, we're already jQuery users, so I'm not eager to add a very large library just to get this functionality. | **NOTE:** I wrote this in 2010, the browsers in the wild were IE 8/9 beta, Firefox 3.x, and Chrome 4.x. Please use this for research purposes only, I doubt you could copy/paste this into a modern browser and have it work without issue.
**WARNING:** It is 2017 now I still get points on this now and then, please only use this for research purposes. I currently have no idea how to detect image loading status, but there are probably much more graceful ways of doing it than this... at least I seriously hope there are. I highly recommend NOT using my code in a production environment without more research.
**WARNING Part Two Electric Boogaloo:** It is 2019 now, most jQuery functionality is built into vanilla JS now. If you're still using it, it may be time to stop and consider heading over to [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript) and reading up on some of the new and fun stuff vanilla JS has to offer.
---
I'm a bit late to this party, maybe this answer will help someone else...
If you're using jQuery don't bother with the stock event handlers (onclick/onmouseover/etc), actually just stop using them altogether. Use the event methods they provided in their [API](http://api.jquery.com/category/events/).
---
This will alert, before the image is appended to the body, because load event is triggered when the image is loaded into memory. It is doing exactly what you tell it to: create an image with the src of test.jpg, when test.jpg loads do an alert, then append it to the body.
```
var img = $('<img src="test.jpg" />');
img.load(function() {
alert('Image Loaded');
});
$('body').append(img);
```
---
This will alert, after the image is inserted into the body, again, doing what you told it to: create an image, set an event (no src set, so it hasn't loaded), append the image to the body (still no src), now set the src... now the image is loaded so the event is triggered.
```
var img = $('<img />');
img.load(function() {
alert('Image Loaded');
});
$('body').append(img);
$img.attr('src','test.jpg');
```
---
You can of course also add an error handler and merge a bunch of events using bind().
```
var img = $('<img />');
img.bind({
load: function() {
alert('Image loaded.');
},
error: function() {
alert('Error thrown, image didn\'t load, probably a 404.');
}
});
$('body').append(img);
img.attr('src','test.jpg');
```
---
Per the request by @ChrisKempen ...
Here is a non-event driven way of determining if the images are broken after the DOM is loaded. This code is a derivative of code from an article by [StereoChrome](http://stereochro.me/ideas/detecting-broken-images-js) which uses naturalWidth, naturalHeight, and complete attributes to determine if the image exists.
```
$('img').each(function() {
if (this.naturalWidth === 0 || this.naturalHeight === 0 || this.complete === false) {
alert('broken image');
}
});
``` | [**According to the W3C spec**](http://www.w3.org/TR/REC-html40/interact/scripts.html), *only* the BODY and FRAMESET elements provide an "onload" event to attach to. Some browsers support it regardless, but just be aware that it is not required to implement the W3C spec.
Something that might be pertinent to this discussion, though not necessarily the answer you are in need of, is this discussion:
> [**Image.onload event does not fire on Internet Explorer when image is in cache**](http://code.google.com/p/google-web-toolkit/issues/detail?id=863)
---
Something else that *may be related* to your needs, though it may not, is this info on supporting a synthesized "onload" event for *any dynamically-loaded* DOM element:
[**How can I determine if a dynamically-created DOM element has been added to the DOM?**](https://stackoverflow.com/questions/220188/how-can-i-determine-if-a-dynamically-created-dom-element-has-been-added-to-the-do) | Browser-independent way to detect when image has been loaded | [
"",
"javascript",
"dom",
""
] |
As part of an installer, I need to run a batch file from ANT. If I run cmd.exe as Administrator and run the batch file, all is well since it has the appropriate administrative privileges. When the batch file is executed from ant, it fails, the same way it does if I were to run the batch file without administrative privileges. My question is, how can I run this batch file in Administrative mode from my ANT script?
```
<exec executable="cmd.exe" output="dir.txt" dir="c:/bin/">
<arg line="/c service.bat install"/>
</exec>
``` | Turning off UAC seems to be the only option to allow this ant task to execute.
I tried making a shortcut to the batch file, and running that, since shortcuts can be set to 'run as administrator'. No luck there either as I get the prompt, but my batch file still fails out.
[<http://www.mydigitallife.info/2007/02/17/how-to-open-elevated-command-prompt-with-administrator-privileges-in-windows-vista/][1]> | At least XP has a `runas` command which you can try to use, something like:
```
runas /u:%COMPUTERNAME%\Administrator "cmd /c service.bat install"
```
When invoked, it will ask for password on console.
UPDATE: half of year later, I have upgraded to Windows 7. Here runas cannot be used for privilege elevation, but [Aaron Margosis](http://blogs.msdn.com/aaron_margosis/archive/2007/07/01/scripting-elevation-on-vista.aspx) has a solution:
```
// elevate.js -- runs target command line elevated
if (WScript.Arguments.Length >= 1) {
Application = WScript.Arguments(0);
Arguments = "";
for (Index = 1; Index < WScript.Arguments.Length; Index += 1) {
if (Index > 1) {
Arguments += " ";
}
Arguments += WScript.Arguments(Index);
}
new ActiveXObject("Shell.Application").ShellExecute(Application, Arguments, "", "runas");
} else {
WScript.Echo("Usage:");
WScript.Echo("elevate Application Arguments");
}
```
Which perhaps could be embedded in the installer if needed. For end users though, the [Script Elevation Power Toys](http://technet.microsoft.com/lt-lt/magazine/2007.06.utilityspotlight%28en-us%29.aspx) is more convienent, as suggested by another answer. | Is there a way to make an ANT task run as Administrator in Windows Vista? | [
"",
"java",
"ant",
"windows-vista",
""
] |
I have a table which has two varchar(Max) columns
```
Column 1 Column 2
-----------------------
URLRewitten OriginalURL
```
its part of my url re-writing for an asp.net webforms site.
when a url comes in I do a check to see if its in the table if it is i use the OriginalURL.
My question is, if all I'm doing is querying the table for urls and no other table in the database will ever link to this table does it need a dedicated primary key field? like an auto-number? will this make queries faster?
and also how can I make the query's run as faster?
Edit: I do have a unique constraint on URLRewitten.
Edit: ways i'm using this table..
* Query when a new Request comes in.. search on URLRewitten to find OriginalURL
* When needing to display a link on the site, i query on the OriginalURL to find the URLRewitten url i should use.
* When adding a new url to the table i make sure that it doesn't already exist.
thats all the querys i do.. at the moment.
Both columns together would be unique. | Do you need a primary key? Yes. Always. However, it looks like in your case OriginalURL could be your primary key (I'm assuming that there wouldn't be more than one value for URLRewritten for a given value in OriginalURL).
This is what's known as a "natural key" (where a component of the data itself is, by its nature, unique). These can be convenient, though I have found that they're generally more trouble than they're worth under most circumstances, so yes, I would recommend some sort of opaque key (meaning a key that has no relation to the data in the row, other than to identify a single row). Whether or not you want an autonumber is up to you. It's certainly convenient, though identity columns come with their own set of advantages and disadvantages.
For now I suppose I would advise creating two things:
1. A primary key on your table of an identity column
2. A unique constraint on OriginalURL to enforce data integrity. | I'd put one in there anyway... it'll make updating alot easier or duplicating an existing rule...
i.e. this is easier
```
UPDATE Rules SET OriginalURL = 'http://www.domain.com' WHERE ID = 1
--OR
INSERT INTO Rules SELECT OriginalUrl, NewUrl FROM Rules WHERE ID = 1
```
Than this
this is easier
```
UPDATE Rules SET OriginalURL = "http://www.domain.com" WHERE OriginalURL = 'http://old.domain.com'
--OR
INSERT INTO Rules SELECT OriginalUrl, NewUrl FROM Rules WHERE OriginalURL = 'http://old.domain.com'
```
In terms of performance, if your going to be searching by OriginalURL,
you should add an index to that column, | Should I use an auto-generated Primary Key if I'm just doing a lookup table? | [
"",
"asp.net",
"sql",
"performance",
""
] |
Bizarrely the stack collection seems to be missing the rather basic shift and unshift methods\* and I'm working in 2.0 so I can't just extend them.
Is there any reasonable technique or alternative collection class to get these methods available? I need push and pop as well.
Edit: looks like the collection I want is indeed a [deque](http://en.wikipedia.org/wiki/Double-ended_queue) which is happily not native to C# :(
Can't use third party libraries at this time so I'll be going with the clunky LinkedList (I say clunky because reading and removing are two operations where shift would be one) but I think I'd recommend the PowerCollections approach to anyone who could use it. Or better yet, upgrading to extension methods.
*sigh*
---
\* Apologies, I didn't realise these were uncommon terms, I thought I just didn't know where to find them in the API. For reference:
shift = remove first element
unshift = insert element at beginning of collection | I would say use a [`LinkedList<T>`](http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx). It has methods for adding and removing from the front, as well as adding and removing from the back. I've never heard of shifting and unshifting, but I'm assuming that's what it means. | Never heard of shift/unshift in a stack. The Stack class does provide `Pop`, `Peek`, and `Push` though. | stack collection missing shift and unshift in C# 2.0 | [
"",
"c#",
"collections",
".net-2.0",
""
] |
Can someone explain why I get different results from these two statements? I thought that reassigning the value to the same variable would result in the value I get in the above example. What am I missing here?
```
_body.Replace("##" + _variableName + "##",
templateVariables[_variableName])
```
**Hello pitty ##LastName##,**
```
_body = _body.Replace("##" + _variableName.ToUpper() + "##",
templateVariables[_variableName])
```
**Hello ##FirstName## ##LastName##,** | If I understand this correctly:
Your first statement is not assigning the return value, since replace returns a new instance of the string replaced.
```
_body = _body.Replace("##" + _variableName + "##",
templateVariables[_variableName]);
```
should fix you there.
The second instance you have the variable getting replace changed ToUpper() and the actual string containing mixed cased values.
Your string should be
```
Hello ##FIRSTNAME## ##LASTNAME##,
``` | Strings are immutable, so the Replace function doesn't modify the string it is called on. You need to assign it again like you did in your second example.
And as other people have pointed out, the ToUpper call will ensure that variable names don't match. | string.Replace not behaving as expected | [
"",
"c#",
".net",
"string",
""
] |
I have been working with Java a couple of years, but up until recently I haven't run across this construct:
```
int count = isHere ? getHereCount(index) : getAwayCount(index);
```
This is probably a very simple question, but can someone explain it? How do I read it? I am pretty sure I know how it works.
* if `isHere` is true, `getHereCount()` is called,
* if `isHere` is false `getAwayCount()` is called.
Correct? What is this construct called? | Yes, it is a shorthand form of
```
int count;
if (isHere)
count = getHereCount(index);
else
count = getAwayCount(index);
```
It's called the **conditional operator**. Many people (erroneously) call it *the ternary operator*, because it's the only ternary (three-argument) operator in Java, C, C++, and probably many other languages. But theoretically there *could* be another ternary operator, whereas there can only be one *conditional operator*.
The official name is given in the [Java Language Specification](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25):
> ### §15.25 Conditional Operator ? :
>
> The conditional operator `? :` uses the boolean value of one expression to decide which of two other expressions should be evaluated.
Note that both branches must lead to methods with return values:
> **It is a compile-time error for either the second or the third operand expression to be an invocation of a void method.**
>
> *In fact, by the grammar of expression statements ([§14.8](http://docs.oracle.com/javase/specs/jls/se8/html/jls-14.html#jls-14.8)), it is not permitted for a conditional expression to appear in any context where an invocation of a void method could appear.*
So, if `doSomething()` and `doSomethingElse()` are void methods, you cannot compress this:
```
if (someBool)
doSomething();
else
doSomethingElse();
```
into this:
```
someBool ? doSomething() : doSomethingElse();
```
Simple words:
```
booleanCondition ? executeThisPartIfBooleanConditionIsTrue : executeThisPartIfBooleanConditionIsFalse
``` | Others have answered this to reasonable extent, but often with the name "ternary operator".
Being the pedant that I am, I'd like to make it clear that the name of the operator is the conditional operator or "conditional operator ?:". It's *a* ternary operator (in that it has three operands) and it happens to be the only ternary operator in Java at the moment.
However, the [spec is pretty clear](http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.25) that its name is the conditional operator or "conditional operator ?:" to be absolutely unambiguous. I think it's clearer to call it by that name, as it indicates the behaviour of the operator to some extent (evaluating a condition) rather than just how many operands it has. | What is the Java ?: operator called and what does it do? | [
"",
"java",
"syntax",
"ternary-operator",
"conditional-operator",
""
] |
I have the following rails form (which works) but I want to remove the submit\_tag and have the form submit as soon as a radio button selection is made. How do I do that?
```
<% form_tag({ :controller => "votes", :action => "create", :id => @item.id } ) do %>
<p>
<% for i in 1..10 do %>
<%= radio_button_tag :rating, i %> <%=h i %>
<% end %>
</p>
<p>
<%= submit_tag "Create" %>
</p>
<% end %>
``` | So I have found the precise solution (thanks for the input guys, it helped me redefine my Google searches). Everyone was on the right track, but none were spot on.
All that was needed was to add 'false, :onclick => "this.parentNode.submit();"' to the radio\_button\_tag form helper. The false is selected or not, and the rest is obvious.
The correct solution now looks like:
```
<% form_tag({ :controller => "votes", :action => "create", :id => @item.id } ) do %>
<% for i in 1..10 do %>
<%= radio_button_tag :rating, i, false, :onclick => "this.parentNode.submit();" %> <%=h i %>
<% end %>
<% end %>
``` | You'll want to add an onClick event to your radio button that calls this.formName.submit() where formName is your form ID. This will trigger the submit event when you click the radio button. | Submitting Rails Form on a Radio Button Selection | [
"",
"javascript",
"ruby-on-rails",
"ruby",
""
] |
I have inherited an application that pulls messages out of an MSMQ does some processing to them and then adds some data to database depending on what is in the message. The messages are getting pushed into the Queue by a third party application I do not control.
I do not know much about MSMQ, although I do have a basic understanding of how to use the APIs.
Anyway, I have noticed that the messages never get deleted, our client definately never explictly deletes them, and I can look in computer management and see the messages back to when the server was last rebooted.
**Is this wrong?** Will the messages start to automatically get deleted when the queue reaches some maximum size or will they just pile up there forever slowly taking up more memory? | I'd suspect that while this isn't best practice, the queue is cleared on reboot, and as long as there's a sufficient amount of resources available, you'll never actually run into a problem.
That said, I'd opt for setting something up to periodically clean up the queue so you don't overwhelm the server. I'm not too familiar with MSMQ, but is there some way that you can tell if a message has been processed? Even if it's an additional service that runs, checks the messages in the queue and sees if they already appear in the database, and deletes them if they do? That way, you wouldn't need to modify the codebase you inherited, since it's working properly as-is.
Once you decide on a solution, please post an update here - I'm interested to know how you end up dealing with this problem. Thanks! | Once a message has been processed, it is normal practice to remove it from a queue (transactionally or otherwise). | Is it ok to never delete from a MSMQ? | [
"",
"c#",
"msmq",
""
] |
Recently, I came across Mono and MonoDevelop packages in Ubuntu linux. They claim to have a .NET runtime in accordance with CLI. Before installing the packages myself, I would like to know the following:
1. How powerful is Mono?
2. Can I develop GUI application for
linux like developing WinForm
applications for Windows.
3. Is MonoDevelop IDE compatible with Visual Studio IDE. Can I import VS 2008 solutions to MonoDevelop and work?
4. Does it support .NET 2.0 and above?
EDIT: Adding one more doubt
Is there any way to run the .NET exe (of a winform app) in Linux without building the cod e in linux? In fact I don't have the code for some of the small utilities I developed earlier and would like to run them in linux. | 1. (Strange, markdown starts the enumeration with one, even though I began with 2...)
2. Yes, you can, but you're limited with 3rd-party components, because the internal implementation is different, and last time I checked (not very long ago), the Mono WinForms implementation made my test app look rather strange (owner-drawn list view). It is not really recommended, though Mono claims that it's now completely WinForms-2.0-compatible.
3. MonoDevelop is/was a SharpDevelop branch, with the latter having solution support. I don't know if MonoDevelop has. But the cool thing is, you can just develop with Visual Studio and run your compiled apps on Mono. And Mono is, by the way, also available for Windows.
4. Yes, it does, as far as the CLR goes. As Marc Gravell already wrote, the Windows Foundation libraries are missing, as are a few other (System.Management, for example). But things should mostly work, including ASP.NET 2.0. [Mono's application portability guidelines](http://mono-project.com/Guidelines:Application_Portability) are a good read on this. | 1: pretty good, actually. Not all the full framework is there, so if you are writing code that should build on both MS .NET and mono, you need to build and test early against both platforms
4: yes - although things like WPF/WCF/WF (3.0) are missing or slimmed down
I don't know much about the *development* environment, since I use VSTS (on Windows) and just use a NANT script to do the build on mono... | Feasibility of C# development with Mono | [
"",
"c#",
"linux",
"ubuntu-9.04",
""
] |
I have a collection of objects and am curious about the way you would separate them into two lists - one list will have everything of a specific type, the other will have the remainder. One way I thought of doing it is:
```
var typeXs = (from o in collectionOfThings where o.Type == "typeX" select o);
var notTypeXs = (from o in collectionOfThings where o.Type != "typeX" select o);
```
The other way would be to just loop over collectionOfThings and assign based on if/else.
Both ways are simple and readable, but I'm just wondering if there is an even slicker way? | This example should demonstrate what you're after:
```
class MyObject
{
public int n;
public string t;
}
```
Load up my original list:
```
List<MyObject> allObjects = new List<MyObject>() {
new MyObject() { n = 0, t = "x" },
new MyObject() { n = 1, t = "y" },
new MyObject() { n = 2, t = "x" },
new MyObject() { n = 3, t = "y" },
new MyObject() { n = 4, t = "x" }
};
```
Split out the types using:
```
var typeXs = allObjects.FindAll(i => i.t == "x");
var notTypeXs = allObjects.FindAll(i => i.t != "x");
```
*Or*
```
var typeXs = allObjects.Where(i => i.t == "x").ToList<MyObject>();
var notTypeXs = allObjects.Except(typeXs).ToList<MyObject>();
```
*Alternatively* you could use the List.ForEach method which only iterates once and therefore theoretically *should* outperform the other two options. Also, it doesn't require referencing the LINQ libraries which means it's .NET 2.0 safe.
```
var typeXs = new List<MyObject>();
var notTypeXs = new List<MyObject>();
allObjects.ForEach(i => (i.t == "x" ? typeXs : notTypeXs).Add(i));
``` | You could rewrite the second part as
```
var notTypeXs = collectionOfThings.Except(typeXs);
``` | Slickest way to put objects into separate lists based on a property value | [
"",
"c#",
".net",
"linq",
""
] |
Suppose I'm given an object and a string that holds a method name, how can I return a delegate to that method (of that method?) ?
Example:
```
MyDelegate GetByName(ISomeObject obj, string methodName)
{
...
return new MyDelegate(...);
}
ISomeObject someObject = ...;
MyDelegate myDelegate = GetByName(someObject, "ToString");
//myDelegate would be someObject.ToString
```
Thanks in advance.
One more thing -- I really don't want to use a switch statement even though it would work but be a ton of code. | You'll need to use [`Type.GetMethod`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) to get the right method, and [`Delegate.CreateDelegate`](http://msdn.microsoft.com/en-us/library/system.delegate.createdelegate.aspx) to convert the `MethodInfo` into a delegate. Full example:
```
using System;
using System.Reflection;
delegate string MyDelegate();
public class Dummy
{
public override string ToString()
{
return "Hi there";
}
}
public class Test
{
static MyDelegate GetByName(object target, string methodName)
{
MethodInfo method = target.GetType()
.GetMethod(methodName,
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy);
// Insert appropriate check for method == null here
return (MyDelegate) Delegate.CreateDelegate
(typeof(MyDelegate), target, method);
}
static void Main()
{
Dummy dummy = new Dummy();
MyDelegate del = GetByName(dummy, "ToString");
Console.WriteLine(del());
}
}
```
Mehrdad's comment is a great one though - if the exceptions thrown by this overload of [Delegate.CreateDelegate](http://msdn.microsoft.com/en-us/library/12f294ye.aspx) are okay, you can simplify `GetByName` significantly:
```
static MyDelegate GetByName(object target, string methodName)
{
return (MyDelegate) Delegate.CreateDelegate
(typeof(MyDelegate), target, methodName);
}
```
I've never used this myself, because I normally do other bits of checking after finding the `MethodInfo` explicitly - but where it's suitable, this is really handy :) | ```
static MyDelegate GetByName(object obj, string methodName)
{
return () => obj.GetType().InvokeMember(methodName,
System.Reflection.BindingFlags.InvokeMethod, null, obj, null);
}
``` | C#: Return a delegate given an object and a method name | [
"",
"c#",
"reflection",
""
] |
I can say I don't know what I'm asking for help,because I don't know the format,but I've got a picture.
I have a byte[] array ,how do I convert it to that format below(in right)?
[alt text http://img512.imageshack.us/img512/3548/48667724.jpg](http://img512.imageshack.us/img512/3548/48667724.jpg)
Its not plain ascii. | Use `b.ToString("x2")` to format a byte value into a two character hexadecimal string.
For the ASCII display, check if the value corresponds to a regular printable character and convert it if it is:
```
if (b >= 32 && b <= 127) {
c = (char)b;
} else {
c = '.';
}
```
Or shorter:
```
c = b >= 32 && b <= 127 ? (char)b : '.';
```
To do it on an array:
```
StringBuilder builder = new StringBuilder();
foreach (b in theArray) {
builder.Append(b >= 32 && b <= 127 ? (char)b : '.');
}
string result = builder.ToString();
``` | It sounds like you'd like to take an array of bytes, and convert it to text (replacing characters outside of a certain range with "`.`"s)
```
static public string ConvertFromBytes(byte[] input)
{
StringBuilder output = new StringBuilder(input.Length);
foreach (byte b in input)
{
// Printable chars are from 0x20 (space) to 0x7E (~)
if (b >= 0x20 && b <= 0x7E)
{
output.Append((char)b);
}
else
{
// This isn't a text char, so use a placehold char instead
output.Append(".");
}
}
return output.ToString();
}
```
or as a LINQy extension method (inside a static extension class):
```
static public string ToPrintableString(this byte[] bytes)
{
return Encoding.ASCII.GetString
(
bytes.Select(x => x < 0x20 || x > 0x7E ? (byte)'.' : x)
.ToArray()
);
}
```
(You could call that like `string printable = byteArray.ToPrintableString();`) | How to convert byte[] to that text format? | [
"",
"c#",
"text",
"formatting",
""
] |
## Question
I have two compilers on my hardware C++ and C89
I'm thinking about using C++ with classes but without polymorphism (to avoid vtables).
The main reasons I’d like to use C++ are:
* I prefer to use “inline” functions instead of macro definitions.
* I’d like to use namespaces as I prefixes clutter the code.
* I see C++ a bit type safer mainly because of templates, and verbose casting.
* I really like overloaded functions and constructors (used for automatic casting).
Do you see any reason to stick with C89 when developing for very limited hardware (4kb of RAM)?
## Conclusion
Thank you for your answers, they were really helpful!
I thought the subject through and I will stick with C mainly because:
1. It is easier to predict actual code in C and this is really important if you have only 4kb of ram.
2. My team consists mainly of C developers, so advanced C++ features won't be frequently used.
3. I've found a way to inline functions in my C compiler (C89).
It is hard to accept one answer as you provided so many good answers.
Unfortunately I can't create a wiki and accept it, so I will choose one answer that made me think most. | Two reasons for using C over C++:
1. For a lot of embedded processors, either there is no C++ compiler, or you have to pay extra for it.
2. My experience is that a signficant proportion of embedded software engineers have little or no experience of C++ -- either because of (1), or because it tends not to be taught on electronic engineeering degrees -- and so it would be better to stick with what they know.
Also, the original question, and a number of comments, mention the 4 Kb of *RAM*. For a typical embedded processor, the amount of RAM is (mostly) unrelated to the code size, as the code is stored, and run from, flash.
Certainly, the amount of code storage space is something to bear in mind, but as new, more capacious, processors appear on the market, it's less of an issue than it used to be for all but the most cost-sensitive projects.
On the use of a subset of C++ for use with embedded systems: there is now a [MISRA C++](http://www.misra-cpp.com/) standard, which may be worth a look.
**EDIT:** See also [this question](https://stackoverflow.com/questions/1223710), which led to a debate about C vs C++ for embedded systems. | For a *very* resource constrained target such as 4KB of RAM, I'd test the waters with some samples before committing a lot of effort that can't be easily ported back into a pure ANSI C implementation.
The Embedded C++ working group did propose a standard subset of the language and a standard subset of the standard library to go with it. I lost track of that effort when the C User's Journal died, unfortunately. It looks like there is an article at [Wikipedia](http://en.wikipedia.org/wiki/Embedded_C%2B%2B), and that the [committee](http://www.caravan.net/ec2plus/) still exists.
In an embedded environment, you really have to be careful about memory allocation. To enforce that care, you may need to define the global `operator new()` and its friends to something that can't be even linked so that you know it isn't used. Placement `new` on the other hand is likely to be your friend, when used judiciously along with a stable, thread-safe, and latency guaranteed allocation scheme.
Inlined functions won't cause much problem, unless they are big enough that they should have been true functions in the first place. Of course the macros their replacing had that same issue.
Templates, too, may not cause a problem unless their instantiation runs amok. For any template you do use, audit your generated code (the link map may have sufficient clues) to make certain that only the instantiations you intended to use happened.
One other issue that may arise is compatibility with your debugger. It isn't unusual for an otherwise usable hardware debugger to have very limited support for interaction with the original source code. If you effectively must debug in assembly, then the interesting name mangling of C++ can add extra confusion to the task.
RTTI, dynamic casts, multiple inheritance, heavy polymorphism, and exceptions all come with some amount of runtime cost for their use. A few of those features level that cost over the whole program if they are used, others just increase the weight of classes that need them. Know the difference, and choose advanced features wisely with full knowledge of at least a cursory cost/benefit analysis.
In an small embedded environment you will either be linking directly to a real time kernel or running directly on the hardware. Either way, you will need to make certain that your runtime startup code handles C++ specific startup chores correctly. This might be as simple as making sure to use the right linker options, but since it is common to have direct control over the source to the power on reset entry point, you might need to audit that to make certain that it does everything. For example, on a ColdFire platform I worked on, the dev tools shipped with a CRT0.S module that had the C++ initializers present but comment out. If I had used it straight from the box, I would have been mystified by global objects whose constructors had never run at all.
Also, in an embedded environment, it is often necessary to initialize hardware devices before they can be used, and if there is no OS and no boot loader, then it is your code that does that. You will need to remember that constructors for global objects are run *before* `main()` is called so you will need to modify your local CRT0.S (or its equivalent) to get that hardware initialization done *before* the global constructors themselves are called. Obviously, the top of `main()` is way too late. | Is there any reason to use C instead of C++ for embedded development? | [
"",
"c++",
"c",
"embedded",
"c89",
""
] |
I haven't done web development for about 6 years. I'm trying to get back into it and there is a lot of new stuff out there. I've chosen to write my next project with Perl and Catalyst.
I keep hearing about various JavaScript and CSS frameworks. I know very little about these frameworks so maybe this question is overly broad and open ended.
What are the strengths, weaknesses, and popularity of the various frameworks? Should I be using YUI, JQuery, neither, or something else? | Firstly, it's probably worth perusing [Which Javascript framework (jQuery vs Dojo vs … )?](https://stackoverflow.com/questions/394601/which-javascript-framework-jquery-vs-dojo-vs).
Secondly, there are two broad categories of Javascript framework:
1. **Rich:** made for creating so-called Rich Intenet Applications, they are typically aimed at creating experiences much like a desktop applications with sophisticated windowing GUIs. This includes, but aren't limited to, YUI, Dojo, ExtJS and SmartClient;
2. **Complementary:** these are more focused on improving a traditional Website experience rather than replacing it altogether. These include jQuery, Prototype and others. Some might point out that jQuery has jQuery UI but this is a barebones widget library at best and completely incomparable to, say, YUI in terms of out-of-the-box user interface capabilities.
So the first thing you should ask yourself is: what kind of application are you creating?
Personally I think you can't go wrong with YUI or jQuery, depending on your answer. | **Why not use both?** I have on a couple projects.
jQuery's size is small. You can use the minified version from google's open ajax libraries, and since many people already do this, there may be no download at all b/c it may very well already be in your user's cache.
As for YUI, they have a great configurator for getting exactly what you need. Also their documentation is very thorough and their widgets top notch in compatibility.
Having worked with both, jQuery's strength is it's speed and flexibility to do a lot of tasks. YUI's strength is it's top-notch, ready to use widgets. Both projects have written very solid code that will not interfere with each other. Both projects have worked hard to be compatible across all A grade browsers and careful not to trash the name space - which is better than I can say for some other frameworks. | JavaScript frameworks and CSS frameworks: JQuery, YUI, neither, or something else? | [
"",
"javascript",
"jquery",
"yui",
"javascript-framework",
"css-frameworks",
""
] |
I've played around with the netbeans visual editor for java and it seems very intuitive and simple to use but I can't help but think: is this detrimental to my learning? Should I be getting my hands dirty and doing everything manually? How do professionals in the field handle user interface design?
What would you guys recommend I do? | The main drawback of GUI builders is that they make it easy to do simple things and very difficult to do complicated things. It's the same as building a website with a real design tool vs. using a simple website builder like iWeb or FrontPage.
The three most important topics in GUI framework are learning the event model, the layout model, and the intricacies of each widget. GUI builders isolate you from the latter two and kind of restrict your exposure to your first.
In the long run, it's detrimental to the things you can achieve, and therefore detrimental to your mastering of GUI creation.
In addition, maybe behaviors that are very important to the users (e.g., blanking out one widget in response to change in another) are quite tricky to write, especially with automatically generated code. Complex GUIs often rely on models, and GUI builders often through everything together, so it's much easier to end up with horrible unmaintainable code. | For learning *design* I think a visual GUI editor is fine. Design has nothing to do with what tools you use to create the design. If your goal is to learn how to create a pleasing user experience a visual editor might be very helpful.
For learning how to create an application with a graphical user interface I think it may be detrimental, though that really depends on the individual. At some point I do think you need to "get your hands dirty" so you can learn exactly how widgets interact with business objects and with the user. | Is using a visual GUI editor detrimental to learning GUI design? | [
"",
"java",
"user-interface",
""
] |
I have read my first book on c# and feel completely clueless about LINQ. Please suggest reader-friendly linq material.
Thanks | [LINQ in Action](http://linqinaction.net/) has been recommnded to me by several people. | Download [LINQPad](http://www.linqpad.net/) and play with it. It comes with many free samples. | Where is the best place to start learning LINQ? | [
"",
"c#",
"linq",
""
] |
I have a service method that takes a String and then replaces tags in the String with items from a tag library. As follows:
```
for( MetaDataDTO tag : tagValues )
{
message = message.replace( tag.getKey(), tag.getText1() );
}
```
Obviously; this make heaps of new strings and is BAD. But the StringBuilder replace method is cumbersome to use for multiple strings inside one string. How can I make my method more efficient?
It is for use with blocks of text such as:
Dear #firstName#, your application for #applicationType# has been #approvedRejected# sorry.
Where #firstName#, etc are the keys in a meta data database. It is also possible that tags may not be surrounded by hash characters. | Thanks for your help guys. Certainly learned more about java. Here is my solution. It is this way to support different looking tags and tags within tags:
```
private static String replaceAllTags(String message, Map< String, String > tags)
{
StringBuilder sb = new StringBuilder( message );
boolean tagFound = false;
/**
* prevent endless circular text replacement loops
*/
long recurrancyChecker = 5000;
do
{
tagFound = false;
Iterator it = tags.entrySet().iterator();
while( it.hasNext() )
{
Map.Entry pairs = (Map.Entry) it.next();
int start = sb.indexOf( pairs.getKey().toString() );
while( start > -1 && --recurrancyChecker > 0 )
{
int length = pairs.getKey().toString().length();
sb.replace( start, start + length, pairs.getValue().toString() );
start = sb.indexOf( pairs.getKey().toString() );
tagFound = true;
}
}
}
while( tagFound && --recurrancyChecker > 0 );
return sb.toString();
}
``` | Basically you want to copy the execution of [Matcher.replaceAll()](http://java.sun.com/j2se/1.5.0/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)) like so:
```
public static String replaceTags(String message, Map<String, String> tags) {
Pattern p = Pattern.compile("#(\\w+)#");
Matcher m = p.matcher(message);
boolean result = m.find();
if (result) {
StringBuffer sb = new StringBuffer();
do {
m.appendReplacement(sb, tags.containsKey(m.group(1) ? tags.get(m.group(1)) : "");
result = m.find();
} while (result);
m.appendTail(sb);
message = sb.toString();
}
return message;
}
```
**Note:** I've made an assumption about the valid tag (namely \w in the regex). You will need to cater this for what's really valid (eg "#([\w\_]+)#").
I've also assumed the tags above looks something like:
```
Map<String, String> tags = new HashMap<String, String>();
tags.add("firstName", "Skippy");
```
and not:
```
tags.add("#firstName#", "Skippy");
```
If the second is correct you'll need to adjust accordingly.
This method makes exactly one pass across the message string so it doesn't get much more efficient than this. | best way of replacing all tags in a string with java | [
"",
"java",
"string",
"replace",
"stringbuilder",
""
] |
I've heard a lot of good comments about Boost in the past and thought I would give it a try. So I downloaded all the required packages from the package manager in Ubuntu 9.04. Now I'm having trouble finding out how to actually use the darn libraries.
Does anyone know of a good tutorial on Boost that goes all the way from Hello World to Advanced Topics, and also covers how to compile programs using g++ on ubuntu? | Agreed; [the boost website](http://www.boost.org/doc/libs/1_39_0) has good tutorials for the most part, broken down by sub-library.
As for compiling, a good 80% of the library implementation is defined in the header files, making compiling trivial. for example, if you wanted to use shared\_ptr's, you'd just add
```
#include <boost/shared_ptr.hpp>
```
and compile as you normally would. No need to add library paths to your g++ command, or specify -llibboost. As long as the boost directory is in your include path, you're all set.
From the boost documentation:
> The only libraries that need to be compiled and linked are the following:The only Boost libraries that must be built separately are:
>
> * Boost.Filesystem
> * Boost.IOStreams
> * Boost.ProgramOptions
> * Boost.Python (see the Boost.Python build documentation before building and installing it)
> * Boost.Regex
> * Boost.Serialization
> * Boost.Signals
> * Boost.Thread
> * Boost.Wave
>
> A few libraries have optional separately-compiled binaries:
>
> * Boost.DateTime has a binary component that is only needed if you're using its to\_string/from\_string or serialization features, or if you're targeting Visual C++ 6.x or Borland.
> * Boost.Graph also has a binary component that is only needed if you intend to parse GraphViz files.
> * Boost.Test can be used in “header-only” or “separately compiled” mode, although separate compilation is recommended for serious use.
So, if you're using one of the listed libraries, use the [Getting Started guide](http://www.boost.org/doc/libs/1_39_0/more/getting_started/index.html) to, well, get you started on compiling and linking to Boost. | The Boost website has some good tutorials, they are just kind of [hidden.](http://www.boost.org/doc/libs/1_38_0/doc/html/libraries.html) | Using Boost on ubuntu | [
"",
"c++",
"boost",
"ubuntu-9.04",
""
] |
Is there a C++ function to turn off the computer? And since I doubt there is one (in the standard library, at least), what's the windows function that I can call from C++?
Basically, what is the code to turn off a windows xp computer in c++? | On windows you can use the ExitWindows function described here:
<http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx>
and here's a link to example code that does this:
<http://msdn.microsoft.com/en-us/library/aa376871(VS.85).aspx> | Use the following, assuming you have the privileges):
```
ExitWindowsEx (EWX_POWEROFF | EWX_FORCEIFHUNG,
SHTDN_REASON_MINOR_OTHER);
```
This will cause power off while giving applications a chance to shut down (if they take too long, they'll be terminated anyway).
It's part of the Win32 API rather than standard C++ but that's because C++ provides no way to do this directly. | Is there a C++ function to turn off the computer? | [
"",
"c++",
"windows",
"application-shutdown",
""
] |
I have a table where the results are sorted using an "ORDER" column, eg:
```
Doc_Id Doc_Value Doc_Order
1 aaa 1
12 xxx 5
2 bbb 12
3 ccc 24
```
My issue is to initially set up this order column as efficiently and reusably as possible.
My initial take was to set up a scalar function that could be used as a default value when a new entry is added to the table:
```
ALTER FUNCTION [dbo].[Documents_Initial_Order]
( )
RETURNS int
AS
BEGIN
RETURN (SELECT ISNULL(MAX(DOC_ORDER),0) + 1 FROM dbo.Documents)
```
When a user wants to permute 2 documents, I can then easily switch the 2 orders.
It works nicely, but I now have a second table I need to set up the same way, and I am quite sure there is a nicer way to do it. Any idea? | It sounds like you want an identity column that you can then override once it gets it initial value. One solution would be to have two columns, once call "InitialOrder", that is an auto-increment identity column, and then a second column called doc\_order that initially is set to the same value as the InitialOrder field (perhaps even as part of the insert trigger or a stored procedure if you are doing inserts that way), but give the user the ability to edit that column.
It does require an extra few bytes per record, but solves your problem, and if its of any value at all, you would have both the inital document order and the user-reset order available.
Also, I am not sure if your doc\_order needs to be unique or not, but if not, you can then sort return values by doc\_order and InitialOrder to ensure a consistent return sequence. | Based on your comment, I think you have a very workable solution. You could make it a little more userfriendly by specifying it as a default:
```
alter table documents
add constraint constraint_name
default (dbo.documents_initial_order()) for doc_order
```
As an alternative, you could create an update trigger that copies the identity field to the doc\_order field after an insert:
```
create trigger Doc_Trigger
on Documents
for insert
as
update d
set d.doc_order = d.doc_id
from Documents d
inner join inserted i on i.doc_id = d.doc_id
```
Example defining doc\_id as an identity column:
```
create table Documents (
doc_id int identity primary key,
doc_order int,
doc_value ntext
)
``` | Custom sort in SQL Server | [
"",
"sql",
"sql-server",
"user-defined-functions",
""
] |
I don't want user to see all the exporting functions through Dependence in my DLL, is there a way to do it? I complie my DLL with C++ and MS Visual Studio. | Use a \*.def file and use the NONAME attribute to prevent the name's being exported: see [Exporting Functions from a DLL by Ordinal Rather Than by Name](http://msdn.microsoft.com/en-us/library/e7tsx612(VS.80).aspx) ... there's an [an example here](http://code.google.com/p/mozilla-symbian/source/browse/trunk/nsprpub/config/plc4_winscw.def?spec=svn4&r=4). | Another option may be to create an exported function which will return an array of addresses of the functions which you would like to hide - once you have these addresses, you can call them directly
```
static void** Funcs = {&foo, &foo1, &foo2, 0};
__declspec (dllexport) void* GetFuncs (void)
{
return &Funcs;
}
```
in your executable you can do the following
```
void** Funcs = GetFuncs();
(*Funcs[0]) (1, 2, 3);
``` | How to hide the exporting functions in DLL | [
"",
"c++",
"visual-studio",
"winapi",
"dll",
""
] |
I was wondering what is the best way to convert excel sheet column names into numbers.
I'm working with [Excel Package](http://www.codeplex.com/ExcelPackage/), a good library to handle .xlsx documents. This library unfortunately doesn't have this functionality included.
> OBS: The first column, A, corresponds
> to number 1 in this library. | This function should work for an arbitrary length column name.
```
public static int GetColumnNumber(string name)
{
int number = 0;
int pow = 1;
for (int i = name.Length - 1; i >= 0; i--)
{
number += (name[i] - 'A' + 1) * pow;
pow *= 26;
}
return number;
}
``` | I had to deal with this a few months ago. The inverse - column index to column name - is fun, too, and becomes really messy if you try to solve it with a zero based index not recognizing that this complicates things. It could be so simple if it would be a normal polyadic numeral system ...
Here is a simplified version of my solution as a extension method without error handling and all that stuff.
```
public static Int32 ToOneBasedIndex(this String name)
{
return name.ToUpper().
Aggregate(0, (column, letter) => 26 * column + letter - 'A' + 1);
}
``` | How to convert Excel sheet column names into numbers? | [
"",
"c#",
"excel",
""
] |
The code in question is here:
```
var $item = $(this).parent().parent().find('input');
```
What is the purpose of the dollar sign in the variable name, why not just exclude it? | A '$' in a variable means nothing special to the interpreter, much like an underscore.
From what I've seen, many people using [jQuery](http://jquery.com) (which is what your example code looks like to me) tend to prefix variables that contain a jQuery object with a $ so that they are easily identified and not mixed up with, say, integers.
The dollar sign function `$()` in jQuery is a library function that is frequently used, so a short name is desirable. | In your example the $ has no special significance other than being a character of the name.
***However*, in ECMAScript 6 (ES6) the $ may represent a [Template Literal](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals)**
```
var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.
``` | What is the purpose of the dollar sign in JavaScript? | [
"",
"javascript",
"naming-conventions",
""
] |
Basically I have some variables that I don't want to preinitialize:
```
originalTime = None
recentTime = None
postTime = None
def DoSomething ( ) :
if originalTime == None or (postTime - recentTime).seconds > 5 :
...
```
I get compile error on the if:
```
UnboundLocalError: local variable 'originalTime' referenced before assignment
```
As you can see, all the variables have different relationship that either has to be set right (time, time + 5, etc) or None at all, but I don't wanna set them to precalculated values when just declaring them to None is easier.
Any ideas? | I need to correct Jarret Hardie, and since I don't have enough rep to comment.
The global scope is not an issue. Python will automatically look up variable names in enclosing scopes. The only issue is when you want to change the value. If you simply redefine the variable, Python will create a new local variable, unless you use the global keyword. So
```
originalTime = None
def doSomething():
if originalTime:
print "originalTime is not None and does not evaluate to False"
else:
print "originalTime is None or evaluates to False"
def doSomethingElse():
originalTime = True
def doSomethingCompletelyDifferent()
global originalTime
originalTime = True
doSomething()
doSomethingElse()
doSomething()
doSomethingCompletelyDifferent()
doSomething()
```
Should output:
```
originalTime is None or evaluates to False
originalTime is None or evaluates to False
originalTime is not None and does not evaluate to False
```
I second his warning that this is bad design. | Your code should have worked, I'm guessing that it's inside a function but originalTime is defined somewhere else.
Also it's a bit better to say `originalTime is None` if that's what you really want or even better, `not originalTime`. | How to initialize variables to None/Undefined and compare to other variables in Python? | [
"",
"python",
""
] |
I have a file host website thats burning through 2gbit of bandwidth, so I need to start adding secondary media servers to store the files. What would be the best way to manage a multiple server setup, with a large amount of files? Preferably through php only.
Currently, I only have around 100Gb of files... so I could get a 2nd server, mirror all content between them, and then round robin the traffic 50/50, 33/33/33, etc. But once the total amount of files grows beyond the capacity of a single server, this wont work.
The idea that I had was to have a list of media servers stored in the DB with the amounts of free space left on each server. Once a file is uploaded, php will choose to which server the file is actually uploaded to, and spread out all the files evenly among the servers.
Was hoping to get some more input/inspiration.
Cant use any 3rd party services like Amazon. The files range from several bytes to a gigabyte.
Thanks | If you are doing as much data transfer as you say, it would seem whatever it is you are doing is growing quite rapidly.
It might be worth your while to contact your hosting provider and see if they offer any sort of shared storage solutions via iscsi, nas, or other means. Ideally the storage would not only start out large enough to store everything you have on it, but it would also be able to dynamically grow beyond your needs. I know my hosting provider offers a solution like this.
If they do not, you might consider colocating your servers somewhere that either does offer a service like that, or would allow you install your own storage server (which could be built cheaply from off the shelf components and software like Freenas or Openfiler).
Once you have a centralized storage platform, you could then add web-servers to your hearts content and load balance them based on load, all while accessing the same central storage repository.
Not only is this the correct way to do it, it would offer you much more redundancy and expandability in the future if you endeavor continues to grow at the pace it is currently growing.
The other solutions offered using a database repository of what is stored where, would work, but it not only adds an extra layer of complexity into the fold, but an extra layer of processing between your visitors and the data they wish to access.
What if you lost a hard disk, do you lose 1/3 or 1/2 of all your data?
Should the heavy IO's of static content be on the same spindles as the rest of your operating system and application data? | You could try [MogileFS](http://www.danga.com/mogilefs/). It is a distributed file system. Has a good API for PHP. You can create categories and upload a file to that category. For each category you can define on how many servers it should be distributed. You can use the API to get a URL to that file on a random node. | What's the best way to manage multiple media servers, and file allocations between them? | [
"",
"php",
"mysql",
""
] |
I am new to java NIO. I have to write a simple server client communication program using Java NIO.
Is there any sample programs or any link where can I go for this? | You might give a look at [Apache Mina](http://mina.apache.org/). If you only want to learn java NIO it might me a little to hard to grasp. | **Apache Mina**
<http://mina.apache.org>
Apache MINA is a network application framework which helps users develop high
performance and high scalability network applications easily.
**xSocket**
<http://xsocket.org/>
xSocket is an easy to use NIO-based library to build high performance, highly
scalable network applications.
**JBoss Netty**
**Sun MicroSystem's Grizzly**
<https://grizzly.java.net/>
The Grizzly framework has been designed to help developers to take advantage of the Java NIO API.
Grizzly goals is to help developers to build scalable and robust servers using NIO.
**NIO Framework**
**QuickServer**
<http://www.quickserver.org>
QuickServer is an open source Java library/framework for quick creation of
robust multi-client TCP server applications. QuickServer provides an abstraction over
the ServerSocket, Socket and other network and input output classes and it eases the
creation of powerful network servers. | how to write a complete server client communication using java nio | [
"",
"java",
"sockets",
"nio",
""
] |
**Disclaimer: I realize I can generate this at runtime in Java, this was needed for a very special case while performance testing some code. I've found a different approach, so now this is just more of a curiosity than anything practical.**
I've tried the following as a static field, as an instance field, and initialized directly within the constructor. Every time eclipse is informing me that either "The code of constructor TestData() is exceeding the 65535 bytes limit" or "The code for the static initializer is exceeding the 65535 bytes limit".
There are 10,000 integers. If each int is 4 bytes (32bits), then would that not be 40,000 bytes? Is there really more that 25,0000 bytes of overhead in addition to the data just merely constructing the array?
The data is generated with this small bit of python:
```
#!/usr/bin/python
import random;
print "public final int[] RANDOM_INTEGERS = new int[] {";
for i in range(1,10000):
print str(int(random.uniform(0,0x7fffffff))) + ",";
print "};";
```
Here's a small sample:
```
public final int[] RANDOM_INTEGERS = new int[] {
963056418, 460816633, 1426956928, 1836901854, 334443802, 721185237, 488810483,
1734703787, 1858674527, 112552804, 1467830977, 1533524842, 1140643114, 1452361499,
716999590, 652029167, 1448309605, 1111915190, 1032718128, 1194366355, 112834025,
419247979, 944166634, 205228045, 1920916263, 1102820742, 1504720637, 757008315,
67604636, 1686232265, 597601176, 1090143513, 205960256, 1611222388, 1997832237,
1429883982, 1693885243, 1987916675, 159802771, 1092244159, 1224816153, 1675311441,
1873372604, 1787757434, 1347615328, 1868311855, 1401477617, 508641277, 1352501377,
1442984254, 1468392589, 1059757519, 1898445041, 1368044543, 513517087, 99625132,
1291863875, 654253390, 169170318, 2117466849, 1711924068, 564675178, 208741732,
1095240821, 1993892374, 87422510, 1651783681, 1536657700, 1039420228, 674134447,
1083424612, 2137469237, 1294104182, 964677542, 1506442822, 1521039575, 64073383,
929517073, 206993014, 466196357, 1139633501, 1692533218, 1934476545, 2066226407,
550646675, 624977767, 1494512072, 1230119126, 1956454185, 1321128794, 2099617717,
//.... to 10,0000 instances
``` | Here is the bytecode for initializing an array with {1000001, 1000002, 1000003}:
```
5 iconst_3
6 newarray int [10]
8 dup
9 iconst_0
10 ldc <Integer 1000001> [12]
12 iastore
13 dup
14 iconst_1
15 ldc <Integer 1000002> [13]
17 iastore
18 dup
19 iconst_2
20 ldc <Integer 1000003> [14]
22 iastore
23 putfield net.jstuber.test.TestArrayInitializingConstructor.data : int[] [15]
```
So for this small array each element requires 5 bytes of Java bytecode. For your bigger array both the array index and the index into the constant pool will use 3 bytes for most elements, which leads to 8 bytes per array element. So for 10000 elements you'd have to expect about 80kB of byte code.
The code for initializing big arrays with 16 bit indices looks like this:
```
2016 dup
2017 sipush 298
2020 ldc_w <Integer 100298> [310]
2023 iastore
2024 dup
2025 sipush 299
2028 ldc_w <Integer 100299> [311]
``` | Array literals are translated into the byte code that fills the array with the values, so you need a few more bytes for each number.
Why not move that data out into a resource that you load at class-loading time in a static initializer block? This can easily be done by using `MyClass.class.getClassLoader().getResourceAsStream()`. It seems that this it where it belongs, anyway.
Or better yet, create the random values in the static initializer block using the Java tools available. And if you need repeatable "random" numbers, then just seed the `Random` instance with a fixed, but randomly choosen number each time. | Why does this exceed the 65,535 byte limit in Java constructors and static Initializers? | [
"",
"java",
"jls",
""
] |
I am a C++ user and now trying to use c#.
In c++ taking input from the user was fun (just >>) and supported all the types. So was for the files. But in c# it is too complex, as I can take only strings. Then I have to manipulate it for later use.
And if I want to take multiple inputs in same line separated by whitespaces, it become more complex as I have to go for string splitting. Then conversion...
May be it is for error handling and safe code. But I am disappointed with C# anyway.
You are all expert guys here. Is there any easy way? | As far as I'm aware, you have to do it the hard way. (On the bright side though, the hard way is simpler than it'd be in C++ ;))
Console.OpenStandardInput() does give you the input stream, so it can be treated the same as files, but you'll have to do the string splitting yourself if you need that. Of course, C# has a nice Regex library that may help here.
T.TryParse (where T is int, float, whichever type you want to read) should let you convert the string to those types. | Ultimately, it wouldn't take much to wrap it - you'd just need to buffer the current line and read off inputs in your desired format. But IMO, a little split/TryParse etc rarely hurts.
I'm not 100% sure of the expected formats that `>>` accepts, but I doubt it would be hard to do something similar. I'm not volunteering to write it, though ;-p | How to take the input from user in console or file with ease in c#? | [
"",
"c#",
"file",
"input",
"console",
""
] |
I'm a bit confused with JavaScript's `delete` operator. Take the following piece of code:
```
var obj = {
helloText: "Hello World!"
};
var foo = obj;
delete obj;
```
After this piece of code has been executed, `obj` is `null`, but `foo` still refers to an object exactly like `obj`. I'm guessing this object is the same object that `foo` pointed to.
This confuses me, because I expected that writing `delete obj` deleted the object that `obj` was pointing to in memory—not just the variable `obj`.
Is this because JavaScript's Garbage Collector is working on a retain/release basis, so that if I didn't have any other variables pointing to the object, it *would* be removed from memory?
(By the way, my testing was done in Safari 4.) | The delete operator deletes only a reference, never an object itself. If it did delete the object itself, other remaining references would be dangling, like a C++ delete. (And accessing one of them would cause a crash. To make them all turn null would mean having extra work when deleting or extra memory for each object.)
Since Javascript is garbage collected, you don't need to delete objects themselves - they will be removed when there is no way to refer to them anymore.
It can be useful to delete references to an object if you are finished with them, because this gives the garbage collector more information about what is able to be reclaimed. If references remain to a large object, this can cause it to be unreclaimed - even if the rest of your program doesn't actually use that object. | The `delete` command has no effect on regular variables, only properties. After the `delete` command the property doesn't have the value `null`, it doesn't exist at all.
If the property is an object reference, the `delete` command deletes the property but not the object. The garbage collector will take care of the object if it has no other references to it.
Example:
```
var x = new Object();
x.y = 42;
alert(x.y); // shows '42'
delete x; // no effect
alert(x.y); // still shows '42'
delete x.y; // deletes the property
alert(x.y); // shows 'undefined'
```
(Tested in Firefox.) | Deleting Objects in JavaScript | [
"",
"javascript",
"pointers",
"object",
"memory-management",
"garbage-collection",
""
] |
Last couple of days, I have refrained myself from master's studies and have been focusing on this (seemingly simple) puzzle:
---
There is this 10\*10 grid which constitutes a square of 100 available places to go. The aim is to start from a corner and traverse through all the places with respect to some simple "traverse rules" and reach number 100 (or 99 if you're a programmer and start with 0 instead :)
The rules for traversing are:
1. Two spaces hop along the vertical and horizontal axis
2. One space hop along the diagonals
3. You can visit each square only once
To visualise better, here is a valid example traverse (up to the 8th step):
[Example Traverse http://img525.imageshack.us/img525/280/squarepuzzle.png](http://img525.imageshack.us/img525/280/squarepuzzle.png)
---
Manually, I have been working on this puzzle out of boredom. For years, I have tried to solve it by hand from time to time, but I have never gone beyond 96. Sounds easy? Try yourself and see for yourself :)
Thus, in order to solve the problem, I have developed a short (around 100 lines of code) program in Python. I am a beginner in this language I wanted to see what I can do.
The program simply applies exhaustive try & error solving technique. In other words: brute force depth first search.
My question arises from here on: The program, unfortunately cannot solve the problem because the state space is so big that search never ends withouh ever finding a solution. It can go up to number 98 (and prints that) without much difficulty, nonetheless not a complete solution.
The program also prints out the length of the search tree it has covered so far. In a couple of minutes, the traverse list from, say, 65th element is covered till the end, for just one single path. This number decreases in exponentially increasing time periods. I have run the code for quite some time and could not get beyond 50 barrier and now I am convinced.
It seems that this simple approach will not be enough unless I run it for ever. So, how can I improve my code to be faster and more efficient so that it comes up with solutions?
Basically, I am looking forward to see ideas on how to:
1. Capture and exploit **domain knowledge** specific to this problem
2. Apply **programming techniques/tricks** to overcome exhaustion
..and finally realize into a substantial solution.
Thanks in advance.
---
**Revision**
Thanks to Dave Webb for relating the problem to domain it belongs:
> This is very similar to the Knight's
> Tour problem which relates moving a
> knight around a chess board without
> revisiting the same square. Basically
> it's the same problem but with
> different "Traverse Rules".
--- | Eventually, I have come up with the modified Python code to overcome the problem. I've tun the code for a couple of hours and it has already found half a million solutions in a couple of hours.
The full set of solutions still require a total exhaustive search, i.e. to let the program run until it finishes with all combinations. However, reaching "a" legitimate solution can be reduced to "linear time".
First, things I have learned:
1. Thanks to [Dave Webb's answer](https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767984#767984) and [ammoQ's answer](https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/767991#767991). The problem is indeed an extension of Hamiltonian Path problem as it is NP-Hard. There is no "easy" solution to begin with. There is a famous riddle of [Knight's Tour](http://en.wikipedia.org/wiki/Knight%27s_tour) which is simply the same problem with a different size of board/grid and different traverse-rules. There are many things said and done to elaborate the problem and methodologies and algorithms have been devised.
2. Thanks to [Joe's answer](https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/769302#769302). The problem can be approached in a bottom-up sense and can be sliced down to solvable sub-problems. Solved sub-problems can be connected in an entry-exit point notion (one's exit point can be connected to one other's entry point) so that the main problem could be solved as a constitution of smaller scale problems. This approach is sound and practical but not complete, though. It can not guarantee to find an answer if it exists.
Upon exhaustive brute-force search, here are key points I have developed on the code:
* [Warnsdorff's algorithm](http://en.wikipedia.org/wiki/Knight%27s_tour#Warnsdorff.27s_algorithm): This
algorithm is the key point to reach
to a handy number of solutions in a
quick way. It simply states that, you
should pick your next move to the
"least accessible" place and populate
your "to go" list with ascending
order or accesibility. Least
accessible place means the place with
least number of possible following
moves.
Below is the pseudocode (from Wikipedia):
---
Some definitions:
* A position Q is accessible from a position P if P can move to Q by a single knight's move, and Q has not yet been visited.
* The accessibility of a position P is the number of positions accessible from P.
Algorithm:
> set P to be a random initial position
> on the board mark the board at P with
> the move number "1" for each move
> number from 2 to the number of squares
> on the board, let S be the set of
> positions accessible from the input
> position set P to be the position in
> S with minimum accessibility mark the
> board at P with the current move
> number return the marked board -- each
> square will be marked with the move
> number on which it is visited.
---
* [Checking for islands](https://stackoverflow.com/questions/767912/riddle-the-square-puzzle/768497#768497): A nice exploit of domain knowledge here proved to be handy. If a move (unless it is the last one) would cause *any* of its neighbors to become an island, i.e. not accessible by any other, then that branch is no longer investigated. Saves considerable amount of time (very roughly 25%) combined with Warnsdorff's algorithm.
And here is my code in Python which solves the riddle (to an acceptable degree considering that the problem is NP-Hard). The code is easy to understand as I consider myself at beginner level in Python. The comments are straightforward in explaining the implementation. Solutions can be displayed on a simple grid by a basic GUI (guidelines in the code).
```
# Solve square puzzle
import operator
class Node:
# Here is how the squares are defined
def __init__(self, ID, base):
self.posx = ID % base
self.posy = ID / base
self.base = base
def isValidNode(self, posx, posy):
return (0<=posx<self.base and 0<=posy<self.base)
def getNeighbors(self):
neighbors = []
if self.isValidNode(self.posx + 3, self.posy): neighbors.append(self.posx + 3 + self.posy*self.base)
if self.isValidNode(self.posx + 2, self.posy + 2): neighbors.append(self.posx + 2 + (self.posy+2)*self.base)
if self.isValidNode(self.posx, self.posy + 3): neighbors.append(self.posx + (self.posy+3)*self.base)
if self.isValidNode(self.posx - 2, self.posy + 2): neighbors.append(self.posx - 2 + (self.posy+2)*self.base)
if self.isValidNode(self.posx - 3, self.posy): neighbors.append(self.posx - 3 + self.posy*self.base)
if self.isValidNode(self.posx - 2, self.posy - 2): neighbors.append(self.posx - 2 + (self.posy-2)*self.base)
if self.isValidNode(self.posx, self.posy - 3): neighbors.append(self.posx + (self.posy-3)*self.base)
if self.isValidNode(self.posx + 2, self.posy - 2): neighbors.append(self.posx + 2 + (self.posy-2)*self.base)
return neighbors
# the nodes go like this:
# 0 => bottom left
# (base-1) => bottom right
# base*(base-1) => top left
# base**2 -1 => top right
def solve(start_nodeID, base):
all_nodes = []
#Traverse list is the list to keep track of which moves are made (the id numbers of nodes in a list)
traverse_list = [start_nodeID]
for i in range(0, base**2): all_nodes.append(Node(i, base))
togo = dict()
#Togo is a dictionary with (nodeID:[list of neighbors]) tuples
togo[start_nodeID] = all_nodes[start_nodeID].getNeighbors()
solution_count = 0
while(True):
# The search is exhausted
if not traverse_list:
print "Somehow, the search tree is exhausted and you have reached the divine salvation."
print "Number of solutions:" + str(solution_count)
break
# Get the next node to hop
try:
current_node_ID = togo[traverse_list[-1]].pop(0)
except IndexError:
del togo[traverse_list.pop()]
continue
# end condition check
traverse_list.append(current_node_ID)
if(len(traverse_list) == base**2):
#OMG, a solution is found
#print traverse_list
solution_count += 1
#Print solution count at a steady rate
if(solution_count%100 == 0):
print solution_count
# The solution list can be returned (to visualize the solution in a simple GUI)
#return traverse_list
# get valid neighbors
valid_neighbor_IDs = []
candidate_neighbor_IDs = all_nodes[current_node_ID].getNeighbors()
valid_neighbor_IDs = filter(lambda id: not id in traverse_list, candidate_neighbor_IDs)
# if no valid neighbors, take a step back
if not valid_neighbor_IDs:
traverse_list.pop()
continue
# if there exists a neighbor which is accessible only through the current node (island)
# and it is not the last one to go, the situation is not promising; so just eliminate that
stuck_check = True
if len(traverse_list) != base**2-1 and any(not filter(lambda id: not id in traverse_list, all_nodes[n].getNeighbors()) for n in valid_neighbor_IDs): stuck_check = False
# if stuck
if not stuck_check:
traverse_list.pop()
continue
# sort the neighbors according to accessibility (the least accessible first)
neighbors_ncount = []
for neighbor in valid_neighbor_IDs:
candidate_nn = all_nodes[neighbor].getNeighbors()
valid_nn = [id for id in candidate_nn if not id in traverse_list]
neighbors_ncount.append(len(valid_nn))
n_dic = dict(zip(valid_neighbor_IDs, neighbors_ncount))
sorted_ndic = sorted(n_dic.items(), key=operator.itemgetter(1))
sorted_valid_neighbor_IDs = []
for (node, ncount) in sorted_ndic: sorted_valid_neighbor_IDs.append(node)
# if current node does have valid neighbors, add them to the front of togo list
# in a sorted way
togo[current_node_ID] = sorted_valid_neighbor_IDs
# To display a solution simply
def drawGUI(size, solution):
# GUI Code (If you can call it a GUI, though)
import Tkinter
root = Tkinter.Tk()
canvas = Tkinter.Canvas(root, width=size*20, height=size*20)
#canvas.create_rectangle(0, 0, size*20, size*20)
canvas.pack()
for x in range(0, size*20, 20):
canvas.create_line(x, 0, x, size*20)
canvas.create_line(0, x, size*20, x)
cnt = 1
for el in solution:
canvas.create_text((el % size)*20 + 4,(el / size)*20 + 4,text=str(cnt), anchor=Tkinter.NW)
cnt += 1
root.mainloop()
print('Start of run')
# it is the moment
solve(0, 10)
#Optional, to draw a returned solution
#drawGUI(10, solve(0, 10))
raw_input('End of Run...')
```
Thanks to all everybody sharing their knowledge and ideas. | This is very similar to the [Knight's Tour](http://en.wikipedia.org/wiki/Knight's_tour) problem which relates moving a knight around a chess board without revisiting the same square. Basically it's the same problem but with different "Traverse Rules".
The key optimisation I remember from tackling the Knights Tour recursively is take your next moves in increasing order of the number of available moves on the destination square. This encourages the search to try and move densely in one area and filling it rather than zooming all over the board and leaving little island squares that can never be visited. (This is [Warnsdorff's algorithm](http://en.wikipedia.org/wiki/Knight's_tour#Warnsdorff.27s_algorithm).)
Also make sure you have considered symmetry where you can. For example, at the simplest level the x and y of your starting square only need to go up to 5 since (10,10) is the same as (1,1) with the board rotated. | Riddle: The Square Puzzle | [
"",
"python",
"knights-tour",
""
] |
I'm new to usercontrols, having only created one so far, so bear with me. I've been reading today that usercontrols are supposed to be self-contained and not rely on any information from the parent container. I get that part, but what I'm having trouble understanding is the "right" way to design my program around that principle.
I'm making a web form in C# in which there's a page with a usercontrol in that page. I've made the usercontrol in its ascx file and dragged it into my aspx page. The usercontrol is a couple date boxes and a gridview to show the results of an SQL stored procedure.
I'd really like to reuse this control, but I can't figure out how to "tell" the usercontrol what stored procedure I'd like to run for the specific page I'm on without violating the "don't rely on the parent container" rule.
Thanks | Don't rely on the parent container doesn't mean you can't communicate. Expose a property in the user control which the parent will set. But have a default value so it doesn't crash.
Also, if this is a very specific control, there's no reason it would be bad to rely on the parent. It might not be ideal, but you would be using the user control to provide a separation of code. | Your control does not need to know where it's data came from. It does not need to know about the stored procedure or anything else. All it needs to know is the data that it needs to show. If I understand your control right, it's a grid with some date filters. It will receive data, show that data and filter it by date. That's fine, all it needs to know is the data it needs to show and and maybe a default start and end date from the parent. | Having trouble understanding User Controls in C# | [
"",
"c#",
"user-controls",
"design-principles",
""
] |
In Java, I need to return an Iterator from my method. My data comes from another object which usually can give me an iterator so I can just return that, but in some circumstances the underlying data is null. For consistency, I want to return an "empty" iterator in that case so my callers don't have to test for null.
I wanted to write something like:
```
public Iterator<Foo> iterator() {
if (underlyingData != null) {
return underlyingData.iterator(); // works
} else {
return Collections.emptyList().iterator(); // compiler error
}
}
```
But the Java compiler complains about the returning `Iterator<Object>` instead of `Iterator<Foo>`. Casting to `(Iterator<Foo>)` doesn't work either. | You can get an empty list of type Foo through the following syntax:
```
return Collections.<Foo>emptyList().iterator();
``` | Java 7 has been out for a long time now. Unless you're developing for a previous Java version, you would return an empty iterator like this:
```
return Collections.emptyIterator();
``` | Java iterator over an empty collection of a parameterized type | [
"",
"java",
"collections",
"iterator",
""
] |
I have small utility that does some processing on a file and changes the file extension to .processed when it is finished. I also want to delete these old .processed files after "x" number of days. Is there a file attribute that tells you when a filename was last changed? I realize that I can add white space to the end of the file after processing, re-save it, and then get the "LastWriteTime" attribute, but I do not want touch the original file at all. Any ideas? | LastWriteTime in the System.IO.FileInfo namespace.
```
FileInfo fi1 = new FileInfo(path);
```
Oh yeah, you can write this value as well. Update it when you update the filename. | Another idea if updating the LastWriteTime solution doesn't meet your needs:
Store the filename (or renamed filename) and the date the file was processed in a database. | How do you determine when a filename was last changed in C#? | [
"",
"c#",
"filenames",
""
] |
I need to replace all & in a String that isnt part of a HTML entity. So that the String "This & entites `>` & `<`" will return "This `&` entites `> & <`"
And I've come up with this regex-pattern: "**&[a-zA-Z0-9]{2,7};**" which works fine.
But I'm not very skilled in regex, and when I test the speed over 100k iterations, it uses double amount of time over a previous used method, that didnt use regex. (But werent working 100% either).
Testcode:
```
long time = System.currentTimeMillis();
String reg = "&(?!&#?[a-zA-Z0-9]{2,7};)";
String s="a regex test 1 & 2 1&2 and &_gt; - &_lt;"
for (int i = 0; i < 100000; i++) {test=s.replaceAll(reg, "&");}
System.out.println("Finished in:" + (System.currentTimeMillis() - time) + " milliseconds");
```
So the question would be whether there is some obvious ways of optimize this regex expression for it to be more effective? | `s.replaceAll(reg, "&")` is compiling the regular expression every time. Compiling the pattern once will provide some increase in performance (~30% in this case).
```
long time = System.currentTimeMillis();
String reg = "&(?!&#?[a-zA-Z0-9]{2,7};)";
Pattern p = Pattern.compile(reg);
String s="a regex test 1 & 2 1&2 and &_gt; - &_lt;";
for (int i = 0; i < 100000; i++) {
String test = p.matcher(s).replaceAll("&");
}
System.out.println("Finished in:" +
(System.currentTimeMillis() - time) + " milliseconds");
``` | You have to exclude the `&` from your look-ahead assertion. So try this regular expression:
```
&(?!#?[a-zA-Z0-9]{2,7};)
```
Or to be more precise:
```
&(?!(?:#(?:[xX][0-9a-fA-F]|[0-9]+)|[a-zA-Z]+);)
``` | Regex optimisation - escaping ampersands in java | [
"",
"java",
"regex",
"optimization",
""
] |
I would like to ask if the use of mutable is appropriate here:
```
#include <iostream>
class Base
{
protected:
int x;
public:
virtual void NoMod() const
{
std::cout << x << std::endl;
}
void Draw() const
{
this->NoMod();
}
};
class Derive : public Base
{
private:
mutable int y;
public:
void NoMod() const
{
y = 5;
}
};
int main()
{
Derive derive;
// Test virtual with derive
derive.Draw();
return 0;
}
```
The Base class is a 3rd-party library. I'm extending it to provide my own NoMod(). The library original NoMod() is declared as a const.
My NoMod() differs from Base in the fact that it needs to modify its own member variable.
Thus, for my own NoMod() to compile and get called when Draw() is called, I had to
1) Implement Derive::NoMod() as a const
2) make my int y mutable.
Is this the best I can do? | As 'head geek' described, the answer to your question depends on how your data member is used.
I distinguish two types of data members in a class.
I use the common term 'attribute' to refer to data members
that are the logical state or 'value' of the object.
Typically attributes are rarely declared as mutable.
I have coined the protologism 'contribute' it denote
data members that are simply 'working memory/storage'
and that are somewhat divorced from the state of the object.
Contributes have no contextual relevance to the user of the object,
they exist in the class only to contribute to the maintenance
and efficient operation of the object.
Contributes are usually declared in the class as mutable and are always
private or protected.
For example let's say your object is a linked list,
so you have a pointer to the first item in the list.
I would consider this pointer a contribute because
it does not represent the data in the list.
Even if the list is sorted and the
pointer is set to the new first item in the list,
the user of the list object could care less how the
list is maintained. Only that the list data has
been modified or not and that the the list is sorted or not is
relevant to the user's perspective.
Even if you had a booean data member 'sorted' to quickly determine
if the list is in a sorted state, that too would be a contribute
because it is the list structure itself which imbues the sorted state,
the 'sorted' variable member is used simply to efficiently remember the state
without having to scan the list.
As another example, if you have a const method that searches the list.
Suppose you know that typically the search will return the
most recently previously searched for item,
you would keep a pointer in your class to such a item so your method
can first check if the last found item matches the search key before searching
the entire list (if the method does indeed need to search the list and finds
an item, the pointer would be updated).
This pointer I would consider to be a contribute because it
is only there to help speed up the search. Even though the
search updates the pointer contribute, the method is effectively
const because none of the items' data in the container are modified.
So, data members that are attributes are usually not declared mutable,
and data members that contribute to the functioning of an object will usually be mutable. | It's hard to say, since you don't give any context on what `y` refers to or how it's used.
In general, `mutable` is only appropriate when changing the mutable variable doesn't change the actual "value" of the object. For example, when I was writing a wrapper for C-style strings, I needed to make the internal `mLength` variable mutable so that I could cache the length, even if the thing it was requested on was a `const` object. It didn't *change* the length or the string, and wasn't visible outside of the class itself, so making it `mutable` was okay. | C++ mutable appropriate in this case? | [
"",
"c++",
"mutable",
""
] |
There’s a really cool diff class hosted by Google here:
<http://code.google.com/p/google-diff-match-patch/>
I’ve used it before on a few web sites, but now I need to use it *within* an Excel macro to compare text between two cells.
However, it is only available in JavaScript, Python, Java, and C++, not VBA.
My users are limited to Excel 2003, so a pure .NET solution wouldn't work. Translating the code to VBA manually would take too much time and make upgrading difficult.
One option I considered was to compile the JavaScript or Java source using the .NET compilers (JScript.NET or J#), use Reflector to output as VB.NET, then finally downgrade the VB.NET code manually to VBA, giving me a pure VBA solution. After having problems getting it to compile with any .NET compiler, I abandoned this path.
Assuming I could have gotten a working .NET library, I could have also used ExcelDna (<http://www.codeplex.com/exceldna>), an open-source Excel add-in to make .NET code integration easier.
My last idea was to host an Internet Explorer object, send it the JavaScript source, and calling it. Even if I got this to work, my guess is it would be dirt-slow and messy.
**UPDATE: Solution found!**
I used the WSC method described below by the accepted answer. I had to change the WSC code a little to clean up the diffs and give me back a VBA-compatible array of arrays:
```
function DiffFast(text1, text2)
{
var d = dmp.diff_main(text1, text2, true);
dmp.diff_cleanupSemantic(d);
var dictionary = new ActiveXObject("Scripting.Dictionary"); // VBA-compatible array
for ( var i = 0; i < d.length; i++ ) {
dictionary.add(i, JS2VBArray(d[i]));
}
return dictionary.Items();
}
function JS2VBArray(objJSArray)
{
var dictionary = new ActiveXObject("Scripting.Dictionary");
for (var i = 0; i < objJSArray.length; i++) {
dictionary.add( i, objJSArray[ i ] );
}
return dictionary.Items();
}
```
I registered the WSC and it worked just fine. The code in VBA for calling it is as follows:
```
Public Function GetDiffs(ByVal s1 As String, ByVal s2 As String) As Variant()
Dim objWMIService As Object
Dim objDiff As Object
Set objWMIService = GetObject("winmgmts:")
Set objDiff = CreateObject("Google.DiffMatchPath.WSC")
GetDiffs = objDiff.DiffFast(s1, s2)
Set objDiff = Nothing
Set objWMIService = Nothing
End Function
```
(I tried keeping a single global objWMIService and objDiff around so I wouldn't have to create/destroy these for each cell, but it didn't seem to make a difference on performance.)
I then wrote my main macro. It takes three parameters: a range (one column) of original values, a range of new values, and a range where the diff should dump the results. All are *assumed* to have the same number of row, I don't have any serious error-checking going on here.
```
Public Sub DiffAndFormat(ByRef OriginalRange As Range, ByRef NewRange As Range, ByRef DeltaRange As Range)
Dim idiff As Long
Dim thisDiff() As Variant
Dim diffop As String
Dim difftext As String
difftext = ""
Dim diffs() As Variant
Dim OriginalValue As String
Dim NewValue As String
Dim DeltaCell As Range
Dim row As Integer
Dim CalcMode As Integer
```
These next three lines speed up the update without botching the user's preferred calculation mode later:
```
Application.ScreenUpdating = False
CalcMode = Application.Calculation
Application.Calculation = xlCalculationManual
For row = 1 To OriginalRange.Rows.Count
difftext = ""
OriginalValue = OriginalRange.Cells(row, 1).Value
NewValue = NewRange.Cells(row, 1).Value
Set DeltaCell = DeltaRange.Cells(row, 1)
If OriginalValue = "" And NewValue = "" Then
```
Erasing the previous diffs, if any, is important:
```
Erase diffs
```
This test is a visual shortcut for my users so it's clear when there's no change at all:
```
ElseIf OriginalValue = NewValue Then
difftext = "No change."
Erase diffs
Else
```
Combine all the text together as the delta cell value, whether the text was identical, inserted, or deleted:
```
diffs = GetDiffs(OriginalValue, NewValue)
For idiff = 0 To UBound(diffs)
thisDiff = diffs(idiff)
difftext = difftext & thisDiff(1)
Next
End If
```
You have to set the value *before* starting the formatting:
```
DeltaCell.value2 = difftext
Call FormatDiff(diffs, DeltaCell)
Next
Application.ScreenUpdating = True
Application.Calculation = CalcMode
End Sub
```
Here's the code that interprets the diffs and formats the delta cell:
```
Public Sub FormatDiff(ByRef diffs() As Variant, ByVal cell As Range)
Dim idiff As Long
Dim thisDiff() As Variant
Dim diffop As String
Dim difftext As String
cell.Font.Strikethrough = False
cell.Font.ColorIndex = 0
cell.Font.Bold = False
If Not diffs Then Exit Sub
Dim lastlen As Long
Dim thislen As Long
lastlen = 1
For idiff = 0 To UBound(diffs)
thisDiff = diffs(idiff)
diffop = thisDiff(0)
thislen = Len(thisDiff(1))
Select Case diffop
Case -1
cell.Characters(lastlen, thislen).Font.Strikethrough = True
cell.Characters(lastlen, thislen).Font.ColorIndex = 16 ' Dark Gray http://www.microsoft.com/technet/scriptcenter/resources/officetips/mar05/tips0329.mspx
Case 1
cell.Characters(lastlen, thislen).Font.Bold = True
cell.Characters(lastlen, thislen).Font.ColorIndex = 32 ' Blue
End Select
lastlen = lastlen + thislen
Next
End Sub
```
There are some opportunities for optimization, but so far it's working just fine. Thanks to everyone who helped! | The simplest approach may be to embed the Javascript diff logic into a COM component directly using Javascript. This is possible via something called "[Windows Script Components](http://msdn.microsoft.com/en-us/library/47004bz8(VS.85).aspx)".
Here's [a tutorial on creating WSCs](http://www.microsoft.com/technet/scriptcenter/resources/scriptshop/default.mspx).
A Windows Script Component is a COM component that is defined in script. The interface to the component is via COM, which means it is VBA friendly. The logic is implemented in any Windows Scripting Hosting -compatible language, like JavaScript or VBScript. The WSC is defined in a single XML file, which embeds the logic, the component Class ID, the methods, the registration logic, and so on.
There's also a [tool available to help in creating a WSC](http://www.microsoft.com/downloads/details.aspx?familyid=408024ED-FAAD-4835-8E68-773CCC951A6B&displaylang=en). Basically it is a wizard-type thing that asks you questions and fills in the XML template. Myself, I just started with an example .wsc file and edited it by hand with a text editor. It's pretty self-explanatory.
A COM component defined this way in script (in a .wsc file) is callable just like any other COM component, from any environment that can dance with COM.
**UPDATE**: I took a few minutes and produced the WSC for GoogleDiff. Here it is.
```
<?xml version="1.0"?>
<package>
<component id="Cheeso.Google.DiffMatchPatch">
<comment>
COM Wrapper on the Diff/Match/Patch logic published by Google at http://code.google.com/p/google-diff-match-patch/.
</comment>
<?component error="true" debug="true"?>
<registration
description="WSC Component for Google Diff/Match/Patch"
progid="Cheeso.Google.DiffMatchPatch"
version="1.00"
classid="{36e400d0-32f7-4778-a521-2a5e1dd7d11c}"
remotable="False">
<script language="VBScript">
<![CDATA[
strComponent = "Cheeso's COM wrapper for Google Diff/Match/Patch"
Function Register
MsgBox strComponent & " - registered."
End Function
Function Unregister
MsgBox strComponent & " - unregistered."
End Function
]]>
</script>
</registration>
<public>
<method name="Diff">
<parameter name="text1"/>
<parameter name="text2"/>
</method>
<method name="DiffFast">
<parameter name="text1"/>
<parameter name="text2"/>
</method>
</public>
<script language="Javascript">
<![CDATA[
// insert original google diff code here...
// public methods on the component
var dpm = new diff_match_patch();
function Diff(text1, text2)
{
return dpm.diff_main(text1, text2, false);
}
function DiffFast(text1, text2)
{
return dpm.diff_main(text1, text2, true);
}
]]>
</script>
</component>
</package>
```
To use that thing, you have to register it. In Explorer, right click on it, and select "Register". or, from the command line:
regsvr32 file:\c:\scripts\GoogleDiff.wsc
I didn't try using it from VBA, but here is some VBScript code that uses the component.
```
Sub TestDiff()
dim t1
t1 = "The quick brown fox jumped over the lazy dog."
dim t2
t2 = "The large fat elephant jumped over the cowering flea."
WScript.echo("")
WScript.echo("Instantiating a Diff Component ...")
dim d
set d = WScript.CreateObject("Cheeso.Google.DiffMatchPatch")
WScript.echo("Doing the Diff...")
x = d.Diff(t1, t2)
WScript.echo("")
WScript.echo("Result was of type: " & TypeName(x))
' result is all the diffs, joined by commas.
' Each diff is an integer (position), and a string. These are separated by commas.
WScript.echo("Result : " & x)
WScript.echo("Transform result...")
z= Split(x, ",")
WScript.echo("")
redim diffs(ubound(z)/2)
i = 0
j = 0
For Each item in z
If (j = 0) then
diffs(i) = item
j = j+ 1
Else
diffs(i) = diffs(i) & "," & item
i = i + 1
j = 0
End If
Next
WScript.echo("Results:")
For Each item in diffs
WScript.echo(" " & item)
Next
WScript.echo("Done.")
End Sub
``` | The [Windows Scripting Engine](http://www.microsoft.com/downloads/details.aspx?FamilyID=47809025-d896-482e-a0d6-524e7e844d81&DisplayLang=en#Overview) will allow you to run the JavaScript library. It works well in my experience. | How can I use JavaScript within an Excel macro? | [
"",
".net",
"javascript",
"excel",
"vba",
"j#",
""
] |
I have a script that uses `$(document).ready`, but it doesn't use anything else from jQuery. I'd like to lighten it up by removing the jQuery dependency.
How can I implement my own `$(document).ready` functionality without using jQuery? I know that using `window.onload` will not be the same, as `window.onload` fires after all images, frames, etc. have been loaded. | There is a standards based replacement,`DOMContentLoaded` that is supported by over [99% of browsers](http://caniuse.com/#search=DOMContentLoaded), though not IE8:
```
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
```
jQuery's native function is much more complicated than just window.onload, as depicted below.
```
function bindReady(){
if ( readyBound ) return;
readyBound = true;
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", function(){
document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
jQuery.ready();
}, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent("onreadystatechange", function(){
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", arguments.callee );
jQuery.ready();
}
});
// If IE and not an iframe
// continually check to see if the document is ready
if ( document.documentElement.doScroll && window == window.top ) (function(){
if ( jQuery.isReady ) return;
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch( error ) {
setTimeout( arguments.callee, 0 );
return;
}
// and execute any waiting functions
jQuery.ready();
})();
}
// A fallback to window.onload, that will always work
jQuery.event.add( window, "load", jQuery.ready );
}
``` | Edit:
## 2023 update, use this:
```
function ready(fn) {
if (document.readyState !== 'loading') {
fn();
return;
}
document.addEventListener('DOMContentLoaded', fn);
}
```
From: <https://youmightnotneedjquery.com/>
As a one liner by [Tanuki](https://stackoverflow.com/users/1467194/tanuki) with a little tweak:
```
const ready = fn => document.readyState !== 'loading' ? fn() : document.addEventListener('DOMContentLoaded', fn);
```
## Here is a viable replacement for jQuery ready
```
function ready(callback){
// in case the document is already rendered
if (document.readyState!='loading') callback();
// modern browsers
else if (document.addEventListener) document.addEventListener('DOMContentLoaded', callback);
// IE <= 8
else document.attachEvent('onreadystatechange', function(){
if (document.readyState=='complete') callback();
});
}
ready(function(){
// do something
});
```
Taken from
<https://plainjs.com/javascript/events/running-code-when-the-document-is-ready-15/>
[Another good domReady function here](https://github.com/jfriend00/docReady) taken from <https://stackoverflow.com/a/9899701/175071>
---
As the accepted answer was very far from complete, I stitched together a "ready" function like `jQuery.ready()` based on jQuery 1.6.2 source:
```
var ready = (function(){
var readyList,
DOMContentLoaded,
class2type = {};
class2type["[object Boolean]"] = "boolean";
class2type["[object Number]"] = "number";
class2type["[object String]"] = "string";
class2type["[object Function]"] = "function";
class2type["[object Array]"] = "array";
class2type["[object Date]"] = "date";
class2type["[object RegExp]"] = "regexp";
class2type["[object Object]"] = "object";
var ReadyObj = {
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
ReadyObj.readyWait++;
} else {
ReadyObj.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( ReadyObj.ready, 1 );
}
// Remember that the DOM is ready
ReadyObj.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --ReadyObj.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ ReadyObj ] );
// Trigger any bound ready events
//if ( ReadyObj.fn.trigger ) {
// ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
//}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = ReadyObj._Deferred();
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( ReadyObj.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", ReadyObj.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", ReadyObj.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
_Deferred: function() {
var // callbacks list
callbacks = [],
// stored [ context , args ]
fired,
// to avoid firing when already doing so
firing,
// flag to know if the deferred has been cancelled
cancelled,
// the deferred itself
deferred = {
// done( f1, f2, ...)
done: function() {
if ( !cancelled ) {
var args = arguments,
i,
length,
elem,
type,
_fired;
if ( fired ) {
_fired = fired;
fired = 0;
}
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = ReadyObj.type( elem );
if ( type === "array" ) {
deferred.done.apply( deferred, elem );
} else if ( type === "function" ) {
callbacks.push( elem );
}
}
if ( _fired ) {
deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
}
}
return this;
},
// resolve with given context and args
resolveWith: function( context, args ) {
if ( !cancelled && !fired && !firing ) {
// make sure args are available (#8421)
args = args || [];
firing = 1;
try {
while( callbacks[ 0 ] ) {
callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
}
}
finally {
fired = [ context, args ];
firing = 0;
}
}
return this;
},
// resolve with this as context and given arguments
resolve: function() {
deferred.resolveWith( this, arguments );
return this;
},
// Has this deferred been resolved?
isResolved: function() {
return !!( firing || fired );
},
// Cancel
cancel: function() {
cancelled = 1;
callbacks = [];
return this;
}
};
return deferred;
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ Object.prototype.toString.call(obj) ] || "object";
}
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( ReadyObj.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
ReadyObj.ready();
}
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
ReadyObj.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
ReadyObj.ready();
}
};
}
function ready( fn ) {
// Attach the listeners
ReadyObj.bindReady();
var type = ReadyObj.type( fn );
// Add the callback
readyList.done( fn );//readyList is result of _Deferred()
}
return ready;
})();
```
How to use:
```
<script>
ready(function(){
alert('It works!');
});
ready(function(){
alert('Also works!');
});
</script>
```
I am not sure how functional this code is, but it worked fine with my superficial tests. This took quite a while, so I hope you and others can benefit from it.
PS.: I suggest [compiling](http://closure-compiler.appspot.com/home) it.
Or you can use <http://dustindiaz.com/smallest-domready-ever>:
```
function r(f){/in/.test(document.readyState)?setTimeout(r,9,f):f()}
r(function(){/*code to run*/});
```
or the native function if you only need to support the new browsers (Unlike jQuery ready, this won't run if you add this after the page has loaded)
```
document.addEventListener('DOMContentLoaded',function(){/*fun code to run*/})
``` | $(document).ready equivalent without jQuery | [
"",
"javascript",
"jquery",
"pageload",
""
] |
Sometimes I hear the argument against doing things on client side using javascript. People say stuff like "JavaScript is inefficient...or slow". I'm wondering if there actual facts supporting this conclusion? | There are really two factors to Javascript performance:
1. Your code
2. The scripting engine running your code
Your code is the easiest factor to fix. As you develop, optimize your code as best you can. Easy.
The second isn't always as easy. I've had some applications where performance on one browser was excellent and another was slower than mud. Others run great across the board. Best you can do is test, test, test, and test again. If you want a good article, check out the link:
[Coding Horror: The Great Browser JavaScript Showdown](http://www.codinghorror.com/blog/archives/001023.html) | That depends alot on the browser's javascript engine.
Over all, it's a scripting language, so it won't do as well as C++ or another compiled language. However, it's good at what it was intended for, and that's drive web pages. | How efficient is javascript? | [
"",
"javascript",
"performance",
""
] |
I am a newbie in WCF, currently I am developing a TCP WCF service and I am not sure that I understand passing parameters correctly or not so I recommend you to comment and give a standardized way.
To get things clear I developed a small service for testing purpose that has single method and depends on an external .Net dll that exposes single class.
The service contract code
```
[ServiceContract]
public interface IMyService
{
[OperationContract]
int Test1(actionType at, calculationType ct, action a);
[OperationContract]
int Test2(DataSeries s);
}
```
Where `actionType`,`calculationType`,`action` are enums declared inside the the external dll
and `DataSeries` is a class declared inside the dll.
The origianl defination for the `DataSeries` class in the dll is marked by `[Serializable]` only and no `[DataMember]` on its members.
I am using the 3rd dll on the client and server side, my surprise was both applications working fine without putting `[DataContract]` on the DataSeries class and without using any of `[EnumMember]` inside enums, `[DataMember]` inside class.
So what is going on?
Another Experiment:
Removing the 3rd party from the client side and using the service as it is
I found that the vs2008 generates the enums and the `DataSeries` class and markes them with the proper attributes?
like
```
[System.CodeDom.Compiler.GeneratedCodeAttribute ("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="actionType", Namespace="http://schemas.datacontract.org/2004/07/DBInterface")]
public enum actionType : int {
[System.Runtime.Serialization.EnumMemberAttribute()]
All = 0,
[System.Runtime.Serialization.EnumMemberAttribute()]
Buy = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Sell = 2,
}
``` | [DataContract](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datacontractattribute?view=net-6.0), [DataMember](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datamemberattribute?view=net-6.0) and [EnumMember](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.enummemberattribute?view=net-6.0) attributes are used by the [DataContractSerializer](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.datacontractserializer?view=net-6.0) (usually [basicHttpBinding](https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.basichttpbinding?view=dotnet-plat-ext-6.0) or [wsHttpBinding](https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.wshttpbinding?view=dotnet-plat-ext-6.0)). If you are exposing an endpoint with TCP binding ([netTcpBinding](https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.nettcpbinding?view=dotnet-plat-ext-6.0)) only [SerializableAttribute](https://learn.microsoft.com/en-us/dotnet/api/system.serializableattribute?view=net-6.0) is required. Note that with DataContractSerializer you could only add SerializableAttribute to your classes and it will automatically serialize all fields.
I would recommend you the following: if you want your service to be interoperable, use basicHttpBinding and mark your classes with DataContract and DataMember attributes. If your client is a .NET application, use netTcpBinding and mark your classes with SerializableAttribute.
You could also read this [post](https://web.archive.org/web/20190205023902/http://geekswithblogs.net/claraoscura/archive/2007/05/28/112799.aspx) for comparison between different bindings. | > But without using DataContract or any
> attributes, I found the client side
> working correctly
Yes, that's true - if the data types you use aren't marked with the [DataContract], WCF will try to use the default SOAP serializer on them and just serialize everything that's public (all public properties).
It works - but it might not be what you want / expect - so I'd second darin's opinion - just always use explicit [DataContract] attributes on your types. The clearer you make your intent to yourself (or other programmers who need to maintain your code later), the better. These "magic tricks" that happen behind the scenes tend to cause confusion at times - you're better off **not** relying on them too much
Marc | What is the standardized way to pass complex types in WCF? | [
"",
"c#",
"wcf",
"argument-passing",
""
] |
I am using asp.net MVC.
I have control like
`<%= Html.TextBox("username") %>`
I want lost focus event to that control.
So code like
```
$(document).ready(function() {
$("#username").Attributes.Add("onblur", "alert('losing focus');");
});
```
but it is not working,
Ultimate goal is to check password & confirm password matches
help me! | It looks like you're trying to use C# code in jQuery?
The easiest way to bind an event to onblur in jQuery is:
```
$("#username").blur(function() { alert('losing focus'); });
```
More information on blur() is available at <http://docs.jquery.com/Events/blur> | ```
$(document).ready(function() {
$("#username").blur(function() {
alert('byebye focus');
});
});
```
<http://docs.jquery.com/Events/blur> | Add attributes to textbox using jQuery | [
"",
"javascript",
"jquery",
"asp.net-mvc",
""
] |
Are there any bridges to make mixing Qt with STL and Boost as seamless and easy as possible?
This is a followup to [Mixing Qt and Boost](https://stackoverflow.com/questions/360160), where no specific answers how to accomplish this were given. | What bridges do you need?
You can use all the Qt container classes with std algorithms.
Most of the time I prefer the Qt container classes because I'm sure they use the copy-on-write idiom (constant time operation). Qt's foreach function creates a copy of the container so its nice that you know for sure it is a constant time operation.
If the Qt signal slot mechanism is to slow you can switch to the boost alternative.
The great thing about Qt signal/slot is the signal/slot connection between two threads.
QtConcurrent works great with BOOST.Lambda
---
For "shared" child-parent relationship I use this helper function.
```
template <class Object>
static boost::shared_ptr<Object> makeSharedObject()
{
using namespace boost;
using namespace boost::lambda;
return boost::shared_ptr<Object>(
new Object(),
bind( &Object::deleteLater, _1 ) );
}
```
---
Qt containers are not supported by Boost.serialize, you'll have to write the serialize functions yourself.
I would love a bridge between the Qt streaming classes and Boost.archive.
Here is my QList serialization template you can figure out the rest of them ...
```
///\file document is based on "boost/serialization/list.hpp"
namespace boost {
namespace serialization {
//---------------------------------------------------------------------------
/// Saves a QList object to a collection
template<class Archive, class U >
inline void save(Archive &ar, const QList< U > &t, const uint /* file_version */ )
{
boost::serialization::stl::save_collection< Archive, QList<U> >(ar, t);
}
//---------------------------------------------------------------------------
/// Loads a QList object from a collection
template<class Archive, class U>
inline void load(Archive &ar, QList<U > &t, const uint /* file_version */ )
{
boost::serialization::stl::load_collection<
Archive,
QList<U>,
boost::serialization::stl::archive_input_seq<Archive, QList<U> >,
boost::serialization::stl::no_reserve_imp< QList<U> > >(ar, t);
}
//---------------------------------------------------------------------------
/// split non-intrusive serialization function member into separate
/// non intrusive save/load member functions
template<class Archive, class U >
inline void serialize(Archive &ar, QList<U> &t, const uint file_version )
{
boost::serialization::split_free( ar, t, file_version);
}
} // namespace serialization
} // namespace boost
BOOST_SERIALIZATION_COLLECTION_TRAITS(QList)
```
---
If you want Boost.Bind to handle QPointer as a normal pointer (like shared\_ptr):
```
namespace boost {
template<typename T> T * get_pointer(QPointer<T> const& qPointer)
{
return qPointer;
}
}
```
---
Using `QIODevice` where a `std::stream` is needed
```
namespace boost {
namespace iostreams {
class IoDeviceSource
{
public:
typedef char char_type;
typedef source_tag category;
explicit IoDeviceSource(QIODevice& source)
: m_source(source)
{
}
std::streamsize read(char* buffer, std::streamsize n)
{
return return m_source.read(buffer, n);
}
private:
QIODevice& m_source;
};
class IoDeviceSink {
public:
typedef char char_type;
typedef sink_tag category;
explicit IoDeviceSink(QIODevice& sink)
: m_sink(sink)
{
}
std::streamsize write(const char_type* buffer, std::streamsize n)
{
return m_sink.write(buffer, n);
}
private:
QIODevice &m_sink;
};
class IoDeviceDevice {
public:
typedef char char_type;
typedef seekable_device_tag category;
explicit IoDeviceDevice(QIODevice& device)
:m_device(device) {
}
std::streamsize write(const char_type *buffer, std::streamsize n)
{
return m_device.write(buffer, n);
}
std::streamsize read(char* buffer, std::streamsize n)
{
return m_device.read(buffer, n);
}
stream_offset seek(stream_offset off, std::ios_base::seekdir way)
{
using namespace std;
stream_offset next(0);
if(way==ios_base::beg)
{
next = m_device.pos();
}
else if(way==ios_base::cur)
{
next = m_device.pos() + offset;
}
else if(way==ios_base::end)
{
next = m_device.size() -1 + offset;
}
else
{
throw ios_base::failure("bad seek direction");
}
if( !m_device.seek(next) )
{
throw ios_base::failure("bad seek offset");
}
return m_device.pos();
}
private:
QIODevice &m_device;
};
}
}
```
**Example**
```
#include <iostream>
#include <QFile>
#include <boost/iostreams/stream.hpp>
#include "iodevicestream.h"
int main(int argc, char *argv[])
{
namespace io = boost::iostreams;
QVector<int> data;
QFile fl("temp.bin");
fl.open(QIODevice::ReadWrite);
io::stream<io::IoDeviceDevice> inoutput( fl );
std::copy(data.begin(), data.end(), std::ostream_iterator<int>(inoutput, "\n"));
inoutput.flush();
inoutput.seekg(0, std::ios_base::beg);
std::cout << inoutput;
return 0;
}
``` | What exactly is the problem?
You can ignore all the Qt collection classes if you want and use STL equivalents.
Similarly you can use Boost's cross platform file/network libs.
The main reason to use Qt's own is probably that boost isn't necessarily that widely available, especially on mobile devices. Some of Boost's libs are a little more complicated to use than the Qt ones for simple tasks. | Mixing Qt with STL and Boost - are there any bridges to make it easy? | [
"",
"c++",
"qt",
"boost",
"stl",
""
] |
Suppose I had the string "1 AND 2 AND 3 OR 4", and want to create an array of strings that contains all substrings "AND" or "OR", in order, found within the string.
So the above string would return a string array of {"AND", "AND", "OR"}.
What would be a smart way of writing that?
EDIT:
Using C# 2.0+,
```
string rule = "1 AND 2 AND 3 OR 4";
string pattern = "(AND|OR)";
string[] conditions = Regex.Split(rule, pattern);
```
gives me {"1", "AND", "2", "AND", "3", "OR", "4"}, which isn't quite what I'm after. How can I reduce that to the ANDs and ORs only? | This regex (.NET) seems to do what you want. You're looking for the matches (multiple) in the group at index=1:
```
.*?((AND)|(OR))*.*?
```
**EDIT** I've tested the following and it seems to do what you want. It's more lines than i would like but it approaches the task in a purely regex fashion (which IMHO is what you should be doing):
```
string text = "1 AND 2 AND 3 OR 4";
string pattern = @"AND|OR";
Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
Match m = r.Match(text);
ArrayList results = new ArrayList();
while (m.Success)
{
results.Add(m.Groups[0].Value);
m = m.NextMatch();
}
string[] matchesStringArray = (string[])results.ToArray(typeof(string));
``` | Your probably looking for a tokeniser or Lexer, have a look at the following article:
[C# Regular Expression Recipes—A Better Tokenizer](http://en.csharp-online.net/CSharp_Regular_Expression_Recipes%E2%80%94A_Better_Tokenizer) | C#: finding instances of a string within a string | [
"",
"c#",
"string",
"matching",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.