input stringlengths 51 42.3k | output stringlengths 18 55k |
|---|---|
Need to know some basics of LinkedList class in Java <pre><code>package abc;
class DependencyDataCollection
{
private int sNo;
private String sessionID;
private int noOfDependency;
private int noOfRejection;
private int totalValue;
/** Creates a new instance of DependencyDataCollection */
public DependencyDataCollection(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue)
{
this.sNo = sNo;
this.sessionID = sessionID;
this.noOfDependency = noOfDependency;
this.noOfRejection = noOfRejection;
this.totalValue = totalValue;
}
public int getSNo()
{
return sNo;
}
public String getSessionID()
{
return sessionID;
}
public int getNoOfDependency()
{
return noOfDependency;
}
public int getNoOfRejection()
{
return noOfRejection;
}
public int getTotalValue()
{
return totalValue;
}
}
public class DependencyStack {
LinkedList lList;
/** Creates a new instance of DependencyStack */
public DependencyStack()
{
lList = new LinkedList();
}
public void add(int sNo, String sessionID, int noOfDependency, int noOfRejection, int totalValue)
{
lList.add(new DependencyDataCollection(sNo,sessionID,noOfDependency,noOfRejection,totalValue));
}
public int size()
{
return lList.size();
}
public void show()
{
for(int i=0;i<lList.size();i++)
{
DependencyDataCollection ddc = (DependencyDataCollection)lList.get(i);
System.out.println(ddc.getSNo()+" "+ddc.getSessionID()+" "+ddc.getNoOfDependency()+" "+ddc.getNoOfRejection()+" "+ddc.getTotalValue());
}
}
public int returnIndexOfSession(String sessionID)
{
DependencyDataCollection ddc = null;
for(int i=0;i<lList.size();i++)
{
ddc = (DependencyDataCollection)lList.get(i);
if(ddc.getSessionID().equals(sessionID))
break;
}
return ddc.getSNo();
}
public static void main(String args[])
{
DependencyStack ds = new DependencyStack();
ds.add(1,"a",0,0,0);
ds.add(2,"b",0,0,0);
ds.show();
//System.out.println(ds.returnIndexOfSession("a"));
// DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
// System.out.println(ds.indexOf(ddc));
}
}
</code></pre>
<p>This is a simple Linked List program in java which is using inbuilt linkedlist class from java.util package. The linked list is used to store different amount of data using DependencyDataCollection Class..</p>
<p><strong>Now my question is</strong> </p>
<blockquote>
<p>1) Please evaluate this program,
and temme am i respecting all java
concepts like private member
access,which i have done, etc..</p>
<p>2) I am facing problem to find the
indexOf a particular session.</p>
<p>For e.g. Node 1 contains
1,"a",0,0,0...............Node 2
contains 2,"b",0,0,0</p>
<p>Now i wanted to find the indexOf the
node which is containing one of the
data as "b" or "a". What could be the shortest inbuilt method which can do so, as i have made a function named "public int returnIndexOfSession(String sessionID)" which makes use of for loop, i find this very time consuming.. Is there any other way out.. </p>
</blockquote>
<p>Please evaluate and guide as i am a newbie in java.</p>
| <p>Here are the changes I would make, rationale is in the comments.</p>
<pre><code>import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
class DependencyDataCollection
{
// makte them fnal, then you hava an immutible object and your code is much safer.
// in your case you had noset methods so it was safe, but always try to make things final.
private final int sNo;
private final String sessionID;
private final int noOfDependency;
private final int noOfRejection;
private final int totalValue;
public DependencyDataCollection(final int sNo,
final String sessionID,
final int noOfDependency,
final int noOfRejection,
final int totalValue)
{
this.sNo = sNo;
this.sessionID = sessionID;
this.noOfDependency = noOfDependency;
this.noOfRejection = noOfRejection;
this.totalValue = totalValue;
}
public int getSNo()
{
return sNo;
}
public String getSessionID()
{
return sessionID;
}
public int getNoOfDependency()
{
return noOfDependency;
}
public int getNoOfRejection()
{
return noOfRejection;
}
public int getTotalValue()
{
return totalValue;
}
}
class DependencyStack
{
// change the type to be as generic as poosible - List interface
// added generics so you get compile time safety and don't use casts later on
// renamed it to something meaningful
private final List<DependencyDataCollection> dependencies;
// use an ArrayList instead of a LinkedList, it'll be faster since you are not inserting/deleting
// into the middle of the list
{
dependencies = new ArrayList<DependencyDataCollection>();
}
// your Stack shouldn't know how to make the collections... (in my opinion)
public void add(final DependencyDataCollection ddc)
{
dependencies.add(ddc);
}
public int size()
{
return dependencies.size();
}
// the next 3 methods are just convenience since you don't know if someione
// will want to write to a file or a writer instead of a stream
public void show()
{
show(System.out);
}
public void show(final OutputStream out)
{
show(new OutputStreamWriter(out));
}
public void show(final Writer writer)
{
show(new PrintWriter(writer));
}
public void show(final PrintWriter writer)
{
// use the new for-each instead of the old style for loop
// this also uses an iterator which is faster than calling get
// (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster)
for(final DependencyDataCollection ddc : dependencies)
{
writer.println(ddc.getSNo() + " " +
ddc.getSessionID() + " " +
ddc.getNoOfDependency() + " " +
ddc.getNoOfRejection() + " " +
ddc.getTotalValue());
}
}
public int returnIndexOfSession(final String sessionID)
{
DependencyDataCollection foundDDC;
final int retVal;
foundDDC = null;
for(final DependencyDataCollection ddc : dependencies)
{
if(ddc.getSessionID().equals(sessionID))
{
foundDDC = ddc;
break;
}
}
// deal with the fact that you might have not found the item and it would be null.
// this assumes -1 is an invalid session id
if(foundDDC == null)
{
retVal = -1;
}
else
{
retVal = foundDDC.getSNo();
}
return (retVal);
}
public static void main(final String[] args)
{
DependencyStack ds = new DependencyStack();
ds.add(new DependencyDataCollection(1,"a",0,0,0));
ds.add(new DependencyDataCollection(1,"a",0,0,0));
ds.show();
//System.out.println(ds.returnIndexOfSession("a"));
// DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
// System.out.println(ds.indexOf(ddc));
}
}
</code></pre>
<p>Edit: </p>
<p>This one will speed up the lookups (and deletes).</p>
<pre><code>class DependencyStack
{
// A Map provides quick lookup
private final Map<String, DependencyDataCollection> dependencies;
// a LinkedHashMap allows for quick lookup, but iterates in the order they were added... if that matters for show.
{
dependencies = new LinkedHashMap<String, DependencyDataCollection>();
}
// your Stack shouldn't know how to make the collections... (in my opinion)
public void add(final DependencyDataCollection ddc)
{
if(ddc == null)
{
throw new IllegalArgumentException("ddc cannot be null");
}
dependencies.put(ddc.getSessionID(), ddc);
}
public int size()
{
return dependencies.size();
}
// the next 3 methods are just convenience since you don't know if someione
// will want to write to a file or a writer instead of a stream
public void show()
{
show(System.out);
}
public void show(final OutputStream out)
{
show(new OutputStreamWriter(out));
}
public void show(final Writer writer)
{
show(new PrintWriter(writer));
}
public void show(final PrintWriter writer)
{
// use the new for-each instead of the old style for loop
// this also uses an iterator which is faster than calling get
// (well on an ArrayList it probably is about the same, but a LinkedList it'll be faster)
for(final DependencyDataCollection ddc : dependencies.values())
{
writer.println(ddc.getSNo() + " " +
ddc.getSessionID() + " " +
ddc.getNoOfDependency() + " " +
ddc.getNoOfRejection() + " " +
ddc.getTotalValue());
}
}
public int returnIndexOfSession(final String sessionID)
{
final DependencyDataCollection ddc;
final int retVal;
if(sessionID == null)
{
throw new IllegalArgumentException("sessionID cannot be null");
}
// get it if it exists, this is much faster then looping through a list
ddc = dependencies.get(sessionID);
// deal with the fact that you might have not found the item and it would be null.
// this assumes -1 is an invalid session id
if(ddc == null)
{
retVal = -1;
}
else
{
retVal = ddc.getSNo();
}
return (retVal);
}
public static void main(final String[] args)
{
DependencyStack ds = new DependencyStack();
ds.add(new DependencyDataCollection(1,"a",0,0,0));
ds.add(new DependencyDataCollection(1,"a",0,0,0));
ds.show();
//System.out.println(ds.returnIndexOfSession("a"));
// DependencyDataCollection ddc = new DependencyDataCollection(1,"a",0,0,0);
// System.out.println(ds.indexOf(ddc));
}
}
</code></pre>
|
Have a good hash function for a C++ hash table? <p>I am in need of a performance-oriented hash function implementation in C++ for a hash table that I will be coding. I looked around already and only found questions asking what's a good hash function "in general". I've considered CRC32 (but where to find good implementation?) and a few cryptography algorithms. My table, though, has very specific requirements.</p>
<p>Here's what the table will be like:</p>
<pre><code>100,000 items max
200,000 capacity (so the load is 0.5)
hashing a 6-character string which is a part of English sentence
examples: "become" "and he" ", not "
</code></pre>
<p>The <em>number one priority</em> of my hash table is quick search (retrieval). Quick insertion is not important, but it will come along with quick search. Deletion is not important, and re-hashing is not something I'll be looking into. To handle collisions, I'll be probably using <em>separate chaining</em> as described <a href="http://eternallyconfuzzled.com/tuts/datastructures/jsw%5Ftut%5Fhashtable.aspx">here</a>. I have already looked at <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw%5Ftut%5Fhashing.aspx">this article</a>, but would like an opinion of those who have handled such task before.</p>
| <p>Now assumming you want a hash, and want something <strong>blazing fast</strong> that would work in your case, because your strings are just 6 chars long you could use this magic:</p>
<pre><code>size_t precision = 2; //change the precision with this
size_t hash(const char* str)
{
return (*(size_t*)str)>> precision;
}
</code></pre>
<p>CRC is for slowpokes ;)</p>
<p><strong>Explanation:</strong>
This works by casting the contents of the string pointer to "look like" a size_t (int32 or int64 based on the optimal match for your hardware). So the contents of the string are interpreted as a raw number, no worries about characters anymore, and you then bit-shift this the precision needed (you tweak this number to the best performance, I've found 2 works well for hashing strings in set of a few thousands). </p>
<p>Also the really neat part is any decent compiler on modern hardware will hash a string like this in 1 assembly instruction, hard to beat that ;)</p>
|
Will there be any problem by copying a version of Java from one PC to another instead of installing it <p>I'd like to embed the directory and subdirectories from a current Java 1.6 update 11 into a software package that I will be installing on several other PCs and will like to know what the cons about doing this are (if any). I want to do that so that my version on Java doesn't override other versions on the PCs.</p>
| <p>On Linux, no issues. On Windows too, should not be any issues if you are using the JDK/JRE by setting the path and JAVA_HOME to the directory. You won't be able to use the applet plugin, however, without messing with the registry.</p>
|
What is the best way to cater for users reporting bugs? <p>ok, <a href="http://www.bugzilla.org/" rel="nofollow">Bugzilla</a> would scare the willies out of the average end-user. Even things like <a href="http://www.mantisbt.org/" rel="nofollow">Mantis</a> are a little spooky for the uninitiated.</p>
<p>What method, web package (preferred), interface, whatever can I implement to make it easy, intuitive and not-at-all-intimidating for my end users & customers to report bugs in an intelligible manner?</p>
<p>I like the idea of something forms-based, or point-and-clicky, rather than the prior knowledge needed by something as comprehensive and intimidating as Bugzilla.</p>
<p>Email, while approachable for the average punter, seems less than ideal since it doesn't prompt the user for the kinds of information I need to try & figure out what is broken.</p>
<p>So far <a href="http://www.thebuggenie.com/" rel="nofollow">Bugs - The Bug Genie</a> seems like the least scary option to confront the average user with. I searched but didn't find any questions like mine.</p>
<p>Suggestions, ideas, insights please !</p>
| <p>You're absolutely right - it's not up to the user to use bugzilla. that's for devs.</p>
<p>Error reporting from the user side needs to be really simple if you expect users to use it. (ie. When I see the "report this bug to MS" i usually hit cancel even though it's a one-click mechanism.)</p>
<p>It's also not just about you getting the info you need to track the bug, it's also about making the user feel like something's being done, like they're being taken care of, so keep that in mind.</p>
<p>As a result of all this, I'd go with whatever bug tracking package suited you as a developer and then feed into that from a nice, simple, friendly web-form interface built specifically for your end users.</p>
<p>Then when an error occurs, try to only ask the user questions you can't answer programatically. Ideally, your exception handling should already track their current action (saving an invoice), current context (invoice screen), the entity being acted upon(invoice #10013), and all the exception info from the program. If you can't capture this and retrieve it remotely, feed it to your web form (in URL params or whatever) when the user clicks 'report this issue'. Ensure you pay attention to any sensitive data requirements.</p>
<p>Then you should only need to ask your users the human questions like - 'How can we best contact you about this issue?' (method / times / etc.), and give them an idea of how long it'll take for them to get a response from a human.</p>
<p>I realise this doesn't offer a software recommendation, but hopefully it's still good advice for handling your issue.</p>
|
Connecting to a CDMA network IN from Java <p>Am using java to develop program that receives and processes SMS messages. I have been able to code the processing of the SMS Messages received and its working perfectly. Now the challenge i have is receiving the the SMS Messages from the CDMA network. When the application is about to go live, the CDMA network will setup a VPN connection which will enable my application to connect to its IN or its IN connect to my application to deliver the SMS Messages to my application over the VPN. Now, in what format will be SMS be sent to the application? Or will i just need to listen on the VPN and read data's when they become available? Thank you very much for your time.</p>
<p>Thanks.</p>
| <p>I assume that by IN you mean <a href="http://en.wikipedia.org/wiki/Intelligent%5Fnetwork" rel="nofollow">Intelligent Network</a>? Usually IN is not relevant for sending/receiving SMS messages - you need to connect to the <a href="http://en.wikipedia.org/wiki/Short%5Fmessage%5Fservice%5Fcenter" rel="nofollow">Short Message Service Center</a> (SMSC) (or some proxy/gateway) in order to do that.</p>
<p>As also pointed out by Bombe, there are several protocols that you can use to connect to the mobile operators SMSC, it is all quite vendor-specific, due to historic reasons. Common protocols are:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/SMPP" rel="nofollow">SMPP</a> (most popular, becoming the de-facto standard). There are two SMPP java libraries:
<ul>
<li><a href="http://sourceforge.net/projects/smppapi" rel="nofollow">SMPP API at SourceForge</a> - very stable and mature library, I have personally used it in several projects and can recommend it. </li>
<li><a href="http://opensmpp.logica.com/" rel="nofollow">Logica OpenSMPP</a> - library from the company that developed the SMPP specification. I have never used this, so I cannot comment on its maturity or stability.</li>
</ul></li>
<li><a href="http://en.wikipedia.org/wiki/Universal%5FComputer%5FProtocol" rel="nofollow">UCP</a> (<a href="http://www.nowsms.com/discus/messages/1/EMI%5FUCP%5FSpecification%5F40-8156.pdf" rel="nofollow">specification</a>) - quite old standard. I'm not aware of any open java libraries for this protocol. However, as it is all ASCII-based, it is fairly easy to implement yourself (as long as you like messing with bytes :-)).</li>
<li><a href="http://en.wikipedia.org/wiki/CIMD" rel="nofollow">CIMD2</a> - specification for communicating with Nokia SMSCs. It is becoming legacy, as I have heard that newer Nokia SMSC releases also support SMPP. No known open java libraries for this either.</li>
<li>and finally, there are gazillions of custom protocols implemented to make it "easier" for 3rd-party developers to connect to SMSCs. These are usually based on HTTP and XML (SOAP, if you are lucky).</li>
</ul>
<p>To sum up, the choice of protocol is not yours to make. It is usually dictated by the SMSC vendor or the mobile operator (in case they have developed some sort of "proxy/gateway", to shield their SMSC from potential programming errors that external developers can make).</p>
<p>P.S. in case you are not limited to java, you can also have a look at <a href="http://www.kannel.org/" rel="nofollow">Kannel - the Open Source WAP and SMS gateway</a>. I have not used it myself, but as far as I have heard, they should have all major protocols covered.</p>
|
Problems with IRQs when connecting two digium card in and asterisk box <p>I have two Digium Wildcard TDM800P with 8 FXO ports each. When I connect both at the same time IRQ misses start showing up making my computer unresponsive and unusable. </p>
<p>One card works fine but I need all 16 FXO ports to work to receive calls from my Telco. Is there a way for the cards to communicate with each other so they don't generate as many interrupts. Or a way to tweak Linux to dedicate separate IRQ's for each card.</p>
<p>I have tried disabling Audio, ACPI and USB ports. Still too many IRQ misses. </p>
| <p>This question would be better posted at serverfault, as this is a pure hardware problem.</p>
<p>The problem you are experiencing is typical of high interrupt PCI cards in general, and Digium telephony cards in particular. Please keep in mind that the problem stems from having both cards in the <strong>same</strong> PCI bus, your objective is to not have them share IRQ interrupts.</p>
<p>There are a couple of things you can try that can resolve your problem:</p>
<p><strong>1) Upgrade to DAHDI drivers</strong>. They have better IRQ contention.</p>
<p><strong>2) Change one of the cards to another PCI slot</strong>. Some PCI slots on the motherboard share lanes. You want to avoid this. Check your motherboards manual. Also, you can execute the following</p>
<pre><code>cat /proc/interrupts
</code></pre>
<p>You should receive output like this</p>
<pre><code> CPU0 CPU1 CPU2 CPU3
0: 37 2 5 8 IO-APIC-edge timer
1: 1 1 0 0 IO-APIC-edge i8042
8: 0 0 1 0 IO-APIC-edge rtc0
9: 0 0 0 0 IO-APIC-fasteoi acpi
12: 1 0 0 3 IO-APIC-edge i8042
14: 33 35 31 30 IO-APIC-edge ide0
20: 0 0 0 0 IO-APIC-fasteoi uhci_hcd:usb2
21: 37 37 41 38 IO-APIC-fasteoi uhci_hcd:usb1, uhci_hcd:usb3, ehci_hcd:usb4
1269: 14357 14387 14387 14372 PCI-MSI-edge eth0
1270: 2523 2490 2489 2503 PCI-MSI-edge ioc0
NMI: 0 0 0 0 Non-maskable interrupts
LOC: 487635 236288 376032 88504 Local timer interrupts
RES: 507 516 571 701 Rescheduling interrupts
CAL: 205 281 237 201 function call interrupts
TLB: 2835 2190 2221 1737 TLB shootdowns
TRM: 0 0 0 0 Thermal event interrupts
THR: 0 0 0 0 Threshold APIC interrupts
SPU: 0 0 0 0 Spurious interrupts
ERR: 0
</code></pre>
<p>See how in interrupt 21 is shared by usb1, usb3, and usb4? You don't want that to happen to your Digium cards. By the way, Digium cards ususaly show up as TDPXXX.</p>
<p><strong>3) Load balance interrupts between CPU's</strong> - If your PC has more than one CPU and your kernel and motherboard support IO-APIC, you can load balance interrupts between different CPU's. This will also ease greatly the interrupt load on your CPU's. If you check my previously posted code, you can see that Local timer interrupts are spread evenly between CPU's. If your Digium cards hammer only one CPU (this happens) you can spread out the load by trying the following. Say we wanted to change IRQ 21 (the aforementioned USB's)</p>
<pre><code>cat /proc/irq/21/smp_affinity
ffffffff
</code></pre>
<p>All those 'f' tell us that the interrupt load from IRQ 21 is load balanced between all CPU's. If you want to assign it to a certain CPU, add that nuber to the right in hexadecimal. For example, lets say I want the USB's to only interrupt CPU0. </p>
<pre><code>echo 1 > /proc/irq/21/smp_affinity
cat /proc/irq/21/smp_affinity
00000001
</code></pre>
<p>So now only the first CPU (CPU0) is enabled to receive these interrupts.</p>
<p>Good luck!</p>
|
Extending/replacing Html.Image for Amazon S3 (or other CDN) <p>Just want to confirm that there is no way to extend or replace Html.Image functionality without writing a replacement function.</p>
<p>I want to write a function that will use Amazon's S3 service for hosting images.</p>
<p>The best approach I've come up with is a helper method <code>Html.SmartImage</code> which would check a configuration property to see if i wanted to go to Amazon or not. It may even check a database of files that are hosted remotely and only 'farm them out' if they are in that list.</p>
<p>I'll post what I have when I've done it - but curious about any 'outside the box' ideas.</p>
| <p>No you are right, you need to create your own extension method to handle custom scenarios like this.</p>
|
Constructors vs Factory Methods <p>When modelling classes, what is the preferred way of initializing:</p>
<ol>
<li>Constructors, or</li>
<li>Factory Methods</li>
</ol>
<p>And what would be the considerations for using either of them?</p>
<p>In certain situations, I prefer having a factory method which returns null if the object cannot be constructed. This makes the code neat. I can simply check if the returned value is not null before taking alternative action, in contrast with throwing an exception from the constructor. (I personally don't like exceptions)</p>
<p>Say, I have a constructor on a class which expects an id value. The constructor uses this value to populate the class from the database. In the case where a record with the specified id does not exist, the constructor throws a RecordNotFoundException. In this case I will have to enclose the construction of all such classes within a try..catch block.</p>
<p>In contrast to this I can have a static factory method on those classes which will return null if the record is not found.</p>
<p>Which approach is better in this case, constructor or factory method?</p>
| <p>Ask yourself what they are and why do we have them. They both are there to create instance of an object.</p>
<pre><code>ElementarySchool school = new ElementarySchool();
ElementarySchool school = SchoolFactory.Construct(); // new ElementarySchool() inside
</code></pre>
<p>No difference so far. Now imagine that we have various school types and we want to switch from using ElementarySchool to HighSchool (which is derived from an ElementarySchool or implements the same interface ISchool as the ElementarySchool). The code change would be:</p>
<pre><code>HighSchool school = new HighSchool();
HighSchool school = SchoolFactory.Construct(); // new HighSchool() inside
</code></pre>
<p>In case of an interface we would have:</p>
<pre><code>ISchool school = new HighSchool();
ISchool school = SchoolFactory.Construct(); // new HighSchool() inside
</code></pre>
<p>Now if you have this code in multiple places you can see that using factory method might be pretty cheap because once you change the factory method you are done (if we use the second example with interfaces).</p>
<p>And this is the main difference and advantage. When you start dealing with a complex class hierarchies and you want to dynamically create an instance of a class from such a hierarchy you get the following code. Factory methods might then take a parameter that tells the method what concrete instance to instantiate. Let's say you have a MyStudent class and you need to instantiate corresponding ISchool object so that your student is a member of that school. </p>
<pre><code>ISchool school = SchoolFactory.ConstructForStudent(myStudent);
</code></pre>
<p>Now you have one place in your app that contains business logic that determines what ISchool object to instantiate for different IStudent objects.</p>
<p>So - for simple classes (value objects, etc.) constructor is just fine (you don't want to overengineer your application) but for complex class hierarchies factory method is a preferred way. </p>
<p>This way you follow the first design principle from the <a href="http://rads.stackoverflow.com/amzn/click/0201633612">gang of four book</a> "Program to an interface, not an implementation".</p>
|
NHibernate logs and executes a query twice in a row <p>I am using: NHibernate, NHibernate.Linq and Fluent NHibernate on SQL Server Express 2008. I am selecting an entity using a predicate on a referenced property (many-one mapping). I have fetch=join, unique=true, lazy-load=false. I enabled the log4net log and when any such query executes it logs two identical SQL queries. Running the query returns one row, and when I attempt to use the IQueryable.Single extension method it throws the exception stating there is more than one row returned. I also tried running the query using the standard IQuery.UniqueResult method with the same result, it ends up logging and actually running the query twice, then throwing an exception stating that there were multiple rows, however running the actual query in management studio returns only one result. When I disable logging I receive the same error.</p>
<p>The entities and mappings are declared as follows (proper access modifiers and member type variance are implied)</p>
<pre><code>class User
{
int ID;
string UserName;
}
class Client
{
int ID;
User User;
Person Person;
Address Address;
}
class UserMap : ClassMap<User>
{
public UserMap()
{
Id(x => x.ID);
Map(x => x.UserName);
}
}
class ClientMap : ClassMap<Client>
{
public ClientMap()
{
Id(x => x.ID);
References(x => x.User).Unique();
...
}
}
</code></pre>
<p>Then I invoke a queries such as the following:</p>
<pre><code>ISession s = GetNHibernateSession();
...
var client = s.Linq<Client>().SingleOrDefault(x => x.User.ID = 17);
or
var client = s.Linq<Client>().Where(x => x.User.ID = 17);
or
var client = s.CreateQuery("from Client as c where c.User.ID = 17").UniqueResult<Client>();
</code></pre>
<p>In all cases executes two identical queries. When I enable lazy load, the client is again loaded using two queries, however upon accessing a member, such as Person, only one additional query is executed.</p>
<p>Is this possibly a result of Fluent generating an improper mapping? Or SQL Server Express edition not being used properly by NHibernate?</p>
| <p>The problem was caused by another mapping I had declared. I had a class inheriting from Client which had an associated mapping. This is what caused NHibernate to query twice. I noticed this because when using Linq() it returned the subclass, not Client itself. This particular instance of inheritance and mapping was a design flaw on my part and was the root of the whole problem!</p>
|
My VB.NET Website Hangs For A Long Time Then Displays Nothing <p>Okay, this is a weird issue that I've been having with a recent project I'm undertaking.</p>
<p>Occasionally, my website will stop functioning and anytime an ASP page is accessed, the browser will hang for many minutes before bringing up a correctly formatted HTML page with nothing in the tag. It seems to happen whenever more than one person attempts to access an ASP page, but I'm not positive it's isolated to those conditions.</p>
<p>Let me emphasize that the issue does not arise when accessing directories/HTML pages/other files. Only ASP pages are the problem. I am using lunarpages as a host.</p>
<p>My question is: Does anyone have any prior experience with such an issue, and if so, what are some ways to mitigate it?</p>
<p>Thanks in advance - let me know if I can provide any more pertinent information.</p>
| <p>It sounds like it may be an issue with your Web Server. Do you have the correct version of .Net installed? Is your Web Server setup to host Asp.Net?</p>
|
Implementing CAPTCHA after 50% of Article <p>We are planning to put large number of Business Research Reports and Articles from our intranet on to the Internet. However, we don't want others to copy the content and host it on their own.</p>
<p>I read about protection by CAPTCHA and was wondering if this is possible. Readers should be able to read 50% of the article for FREE after which a CAPTCHA should be entered to read the rest of the article [In this way we are making life little harder for those copycats] </p>
<p>Any pointers on how to implment this ? The content is in HTML and programming experience in Perl, PHP. Can hire others if required.</p>
<p>Aditionally, search engine will crawl half of the article and wondering if it will penalize the site for not being able to crawl the rest of the article since it won't be able to crack the CAPTCHA ?</p>
<p>Thanks.</p>
| <p>There's a really good Captcha service provided by Recaptcha - <a href="http://recaptcha.net/" rel="nofollow">http://recaptcha.net/</a></p>
<p>There is a PHP class that you can use to do all the hard work.</p>
<p>It's important to bear in mind that search engines aren't able to solve a Captcha and so they will only index the first half of the report. As long as this half contains largely the correct key words, it shouldn't cause a massive problem. Don't make the mistake of "detecting" a search engine and showing them different content to a normal user as the major search engines think that this is spamming.</p>
<p>An alternative solution would be to use a service like Copyscape (<a href="http://www.copyscape.com/" rel="nofollow">http://www.copyscape.com/</a>) to protect your content.</p>
|
Prevent windows from going into sleep when my program is running? <p>I have to stop windows from going into sleep when my program is running.</p>
<p>And I don't only want to prevent the sleep-timer, I also want to cancel the sleep-event if I press the sleep-button or in any other way actively tell the computer to sleep. Therefore SetThreadExecutionState is not enough.</p>
<p>Or...I don't actually have to prevent the sleep completely, only delay it 5-10sec to allow my program to finish a task.</p>
<p>(I know that this is bad program behavior but it's only for personal use.)</p>
| <p>I had a problem like this with a hardware device connected via usb. XP /Vista would sleep/hibernate right in the middle of ... Great you say, when it resumes it can just continue. If the hardware is still connected!!!
Users have the habit of pulling cables out whenever they feel like it. </p>
<p>You need to handle XP and Vista </p>
<p>Under XP trap the WM_POWERBROADCAST and look for the PBT_APMQUERYSUSPEND wparam.</p>
<pre><code> // See if bit 1 is set, this means that you can send a deny while we are busy
if (message.LParam & 0x1)
{
// send the deny message
return BROADCAST_QUERY_DENY;
} // if
else
{
return TRUE;
} // else
</code></pre>
<p>Under Vista use SetThreadExecutionState like this</p>
<pre><code>// try this for vista, it will fail on XP
if (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == NULL)
{
// try XP variant as well just to make sure
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
} // if
</code></pre>
<p>and when you app has finished set it back to normal</p>
<pre><code>// set state back to normal
SetThreadExecutionState(ES_CONTINUOUS);
</code></pre>
|
How to protect i18n bundle integrity in larger teams? <p>We use Subversion to manage our project files, including the seam managed message bundles which have the highest mutation rate of the whole project.</p>
<p>Ever so often a developer reads past a line during diff merge and accidentally reverts some changes, which usually slips through the testing process.</p>
<p>What practices have you adopted to ensure bundle integrity?</p>
| <p>You didn't mention how you find out who breaks bundle integrity. But I'm guessing you can tell. I would give these two punishments to the one who broke the build:</p>
<ul>
<li>Make tests to ensure that the reason for the break cannot happen again.</li>
<li>Build X additional number of tests. This makes them more familar with the code as well as increases your build's testability.</li>
</ul>
|
Matching parentheses in Visual Studios 2005 <p>When doing developement for linux, I have a file for vim that changes the colors of matching parentheses.</p>
<p>So for example, given the following line:
<pre><code>if( (foo / 12 == 4) && arr[i] == 2 ) {}</pre></code>
The parentheses that opened and closed the if statement could be red, the parentheses that hold the foo statement could be blue, the brackets that hold the array index could be green, and the curly-brackets would be light-brown.</p>
<p>Such a tool makes complex control-statements much easier to understand, and the days of manually looking to see what matched what are over. </p>
<p>Is there an option in VS 2005 for this sort of functionality? I'm not in a position to pay for any tools that offer such a thing, so I'd appreciate it if there's a built-in option or a free plugin. </p>
| <p>I don't know of something that exactly does that, but I'll draw your attention to the functionality that is built in. When you type a character that can match (such as a close-paren), it will briefly highlight the matching character. The key combination ctrl-] will take you between matching characters.</p>
|
strange linq to nhibernate issue, Invalid cast from 'System.Int32' <p>Calling Get in the following code works fine:</p>
<pre><code>public class ContractService : IContractService
{
private readonly IRepository<Contract> repository;
public ContractService(IRepository<Contract> repository)
{
this.repository = repository;
}
public Contract Get(int contractId)
{
return repository.Query().Where(x => x.Id == contractId).FirstOrDefault();
}
</code></pre>
<p>but when i do this:</p>
<pre><code>public class ContractService : CRUDService<Contract>, IContractService
{
public ContractService(IRepository<Contract> repository) : base(repository)
{
}
}
public class CRUDService<TEntity> : ICRUDService<TEntity> where TEntity : IEntity
{
protected readonly IRepository<TEntity> repository;
public CRUDService(IRepository<TEntity> repository)
{
this.repository = repository;
}
public TEntity Get(int id)
{
var entities = this.repository.Query().Where(s => s.Id == id);
return entities.FirstOrDefault();
}
</code></pre>
<p>"entities" inside the get method throws an exception when you iterate over it:</p>
<pre><code>Invalid cast from 'System.Int32' to 'TEntity' (where TEntity is the type name)
</code></pre>
<p>Anyone got any idea why?</p>
<p>Edit: here's what the different expressions look like:</p>
<p>In the generic version (top one), it seems to be trying to convert x for some reason, which must be because of the generics :s</p>
<pre><code>{value(NHibernate.Linq.Query`1[Contract]).Where(x => (Convert(x).Id = value(CRUDService`1+<>c__DisplayClass0[Contract]).Id)).FirstOrDefault()}
{value(NHibernate.Linq.Query`1[Contract]).Where(x => (x.Id = value(ContractService+<>c__DisplayClass2).Id)).FirstOrDefault()}
</code></pre>
<p>(namespaces omitted for clarity)</p>
<p>2nd Edit: It seems to be when it tries to convert between IEntity and the instance type (TEntity)</p>
<p>here is IEntity:</p>
<pre><code>public interface IEntity
{
int Id { get; }
}
</code></pre>
<p>3rd Edit: it seems to be the Convert(x) that causes the AssociationVisitor to not properly visit the expression tree and convert "Convert(x).Id"</p>
<p>4th Edit: And there we go, someones already found the bug <a href="https://nhibernate.jira.com/browse/NHLQ-11" rel="nofollow">https://nhibernate.jira.com/browse/NHLQ-11</a>!</p>
<p>Thanks</p>
<p>Andrew</p>
| <p>I believe the problem is that Linq/NHibernate is trying to map IEntity.Id to a table column instead of TEntity.Id. I had this problem with a LinqToSql repository implementation. The way around it was to use an expression like this:</p>
<pre><code>private static Expression<Func<TEntity, bool>> GetFindExpression(string propertyName, object value)
{
ParameterExpression parameterExpression = Expression.Parameter(typeof (TEntity), "id");
MemberExpression propertyExpression = Expression.Property(parameterExpression, propertyName);
Expression bodyExpression = Expression.Equal(propertyExpression, Expression.Constant(value));
return Expression.Lambda<Func<TEntity, bool>>(bodyExpression, parameterExpression);
}
</code></pre>
<p>So this would change Get(id) to:</p>
<pre><code>public TEntity Get(int id)
{
var entities = Query.Where(GetFindExpression("Id", id));
return entities.FirstOrDefault();
}
</code></pre>
<p><strong>Update:</strong></p>
<p>If you don't want to deal with expressions (they can be tricky!), you could use the Dynamic LINQ library as described by Scott Guthrie here:
<a href="http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx" rel="nofollow">http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx</a></p>
<p>That would change Get(id) to:</p>
<pre><code>public TEntity Get(int id)
{
var entities = Query.Where("Id = @0", id);
return entities.FirstOrDefault();
}
</code></pre>
|
Calling synchronous methods asynchronously on the UI thread <p>I have written a class that checks a POP3 account and I'd like it to execute on a thread other than the UI thread.</p>
<p>To do this, I've chosen the asynchronous route.</p>
<p>In order to get the result from pop3delegate.BeginInvoke(null,null) I need to call EndInvoke but doing this in the UI thread blocks rendering the UI unusable.</p>
<p>I could use the IAsyncResult object and check the IsComplete property, but this involves putting in a loop which checks and this in turn locks up the UI.</p>
<p>What I'm looking for is a way to get a percentage complete or some sort of a status from the POP3 class, which in turn updates the UI and also allows the UI to be usable to do other tasks. I'll also need to call the EndInvoke method at some point in order to catch any exceptions thrown on the worker thread.</p>
<p>Any suggestions?</p>
| <p>Try using BackgroundWorker class, its was designed to do exactly what you need.</p>
<p>Example and more details on msdn: <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx</a></p>
|
multiple processes writing to a single log file <p>This is intended to be a lightweight generic solution, although the problem is currently with a IIS CGI application that needs to log the timeline of events (second resolution) for troubleshooting a situation where a later request ends up in the MySQL database BEFORE the earlier request!</p>
<p>So it boils down to a logging debug statements in a single text file.</p>
<p>I could write a service that manages a queue as suggested in this thread:
<a href="http://stackoverflow.com/questions/119548/problem-in-writing-to-single-file-in-web-service-in-net">Problem in writing to single file in Web service in .NET</a>
but deploying the service on each machine is a pain</p>
<p>or I could use a global mutex, but this would require each instance to open and close the file for each write</p>
<p>or I could use a database which would handle this for me, but it doesnt make sense to use a database like MySQL to try to trouble shoot a timeline issue with itself. SQLite is another possability, but this thread</p>
<p><a href="http://www.perlmonks.org/?node_id=672403" rel="nofollow">http://www.perlmonks.org/?node_id=672403</a></p>
<p>Suggests that it is not a good choice either.</p>
<p>I am really looking for a simple approach, something as blunt as writing to individual files for each process and consolidating them accasionally with a scheduled app. I do not want to over engineer this, nor spend a week implementing it. It is only needed occassionally.</p>
<p>Suggestions?</p>
| <p>Try the simplest solution first - each write to the log opens and closes the file. If you experience problems with this, which you probably won't , look for another solution.</p>
|
jQuery: Selecting an element in inside an already selected element <p>For example:</p>
<pre><code>$("table tr").click( function(event)
{
//Say, here i want get the data of td element where its class name="special"
});
</code></pre>
<p>Is there any way I can select a element while in the click event, a element under the attached element above ( $("table tr") )?</p>
| <p>In this specific case, you can do this:</p>
<pre><code>$("table tr").click( function(event)
{
$(this).children('td.special').whatEverYouNeed();
});
</code></pre>
<p>Generally speaking, you need to use <code>find()</code>:</p>
<pre><code>$("table tr").click( function(event)
{
$(this).find('td.special').whatEverYouNeed();
});
</code></pre>
|
Variable/Type declaration private by default <p>Is there a way to make the default access modifier public for variable/method/class declarations?</p>
<p>I think by default, class declarations are private yes?</p>
| <p>You can't change the defaults. They default to the most restrictive.</p>
<p>The default accessibility (for the type) for a top-level type is <code>internal</code>.
The default accessibility (for the type) for a nested type is <code>private</code>.
The default accessibility for members is private.</p>
<p>The only time it isn't the most restrictive is for the explicit part of an automatically implemented property, where you can make it <em>more</em> restrictive by adding a modifier:</p>
<pre><code>public int Foo {get;private set;}
</code></pre>
|
soap4r custom headers <p>I've been working with soap4r and trying to use the SOAP::Header::SimpleHandler, I'm trying to get it to put a custom header on the outgoing message, but I can't work out how to get it to include attributes rather than as subelements:</p>
<pre><code> class ServiceContext < SOAP::Header::SimpleHandler
NAMESPACE = "http://context.core.datamodel.fs.documentum.emc.com/"
def initialize()
super(XSD::QName.new(NAMESPACE, 'ServiceContext'))
XSD::QName.new(nil, "Identities")
end
def on_simple_outbound
username = "username"
password = "password"
docbase = "Test"
return {"Identities" => {"Username" => username, "Password" => password, "Docbase" => docbase}}
end
end
</code></pre>
<p>which returns:</p>
<pre><code> <n1:ServiceContext xmlns:n1="http://context.core.datamodel.fs.documentum.emc.com/"
env:mustUnderstand="0">
<n1:Identities>
<n1:Username>username</n1:Username>
<n1:Password>password</n1:Password>
<n1:Docbase>Test</n1:Docbase>
</n1:Identities>
</n1:ServiceContext>
</code></pre>
<p>what I need it to return is the following:</p>
<pre><code> <ServiceContext xmlns="http://context.core.datamodel.fs.documentum.emc.com/">
<Identities xsi:type="RepositoryIdentity" userName="_USER_" password="_PWD_" repositoryName="_DOCBASE_" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>
</ServiceContext>
</code></pre>
<p>Any help is greatly appreciated.</p>
| <p>soap4r is not very pretty. I poked around the rdocs abit and it looks like the simplest way to fix your problem would be to have <code>on_simple_outbound</code> return the string representation of the element you want to create.</p>
<p>so instead of</p>
<pre><code>return {"Identities" => {"Username" => username, "Password" => password, "Docbase" => docbase}}
</code></pre>
<p>try</p>
<pre><code>%Q(<Identities xsi:type="RepositoryIdentity" userName="#{user}" password="#{password}" repositoryName="#{docbase}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/>)
</code></pre>
<p>using something like builder, you could make it look more rubyish, but try that.</p>
<p>The other option would be to investigate newer soap libraries. <a href="http://github.com/troelskn/handsoap/" rel="nofollow">handsoap</a> looks interesting.</p>
|
How do I autosize a blockui dialog to the available visible area with JQuery? <p>I need to resize a div shown as a message in blockUI so that it fills the visible screen area less some hardcoded fudge factor (so width - 100 say). The premise is that I can show a smaller image on the screen but if the user needs an enlarged image then I just show them block ui dialog sized to their screen.</p>
<p>The image is dynamically generated so can be sized to whatever dimensions are passed to it from the application.</p>
<p>I've looked and have only found code for centering a div. I'm working on this so if I find an answer I'll post it here (assuming it doesn't replicate anyone elses answers!)</p>
<p>Here's a very simple html snippet for the calling markup:</p>
<pre><code><div>
<img src="someurl" class="image" height="280px" width="452px" alt="" />
</div>
<div style="text-align: right;">
<a href="#viewpopup" id="viewpopup">View larger map</a>
</div>
</code></pre>
<p>And here's the popup markup</p>
<pre><code><div id="popup">
<div class="titlebar">
<div class="title left">Map details</div>
<div class="closebuttons right"><a class="close">x</a></div>
<div class="clearer"></div>
</div>
<div class="popupcontent">
<!-- auto append content here -->
</div>
<div class="buttonbar">
<a class="close">Close</a>
</div>
</div>
</code></pre>
<p>I'm using JQuery, here's the current code I have:</p>
<pre><code>var popup = $("#popup");
var popupcontent = popup.children(".popupcontent");
var image = $(".image");
$(document).ready(function(){
$("#viewpopup").click(function(){
// Fudged indent on the top left corner
var top = 20;
var left = 20;
// Dynamically set the contents
// popupcontent.empty();
// popupcontent.append();
$.blockUI({ message: popup, css : { border : 'none', height: 'auto', 'cursor': 'auto', 'width': 'auto', 'top': top, 'left' : left } });
});
$(".close").live("click",function(){
$.unblockUI();
});
});
</code></pre>
<p>I've also got to figure out how to set the popupcontent height to auto fill the currently
available space (I'm using ems in my css) but I'm unsure if that's a separate question :).</p>
<p>Thanks :)</p>
| <p>I've got it working now. I've used the window width and height methods as described above.
The code assumes some fudge numbers purely to make it work :).</p>
<p>Note that I'm clamping the maximum width and height. Something that I'm going to move to my dynamic image generation so I don't consume too many resources.</p>
<p>Also note I've not included the code to pass the new dimensions to the dynamic image app, I figured that would be custom to each individual implementation.</p>
<pre><code> $("#viewmap").click(function(){
var width = $(window).width();
if(width < 200)
width = 200;
if(width > 1200)
width = 1200;
var height = $(window).height();
if(height < 200)
height = 200;
if(height > 800)
height = 800;
var popupwidth = $(window).width() - 100;
var popupheight = $(window).height() - 100;
var top = 20;
var left = (width - popupwidth) / 2 ;
popup.css("width", popupwidth);
popup.css("height", popupheight);
popupcontent.css("height", popupheight - 40) ;
popupcontent.empty();
popupcontent.append("<img src=\"someurl\" width=\""+ popupwidth + "\" height=\""+ (popupheight - 40) +"\" />");
$.blockUI({ message: popup, css : { border : 'none', height: 'auto', 'cursor': 'auto', 'width': 'auto', 'top': top, 'left' : left } });
});
</code></pre>
|
When to use database views and when not? <p>This question is about database views, <strong>not</strong> materialized-views.</p>
<p>Pros:</p>
<ul>
<li>Query simplification.</li>
<li>Avoid repeat the same joins on multiples queries.</li>
<li>Avoid magic numbers.</li>
</ul>
<p>Cons:</p>
<ul>
<li>Hiding real queries (may be you are repeating joins).</li>
</ul>
<p>What else?</p>
| <p>Pros:
Allows you to change the underlying data structures without affecting the queries applications are using (as long as your view can hide the data structures)</p>
|
How to add several dependent records with LINQ2SQL <p>I have two tables. One table contains comments on posts, another contains commenter information like nickname, site, etc..
There is FK relations betwin two tables
Comment.CommenterId -> Commenter.Id
Whenever user posts a comment I need to add comment and commenter at the same time.
The problem is that I don't know what would be Commenter.Id after addition to assign it to Comment.CommenterId before addition.</p>
<p>What is the best practice to do such inserts?</p>
| <p>you can do this like so:</p>
<pre><code>Comment comment = new Comment(); // your constructor here
Commenter commenter = new Commenter(); // use your constructor;
comment.Commenter = commenter; // linq2sql creates this property for you.
datacontext.Commenter.InsertOnSubmit(commenter);
datacontext.Comment.InsertOnSubmit(comment);
datacontext.SubmitChanges();
</code></pre>
<p>this code has not been tested here in any way, so there may be syntax or other errors, but this is basically what you would need to do.</p>
|
What does "() =>" mean in C#? <p>Came across the following line in the Composite Application Guidelines.</p>
<p>I know the <strong>=></strong> is a lambda but what does the <strong>()</strong> mean?</p>
<p>What are some other examples of this?</p>
<p>What is it called so I can search for it?</p>
<pre><code>this.regionViewRegistry.RegisterViewWithRegion(RegionNames.SelectionRegion
, () => this.container.Resolve<EmployeesListPresenter>().View);
</code></pre>
| <p>It's a lambda expression that takes 0 arguments</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx">http://msdn.microsoft.com/en-us/library/bb397687.aspx</a></p>
|
Prevent form from stealing focus <p>When I run my VB.NET Winforms app I do not want it to steal the focus from the other open apps. FYI, my app is started from the command line but that shouldn't make a difference. I've seen question <a href="http://stackoverflow.com/questions/577076/topmost-window-form-steal-focus">577076</a> but that doesn't seem to work.</p>
<p>What is the best way to do this?</p>
| <p>Here is what I did to get this working:</p>
<p>I added the following code to my Form1.vb file:</p>
<pre><code>Protected Overloads Overrides ReadOnly Property ShowWithoutActivation() As Boolean
Get
Return True
End Get
End Property
</code></pre>
<p>But still no success. </p>
<p>Then I unchecked the Enable Application Framework checkbox on the Application tab of the project properties.</p>
<p>Success!!!</p>
|
Why does a report throw an error when the corresponding query doesn't? <p>I have to use a Microsoft Access application. (At least until I've got time to rewrite it in another language.)</p>
<p>I've got a report that throws the error "Syntax error in PARAMETER clause."</p>
<p>At the moment the SQL looks like this:</p>
<pre><code>PARAMETERS [Test] Text ( 255 );
SELECT â¦
</code></pre>
<p>If I remove the PARAMETERS-line the problem vanishes.</p>
<p>Strange is, that if I open the query in the Datasheet view, the program displays the dialog. Only if I try to open the report it displays this message.</p>
<p>Any clue what's wrong?</p>
| <p>Could this be a bug that's fixed by MS Office Service Pack 1?</p>
<p><a href="http://support.microsoft.com/kb/942378" rel="nofollow">http://support.microsoft.com/kb/942378</a></p>
<p>About a third the way down that document:</p>
<p><em>Error message when you execute a query that contains parameters in Access 2007: "Syntax error in Parameter clause"
In Access 2007, you receive the following error message when you try to execute a query that contains parameters:</em></p>
|
Errors on beginner bash script <p>could u help me out?
I run this on cygwin as ./test.sh and I get unexpected end of file on line 51.
Any thoughts?</p>
<p>Thx in advance</p>
<p>LAST EDIT: final version 'runnin on CygWin, the problem was with the line break, CrLf instead Lf.</p>
<pre><code>#!/bin/sh
##################################################
## USAGE
##################################################
if [ $# -ne 1 ]; then
echo "1>Use Extractor: $0 <MODO DE OPERACAO>"
echo "2>Use Extractor: $0 <MODO DE OPERACAO> <DATA INICIAL> <DATA FINAL>"
exit 127
else
if [ $1 -lt 0 ]; then
if [ $1 -gt 1 ]; then
echo "2>Use Extractor: $0 <MODO DE OPERACAO> <DATA INICIAL> <DATA FINAL>"
exit 127
fi
fi
fi
##################################################
## VARS
##################################################
##########################################
## AUX
##########################################
set java_cmd=""
set java_cmd_emergencial=""
set java_cp=""
##########################################
## JAR
##########################################
set db_user=""
set db_pwd=""
set conn_string=""
set work_dir=""
set output_dir=""
##################################################
## PARAMETROS
##################################################
set mode=$1
set data_ini=""
set data_fim=""
if [ $# -eq 3 ]; then
set data_ini = $2
set data_fim = $3
fi
##################################################
## CHAMADA DO JAR
##################################################
java "$java_cp" "$java_cmd" "$mode" "$db_user" "$db_pwd" "$conn_string" "$work_dir" "$output_dir"
</code></pre>
| <p>"set" isn't bash syntax. Instead of "set foo = bar", you want "foo=bar".</p>
<p>Note: I wrote the corrected form without spaces for a reason. It <em>has</em> to be written that way. Your updated question is still wrong.</p>
|
How to make schtasks work after the user's password has changed? <p>On Windows machines, <a href="http://support.microsoft.com/kb/308569" rel="nofollow">schtasks</a> is a utility similar to cron for scheduling jobs to run on a regular basis.</p>
<p>Problem is, when you define a schtask, you must specify the userid <em>and</em> password of the account to run the job.</p>
<p>Then later, when the user changes his password, that schtask will no longer work. It must be deleted and rescheduled with the <em>new</em> password.</p>
<p>So, how can I setup a scheduled job (via schtasks, at, whatever) that's immune to password changes? </p>
| <p>This doesn't <em>quite</em> answer your question, but a common workaround is to create a user (with appropriate privileges) and use that account solely for executing scheduled tasks.</p>
<p>As the user account is created with a non-expiring password, the sysadmin who creates it should choose an appropriately strong password.</p>
|
Configuring Windows DNS resolver cache <p>Note that I'm talking about the client DNS resolver cache. This message is not concerned with the Windows DNS Server.</p>
<p>I have a C# program that does a lot of DNS resolutions. Because the HTTPWebRequest component won't let me change the Host header, I can't create my own internal DNS cache. So I have to depend on the Windows DNS cache, which doesn't appear amenable to change.</p>
<p>There's a reasonably good <a href="http://technet2.microsoft.com/windowsserver/en/library/94d21089-411b-4bce-a823-49a77a46e7661033.mspx?mfr=true">TechNet article</a> about the DNS cache Registry settings in Windows Server 2003, but I haven't been able to prove that setting them does anything. All the other pages I found through a Google search either reference that page, or paraphrase it, sometimes incorrectly.</p>
<p>Windows' ipconfig command has a /displaydns switch that will output the contents of the cache. To my knowledge, that's the only way to determine the size of the DNS cache. In my experiments on a 32 bit Windows XP box with 2 GB of memory, no matter what I set the DNS cache registry values to, I always end up with between 30 and 40 items in the cache--even after doing thousands of DNS resolutions. On my 64-bit Windows 2008 machine with 16 GB of memory, I always get between 270 and 300 items in the cache.</p>
<p>I'm stumped. I don't know what the answer is, but I figure one of the following is the case:</p>
<ol>
<li>It's not possible to change the size of the DNS resolver cache.</li>
<li>It is possible, but the documentation is wrong.</li>
<li>The documentation is correct as far as it goes, but itâs incomplete.</li>
<li>The documentation is correct and complete, but Iâm too dumb to make sense of it.</li>
<li>The documented registry entries actually changed the size of the cache, but ipconfig isnât showing me all the entries that are in the cache. </li>
</ol>
<p>Can anybody tell me if it's possible to configure the size of the DNS resolver cache in Windows XP, Vista, or Server 2008?</p>
| <p>With these settings, after just a few minutes on the web, I am seeing 1517 cached entries:</p>
<p>REGEDIT4 </p>
<p>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Dnscache\Parameters]<br>
"QueryIpMatching"=dword:00000001<br>
"NegativeCacheTime"=dword:00000000<br>
"NegativeSOACacheTime"=dword:00000000<br>
"CacheHashTableBucketSize"=dword:00000001<br>
"CacheHashTableSize"=dword:00000180<br>
"MaxCacheEntryTtlLimit"=dword:00000e10<br>
"MaxSOACacheEntryTtlLimit"=dword:0000012c </p>
<p>[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]<br>
"QueryIpMatching"=dword:00000001 </p>
|
Different style on buttons in messagebox in different projects <p>I have a problem with the style of the button in a messagebox.
If I call the following line of code in a current project the button get one type of visual apperance/style. And If I create a new VB.NET Windows Application project it gets a standard Windows apperance/style.</p>
<pre><code>Windows.Forms.MessageBox.Show("Yaay", "Yaay!", Windows.Forms.MessageBoxButtons.OK)
</code></pre>
<p>See the difference between the buttons below.
I suspect they inherit the visual apperance from it's parent or maybe from some project settings. But I have not been able to find out from where.</p>
<p>Both projects are created in VB.NET 2.0, and both have same System.Windows.Forms - dll as reference (c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\System.Windows.Forms.dll).</p>
<p>
Screenshot can be found <a href="http://www.freeimagehosting.net/uploads/2a956b0675.jpg" rel="nofollow">here</a>.</p>
<p>Thanx in advance for your help!</p>
| <p>I cannot see the image from where I am so I'm not sure if this will help you.</p>
<p>Open the Project Properties for each solution and look at the Application tab.</p>
<p>Is the "Enable Applicaton Framework" item ticked? And if so, is the "Enable XP Visual Styles" item also ticked?</p>
<p>That may the difference in the two solutions.</p>
|
Regex replace consecutive non-alpha chars with single char <p>I want to replace all non-alpha characters in a string with a plus '+' sign, but making sure that a group of more than one non-alpha chars is only replaced by one plus sign.</p>
<p>I had thought the following might work but apparently not:</p>
<pre><code>System.Text.RegularExpressions.Regex.Replace(name, @"[^\w]*?", "+")
</code></pre>
| <p>Try System.Text.RegularExpressions.Regex.Replace(name, @"\W+", "+")</p>
<p>For this: "sasa-==[]<em>&^asdsa2435" matches -==[]</em>&^</p>
|
.net HttpCookie class / session cookie questions <p>I am interested on how to make a regular <code>HttpCookie</code> object into a cookie that expires at the end of a session. I am not interested in someone <code>showing me HttpContext.Session</code>. How does a session cookie look in the response headers compared to a normal cookie? How can I modify a <code>HttpCookie</code> to expire at the end of a session? Thanks!</p>
| <p>A session cookie is just a cookie that doesn't have any expiration date set.</p>
<pre><code>Response.Cookies.Add(new HttpCookie("name", "value"));
</code></pre>
<p>or:</p>
<pre><code>Response.Cookies["name"] = "value";
</code></pre>
|
Store pointers to member function in the map <p>I'd like to map string to an instance member functions, and store each mapping in the map.</p>
<p>What is the clean way of doing something like that?</p>
<pre><code>class MyClass
{
//........
virtual double GetX();
virtual double GetSomethingElse();
virtual double GetT();
virtual double GetRR();
//........
};
class Processor
{
private:
typedef double (MyClass::*MemFuncGetter)();
static map<std::string, MemFuncGetter> descrToFuncMap;
public:
static void Initialize();
void Process(Myclass m, string);
};
void Processor::Initialize()
{
descrToFuncMap["X"]=&MyClass::GetX;
descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse;
descrToFuncMap["RR"]=&MyClass::GetRR;
descrToFuncMap["T"]=&MyClass::GetT;
};
void Processor::Process(MyClass ms, const std::string& key)
{
map<std::string, Getter>::iterator found=descrToFuncMap.find(key);
if(found!=descrToFuncMap.end())
{
MemFuncGetter memFunc=found->second;
double dResult=(ms).*memFunc();
std::cout<<"Command="<<key<<", and result="<<result<<std::end;
}
}
</code></pre>
<p>let me know if you see a problem with this approach and what are common idioms for that?</p>
<p><strong>Perhaps, I should use if-else-if statement chain, given that I have a limited number of member functions, instead of a confusing map of func pointers</strong></p>
<p>BTW, I found some of the useful info here in the <a href="http://www.parashift.com/c%2B%2B-faq-lite/pointers-to-members.html">c++-faq-lite</a></p>
| <p>Looks fine to me, but for the fact that <code>descrToFuncMap</code> needs to be declared <code>static</code> if you intend to initialise it from inside the static function <code>Initialize()</code>.</p>
<p>If you want to make sure that <code>Initialize()</code> gets called, and gets called just once, you can use the Singleton pattern. Basically, if you aren't doing multithreading, that just means wrapping <code>descrToFuncMap</code> inside its own class (called say <code>FuncMap</code>) with a private constructor that calls <code>Initialize()</code>. Then you add a <code>static</code> local variable of type <code>FuncMap</code> to <code>Processor::Process()</code> -- because the variable is <code>static</code>, it persists and is only initialised once.</p>
<p>Example code (I now realise that <code>friend</code> isn't really necessary here):</p>
<pre><code>class Processor {
private:
typedef double (MyClass::*MemFuncGetter)();
class FuncMap {
public:
FuncMap() {
descrToFuncMap["X"]=&MyClass::GetX;
descrToFuncMap["SomethingElse"]=&MyClass::GetSomethingElse;
descrToFuncMap["RR"]=&MyClass::GetRR;
descrToFuncMap["T"]=&MyClass::GetT;
}
// Of course you could encapsulate this, but its hardly worth
// the bother since the whole class is private anyway.
map<std::string, MemFuncGetter> descrToFuncMap;
};
public:
void Process(Myclass m, string);
};
void Processor::Process(MyClass ms, const std::string& key) {
static FuncMap fm; // Only gets initialised on first call
map<std::string, Getter>::iterator found=fm.descrToFuncMap.find(key);
if(found!=fm.descrToFuncMap.end()) {
MemFuncGetter memFunc=found->second;
double dResult=(ms).*memFunc();
std::cout<<"Command="<<key<<", and result="<<result<<std::end;
}
}
</code></pre>
<p>This is not the "true" Singleton pattern as different functions could create their own, separate instances of <code>FuncMap</code>, but it's enough for what you need. For "true" Singleton, you would declare <code>FuncMap</code>'s constructor private and add a static method, say <code>getInstance()</code>, which defined the one-and-only instance as a <code>static</code> variable and returned a reference to that. <code>Processor::Process()</code> would then use this with</p>
<pre><code>FuncMap& fm = FuncMap::getInstance();
</code></pre>
|
Pure virtual destructor in C++ <p>Is it wrong to write:</p>
<pre><code>class A {
public:
virtual ~A() = 0;
};
</code></pre>
<p>for an abstract base class?</p>
<p>At least that compiles in MSVC... Will it crash at run time?</p>
| <p>Yes. You also need to implement the destructor:</p>
<pre><code>class A {
public:
virtual ~A() = 0;
};
inline A::~A() { }
</code></pre>
<p>should suffice.</p>
<p>And since this got a down vote, I should clarify: If you derive anything from A and then try to delete or destroy it, <code>A</code>'s destructor will eventually be called. Since it is pure and doesn't have an implementation, undefined behavior will ensue. On one popular platform, that will invoke the purecall handler and crash.</p>
<p>Edit: fixing the declaration to be more conformant, compiled with <a href="http://www.comeaucomputing.com/tryitout/">http://www.comeaucomputing.com/tryitout/</a></p>
|
Bash history re-runs: possible command to avoid using !bang!? <p><strong>Scenario:</strong></p>
<p>You are doing your daily Bash shell stuff. You want to run a previous command so you type:</p>
<pre><code>history | grep foocommand
</code></pre>
<p>Then you get a list of all the <code>foocommand</code> stuff you did for however long your history has kept track, in a list like so:</p>
<pre><code> 585 foocommand --baz --bleet
750 foocommand | grep quux
987 history grep | foocommand
</code></pre>
<p>You decide you want to run command 585, so you type</p>
<pre><code> !585
</code></pre>
<p><strong>Question:</strong> Just for curiosity, is there a way to take that final step out of the equation and still get the expected outcome? It would be nice if there were a way to say:</p>
<pre><code> "grep through history and automatically run the first item on the list"
</code></pre>
<p>or</p>
<pre><code>"grep through history and let me choose which item to run using the arrow keys"
</code></pre>
| <p>Press <code>^r</code> (that's <code>CTLR-r</code>), type <code>foocommand</code> press Enter ;)
That will search history and show the latest matching entry</p>
|
How big should a language vocabulary be? <p>I started looking at the upcoming <a href="http://en.wikipedia.org/wiki/C%2B%2B0x" rel="nofollow">C++0x specification</a> today, and I started thinking on what is the right size for a language vocabulary. Initially, it struck me as very annoying that new keywords were introduced. At some rough level, the number of keywords in a language is, I think, an estimate of its complexity. That is, in the case of C++, adding new constructs would make it even harder to master the language. Thats one reason why the K&R book is so much smaller that the C++ equivalent.</p>
<p>After that, I thought about natural languages, whose vocabulary has been shown to grow linearly with time, regardless of the language (*). The only exception is, of course, <a href="http://en.wikipedia.org/wiki/Newspeak" rel="nofollow">Newspeak</a>, which says a lot. The vocabulary size in this case is related to the expressive power the language.</p>
<p>In programming languages, however, you can have very expressive languages with a small vocabulary size (ie, Lisp).</p>
<p><strong>So, to phrase this is a question, what, in your opinion, should a language vocabulary be - big and verbose or small and concise?</strong></p>
| <blockquote>
<p>How big should a language vocabulary
be?</p>
</blockquote>
<p><strong>42.</strong></p>
|
Can I alter a column in an sqlite table to AUTOINCREMENT after creation? <p>Can I make a field <code>AUTOINCREMENT</code> after made a table? For example, if you create a table like this:</p>
<pre><code>create table person(id integer primary key, name text);
</code></pre>
<p>Then later on realise it needs to auto increment. How do I fix it, ie in MySQL you can do:</p>
<pre><code>alter table person modify column id integer auto_increment
</code></pre>
<p>Is table creation the only opportunity to make a column <code>AUTOINCREMENT</code>?</p>
| <p>You can dump the content to a new table:</p>
<pre><code>CREATE TABLE failed_banks_id (id integer primary key autoincrement, name text, city text, state text, zip integer, acquired_by text, close_date date, updated_date date);
INSERT INTO failed_banks_id(name, city, state, zip, acquired_by,close_date, updated_date)
SELECT name, city, state, zip, acquired_by,close_date, updated_date
FROM failed_banks;
</code></pre>
<p>And rename the table:</p>
<pre><code>DROP TABLE failed_banks;
ALTER TABLE failed_banks_id RENAME TO failed_banks;
</code></pre>
|
SQL Reporting Services 2005 - How to get current date as a ReportParameter <p>I have some working reports that must be deployed on SSRS.
One more customization that I want to be added is to automatically select the FromDate as today - 1 month, and ToDate as today.</p>
<p>Specifically, I want to replace the fragment bellow with a piece that accomplish the requirements above:</p>
<pre><code> <ReportParameter Name="FromDate">
<DataType>String</DataType>
<DefaultValue>
<Values>
<Value>[Date].&amp;[2008-09-26T00:00:00]</Value>
</Values>
</DefaultValue>
<Prompt>From Date</Prompt>
<ValidValues>
<DataSetReference>
<DataSetName>FromDate2</DataSetName>
<ValueField>ParameterValue</ValueField>
<LabelField>ParameterCaption</LabelField>
</DataSetReference>
</ValidValues>
</ReportParameter>
<ReportParameter Name="ToDate">
<DataType>String</DataType>
<Prompt>To Date</Prompt>
<ValidValues>
<DataSetReference>
<DataSetName>ToDate</DataSetName>
<ValueField>ParameterValue</ValueField>
<LabelField>ParameterCaption</LabelField>
</DataSetReference>
</ValidValues>
</ReportParameter>
</code></pre>
<p>Thanks in advance. </p>
| <p>Replace the hard-coded</p>
<pre><code>[Date].&amp;[2008-09-26T00:00:00]
</code></pre>
<p>to formula</p>
<pre><code>=DateAdd("m", -1, Now)
</code></pre>
<p>For "ToDate", just pass a formula that returns current date</p>
<pre><code>=Now
</code></pre>
<p>Now the result looks something like this.</p>
<pre><code><ReportParameters>
<ReportParameter Name="FromDate">
<DataType>DateTime</DataType>
<DefaultValue>
<Values>
<Value>=DateAdd("m", -1, Now)</Value>
</Values>
</DefaultValue>
<AllowBlank>true</AllowBlank>
<Prompt>FromDate</Prompt>
</ReportParameter>
<ReportParameter Name="ToDate">
<DataType>DateTime</DataType>
<DefaultValue>
<Values>
<Value>=Now</Value>
</Values>
</DefaultValue>
<AllowBlank>true</AllowBlank>
<Prompt>ToDate</Prompt>
</ReportParameter>
</ReportParameters>
</code></pre>
<p><strong><em>[UPDATE]</em></strong><br />
It looks like I have forgotten to paste <code><ReportParameters></code> correctly for <em>ToDate</em>; it's updated.
Above RDL was generated by configuring <em>Report Parameter</em>.
This is how I have configured date in GUI.</p>
<ul>
<li><p>FromDate:<br />
<img src="http://farm4.static.flickr.com/3614/3346000613%5F483516b4d3.jpg" alt="alt text" /></p></li>
<li><p>ToDate: <br />
<img src="http://farm4.static.flickr.com/3363/3346000617%5Fb85cf206ff.jpg" alt="alt text" /></p></li>
</ul>
|
What are Splay tree, Red-black tree, AVL tree, B-tree and T-tree? <p>What are Splay tree, Red-black tree, AVL tree, B-tree and T-tree?</p>
<p>I'm looking for good implementations.</p>
| <p>These are all data structures used for quickly searching binary data. Many are used by different data management systems.</p>
<p>They differ in their approach for storage of data. I'd recommend reading up on each.</p>
<p>Splay: <a href="http://en.wikipedia.org/wiki/Splay%5Ftree">http://en.wikipedia.org/wiki/Splay_tree</a></p>
<p>Red-Black: <a href="http://en.wikipedia.org/wiki/Red-black%5Ftree">http://en.wikipedia.org/wiki/Red-black_tree</a></p>
<p>AVL: <a href="http://en.wikipedia.org/wiki/Avl%5Ftree">http://en.wikipedia.org/wiki/Avl_tree</a></p>
<p>B-Tree: <a href="http://en.wikipedia.org/wiki/B-Tree">http://en.wikipedia.org/wiki/B-Tree</a></p>
<p>T-Tree: <a href="http://en.wikipedia.org/wiki/T-tree">http://en.wikipedia.org/wiki/T-tree</a></p>
|
How to code in the unix spirit? (small single task tools) <p>I have written a little script which retrieves pictures and movies from my camera and renames them based on their date and then copies them on my harddrive, managing conflicts automatically (same name? same size? same md5?)<br />
Works pretty well.</p>
<p>But this is ONE script.<br />
From time to time I need to check if a picture is already hidden somewhere in a volume, so I'd like to apply the "conflict manager" only. I guess if I had properly followed the unix spirit of tiny single-task tools, I could do that.</p>
<p>What are the best resources, best practices and your experience on the subject?</p>
<p>Thank you.</p>
<p>Edit : Although I'd love to read unix books and have a deep understanding of the subject, I am looking for the Great Principles first. Plus I tend to limit myself to online resources.</p>
| <p>I would look at the book called The <a href="http://rads.stackoverflow.com/amzn/click/0131429019" rel="nofollow">Art of Unix Programming</a>. </p>
|
"Failed to enable constraints" Error keeps cropping up (seemingly randomly) in my ASP.Net project <p>I have a weird problem where the "Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints." error sometimes pops up when I am trying to build my project.</p>
<p>The line in question throwing the error was <strong>auto-generated code</strong> in the designer file for the dataset. To find out the offending table, I used the following code:</p>
<pre><code> Try
Me.Adapter.Fill(dataTable) <--Breakpoint here on the offending line
Catch ex As Exception
For Each TRow As DataRow In dataTable.Rows
If TRow.HasErrors Then
Trace.Write(TRow.RowError)
End If
Next
End Try
</code></pre>
<p>Funnily enough, as soon as I run the project after putting in the above code and breakpoint, the error disappears. I assume this has something to do with the code being regenerated. All data is presented successfully, and the project compiles without errors.</p>
<p>However, this has happened often enough for me to frustrate me. Anybody know what might be causing the error and how I can isolate it?</p>
| <p>What unique constraint are you placing on the datatable and have you verified that the data your passing in doesn't have any duplicates? If this is coming from a shared database perhaps someone else is modifying the data which could be causing the randomness.</p>
<h1>Edit</h1>
<p>If that code is exactly as what you have (And forgive me my vb.net is not as strong as my C#). Wouldn't it swallow the exception? In C# we need to rethrow the error.</p>
<p>Add a Trace.Write() right before you go into your for loop.</p>
|
Is Regular Expression usage in Actionscript 3 processor intensive? <p>I was curious of just how much stress AS3 Regular Expression testing can impose on the end-user's pc. Is this something that should be used in moderation, or can most computers handle the exhaustive use of it?</p>
| <p>Only in pathological cases. In practice you never have to worry about it. Regular expressions are very efficient.</p>
<p>For example, many regular expression engines have serious performance problems failing to match a string of 'a's not ending with b with this type of expression.</p>
<pre><code>/a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*a*[b]/
</code></pre>
<p>Testing will quickly identify odd edge cases like this one. Otherwise, just use common sense like not creating multiple RegExp objects if you repeatedly check the same pattern.</p>
|
I have a legacy C++ project that uses motif for GUI. I want to create a Visual Studio solution of this project. Is this possible? <p>I have a legacy C++ project that uses motif for GUI. I want to create a Visual Studio solution of this project. So that I can build/run/debug from Visual studio. Currently I am on a windows box. I ssh into a Unix box and use cc to build and dbx to debug. When I run the application I change my display to the windows box and use xming for the xwindows display.</p>
<p>Is it even possible to build/run/debug from Visual Studio with this setup?</p>
<p>TIA</p>
| <p>I'm not aware of a Motif implementation for Windows and I would expect that to be quite hard to do, given that Motif has been intimately tied to X-Windows for decades.</p>
<p>I assume that you want to use Visual Studio as it is a friendlier environment? In that case, you may want to look into getting better tools on Unix to make your development experience more pleasant. There are various IDEs (if that's your poison) available on Unix, starting with the ubiquitous Eclipse to things like SunStudio (if you're on SUN) and of course all the integration tools that allow you to use the more powerful Unix editors like Emacs or VIM.</p>
<p>If your server connection is slow/flaky/expensive etc and you'd rather develop on your desktop, why not stick a VM with a Linux version or if you're developing for Solaris, one of the OpenSolaris or Solaris 11 developer preview builds into a VM on your machine and work on that one?</p>
|
Does anyone know of any good (and cheap) domain registration companies who all access to SPF/TXT records <p>I use 1and1 mainly - through legacy/lethargy reasons as I would not recommend them. Unfortunately, they do not allow access to the SPF/TXT records of domains, and I need this. At the moment I do not need a new host (as there are too many client systems to move over), but just someone to register the domain and give me access to the DNS, SPF, etc...</p>
<p>Cheers.//</p>
| <p>There are <strong>many</strong> such companies and it will be hard to list them all. For instance, the DNS hoster I use sometimes, <a href="http://www.gandi.net/" rel="nofollow">Gandi</a>, allows you to set SRV, LOC, AAAA, TXT (but not SPF and not DS).</p>
<p>Do note that very few programs use the SPF record, they typically lookup only the legacy TXT one.</p>
<p>And, of course, another option is to manage the zone yourself on one server which belongs to you.</p>
|
Serial port dropping data with Readline() <p>I am using serial port to read the data off the scale that is attached to the thin client. In 99% of cases the data is read correctly - ie whatever is on the scale is what is captured by the application.
However, sometimes, it looks like data is dropped. For instance instead of 90.007 it will be read as 0.007. I am using ReadLine function:</p>
<pre><code>private void CaptureWeight()
{
globalCounter++;
string value = "";
_sp.DiscardInBuffer();
while (!this._processingDone)
{
try
{
value = this._sp.ReadLine();
if (value != "")
{
if (value == "ES")
{
_sp.DiscardInBuffer();
value = "";
}
else
{
this.Invoke(this.OnDataAcquiredEvent, new object[] { value });
}
}
}
catch (TimeoutException)
{
//catch it but do nothing
}
catch
{
//reset the port here?
MessageBox.Show("some other than timeout exception thrown while reading serial port");
}
}
} //end of CaptureWeight()
</code></pre>
| <p>Don't call DiscardInBuffer. The operating system buffer is filled <a href="http://en.wikipedia.org/wiki/Asynchronous%5Fserial%5Fcommunication" rel="nofollow">asynchronously</a> as data is shifted in through the <a href="http://en.wikipedia.org/wiki/UART" rel="nofollow">UART</a>. Read all of the data and act on it accordingly because you have no way of knowing what is in the buffer at the time you discard it!</p>
|
How can I display my logo on my DokuWiki's title? <p>I have a DokuWiki and I'd like to place a logo on the title bar at the top of the page? How can I do this? Note that I am not referring to the title bar at the top of the browser, but rather the title bar on the website itself.</p>
<p>I tried inserting the DokuWiki syntax: {{public:logo.jpg?100x100}}, but this simply rendered as plain text and not an image.</p>
<p>Is it possible to put an image in the page title?</p>
| <p>Easy: Rename your logo as "logo.png" and place it into :wiki namespace. It will show automatically.</p>
<p>This solution works on template "<a href="https://www.dokuwiki.org/template%3adokuwiki">dokuwiki</a>" (default one on dokuwiki old stable version "<a href="https://www.dokuwiki.org/changes#release_2012-10-13_adora_belle">Adora Belle</a>" and in current one "<a href="https://www.dokuwiki.org/changes#release_2013-05-10_weatherwax">Weatherwax</a>"): </p>
<p><strong>Deeper:</strong></p>
<p>We can look at tpl_header.php file, lines 21&23:</p>
<pre><code>// get logo either out of the template images folder or data/media folder
</code></pre>
<p>[...]</p>
<pre><code>$logo = tpl_getMediaFile(array(':wiki:logo.png', 'images/logo.png'), false, $logoSize);
</code></pre>
<p>Ok: tpl_getMediaFile() function will look for a file logo.png in media namespace called wiki.</p>
<p>So I go to dokuwiki File Manager and I upload my logo.png file on wiki namespace. I refresh page and I smile.</p>
<p><img src="http://i.stack.imgur.com/CFD9F.png" alt="solution with dokuwiki File Manager"></p>
<p>Hope That Helps</p>
|
Is it wise to provide access to weak_ptr in a library interface? <p>I have written a library that exposes references to several related object types. All of these objects have their lifetimes managed by the library internally via <code>boost::shared_ptr</code></p>
<p>A user of the library would also be able to know, by nature of the library, the lifetimes of any of the exposed objects. So they could store pointers or keep references to these objects. It would be reasonable for them to do this and know when those objects are no longer valid.</p>
<p>But I feel guilty forcing my users to be reasonable.</p>
<p><strong>Is it acceptable to have a library expose <code>weak_ptr</code>'s to its objects? Have other libraries done this?</strong></p>
<p>I have profiled this library's usage in apps and have found it to be too mission-critical to expose <code>weak_ptr</code> exclusively.</p>
<p><strong>Would it be wiser to have matching API functions expose either a reference <em>or</em> a weak_ptr or to make any object capable of exposing a <code>weak_ptr</code> to itself?</strong></p>
| <p>If the <code>smart_ptr</code>s are already directly accessible to the library's users, then they've already got access to the <code>weak_ptr</code>s, simply via the corresponding <code>weak_ptr</code>'s constructor. But if the <code>smart_ptr</code>s are all internal to the library, that's a different story.</p>
<p>In that case, I'd recommend letting each object pass out <code>weak_ptr</code>s to itself, in addition to any other access your library offers. That gives the users the most flexibility: if they need a <code>weak_ptr</code>, they've got immediate access to it; if they need a <code>shared_ptr</code>, they can easily get it; and if they just need access to the object itself, they can ignore the smart pointers entirely.</p>
<p>Of course, I don't know what your library does or how it's used or designed. That might change my recommendation.</p>
|
Looking for a Command Line Argument Parser for .NET <p>I'm looking for a command line argument parser, such as "Command line parser" from <a href="http://www.sellsbrothers.com/tools/Genghis/">http://www.sellsbrothers.com/tools/Genghis/</a> .</p>
<p>Features I'm looking for:</p>
<ul>
<li>Auto-generation of usage</li>
<li>Should able to check required and optional parameters</li>
<li>Parameters should support IEnumerable with separator support</li>
<li>Should support flag parameters</li>
<li>Would be nice to support combining parameters such as "/fx" == "/f /x"</li>
<li>Would be nice to not force for a space after a parameter such as "/ftest.txt" == "/f test.txt"</li>
</ul>
<p>P.S :
<em>"Command line parser" is quite good, I really like the design of it but there is no documentation, no new updates and I couldn't figure out to do certain stuff such as how to check for required parameters.</em></p>
| <p>My personal favourite 3rd party commandline parsing library is <a href="http://commandline.codeplex.com/">Command Line Parser</a> and I assume this is the one you are referring to. The most recent release was less than 2 months ago and there are regular commits. If you want a more mature offering you could chek out the console library in the mono project (sorry I can't seem to find a direct link to the namespace at the moment, but its a part of the mono framework)</p>
|
Grails UrlMappings with URL-pattern ending with "/" <p>I have the following UrlMapping in my Grails UrlMappings class:</p>
<pre><code> "/$something/" {
controller = "controllerName"
action = "actionName"
constraints {
}
}
</code></pre>
<p>Requests to both "/foobar/" and "/foobar" gets routed to the correct controller and action.</p>
<p>However, URL:s created using g:link does not end with slash ("/") as expected.</p>
<p>The GSP code ...</p>
<pre><code><g:link controller="controllerName" action="actionName" params="[something: 'foobar']">...</g:link>
</code></pre>
<p>... generates the HTML output ...</p>
<pre><code><a href="/foobar">...</a>
</code></pre>
<p>How do I make Grails generate the link as specified by the URL pattern? That is including the ending slash.</p>
| <p>Unfortunately this is not possible with Grails' default URL mapping. Slashes are handled in a special way. And this behaviour is hard-coded in the Grails core. It could be overridden using a plugin though.</p>
<p>As a workaround (probably not applicable) I can provide to use it that way:</p>
<pre><code><g:link uri="/foobar/">Foo Link</g:link>
</code></pre>
<p>This should produce a link with a trailing slash.</p>
|
Should I make a constants class for my annotations? <p>Which is better?</p>
<ol>
<li><code>@SuppressWarnings("unchecked")</code></li>
<li><code>@SuppressWarnings(AnnotationConstants.UNCHECKED)</code></li>
</ol>
<p>Where <code>AnnotationConstants</code> is a typical constants class...</p>
<pre><code>public final class AnnotationConstants {
private AnnotationConstants() { }
public static final String UNCHECKED = "unchecked";
...
}
</code></pre>
<p>I know that there are a lot of general arguments for and against constants classes--and that's exactly what I'm <strong>not</strong> interested in. I want to know if a constants class <strong>specifically</strong> for annotations is a good idea or a bad idea.</p>
| <p>For this <em>specific</em> example I'd stick with literals. After all, you're trying to suppress warnings - if you use the wrong literal, the warning won't be suppressed, which will draw your attention to the problem.</p>
|
Popup menu radio item checks <p>I'm using a popup menu with wxTaskBarIcon on windows (wxWidgets-2.8.9).
If I fill popup menu with radio items, they do not change state when clicked.
First item in popup menu list is marked as selected. But selecting any other item does not change this.</p>
<p>Currently there is no item click event handler (application is more like UI prototype). Should i manually update item check status in this handler or it is still framework duty?</p>
| <p>You should use <code>EVT_UPDATE_UI(yourCommandID, yourEventHandler)</code> for checking/unchecking and enabling/disabling menu items.
In your UpdateUI event handler you should specify cases when your item is enabled
E.g. you have radiobutton group with commands ID_RADIO_1 and ID_RADIO_2 and they should be checked depending on condition <code>bool m_SomeConditionVariable</code> then you should create 2 event handlers for them like</p>
<pre><code>void OnRadio1UpdateUI(wxUpdateUIEvent & event)
{
event.Checked(m_SomeConditionVariable == true);
}
void OnRadio2UpdateUI(wxUpdateUIEvent & event)
{
event.Checked(m_SomeConditionVariable == false);
}
</code></pre>
<p>and in this case first radio item will be checked only when variable is false and second will be checked when variable is true.</p>
<p>You can use also calculated condition instaed of storing variable e.g.</p>
<pre><code>void OnRadio2UpdateUI(wxUpdateUIEvent & event)
{
// Item will be enabled only when text control has non-empty value
event.Enabled(!m_SomeTextCtrl->GetValue().Trim().IsEmpty());
}
</code></pre>
|
non-static and static data and functions <p>Is it possible to call a non-static data member in a static member function?
And is it also possible to call a non-static member function in a static member function?</p>
<p>How do you do it?</p>
| <p>YES - you can, and here is how</p>
<pre><code>class Foo
{
public:
static void staticFunc( const Foo & foo)
{
foo.memberFunc();
}
void memberFunc() const
{
staticFunc(*this);
}
};
</code></pre>
<p>This is the sort of a design, recursion aside, demonstrates how to call both static and non-static member functions. </p>
|
How to properly name a class with respect to its namespace? <p>One can often see class names carrying a reference to the namespace to which they belong. One of the most popular examples is the .NET 'Xml' namespace where every single class defined in it is prefixed with the 'Xml' tag.</p>
<p>This has always seemed pretty redundant to me, but recently I've realized that in some cases it could be useful... but still redundant.</p>
<p>I'd like to know how people actually deal with this issue.</p>
<p>Thanks.</p>
| <p>I take the "when it is appropriate" approach. The idea is that you want to name your classes using the name that makes the most sense. In some cases it does mean that the class name is somewhat redundant with the namespace, but keep in mind that the namespaces aren't generally seen as part of the class name in the code other than as part of a using directive.</p>
<p>The namespaces are used to logically group related classes, etc. together to help the developer find the correct classes and help minimize the chance of name collisions.</p>
|
How to minimize question-marks when encoding a String as Latin-1? <p>When encoding a java String to Latin-1 (ie. charset ISO-8859-1) I currently convert the German symbol β ('\u03B2') to à ('\u00DF') before performing the encoding. I'm trying to avoid a question mark in the encoding where possible.</p>
<p>Can anyone suggest other un-encodable characters which can be replaced an encodable character? Or better yet, a Java library that does it for me?</p>
<p>Update:
A bit of background: I have a Java program which exports it's data to CSV files so they can be read into a thrid-party application. A customer has complained that some characters are not converted - he gave me the example of "straβe". Although technically β is the greek symbol for Beta, a quick google search shows quite a few people use it to mean Ã.</p>
| <p>U+03B2 is the Greek letter "beta". U+00DF is a German "sharp s". Really not the same thing! If you want a Latin character, wouldn't the letter B be a better fit for β? A little background on your scenario or use cases would help guide suitable suggestions.</p>
<p>There are 10s of thousands of glyphs in Unicode, and only a few of them can be encoded with Latin-1.</p>
|
C++ select first not null element <p>Guys,
<br><strong>[question update according to updated requirements]</strong><br>
I've implemented following function which should return either first not null element or throw an exception.<br>
Also could you invent more classic and shorter name like 'max', 'min', 'pair'?</p>
<pre><code>template <typename T>
T select_first_not_empty( const T& a, const T&b )
{
static T null = T();
if ( a == null && b == null )
throw std::runtime_error( "null" );
return
a != null ? a : b;
}
int main()
{
const int a1 = 2;
const int b1 = 0;
const int* a2 = 0;
const int* b2 = new int(5);
const std::string a3 = "";
const std::string b3 = "";
std::cout << select_first_not_empty( a1, b1 ) << std::endl;
std::cout << select_first_not_empty( a2, b2 ) << std::endl;
std::cout << select_first_not_empty( a3, b3 ) << std::endl;
return 0;
}
</code></pre>
| <p>you can try do next<br></p>
<pre><code>template < typename T >
T get_valuable( const T& firstValue,
const T& alternateValue,
const T& zerroValue = T() )
{
return firstValue != zerroValue ? firstValue : alternateValue;
}
// usage
char *str = "Something"; // sometimes can be NULL
std::string str2 ( get_valuable( str, "" ) );
// your function
template <typename T>
T select_first_not_empty( const T& a,
const T& b,
const T& zerroValue = T() )
{
const T result = get_valuable( a, b, zerroValue );
if ( result == zerroValue )
{
throw std::runtime_error( "null" );
}
return result;
}
</code></pre>
|
how can I easily get a set of files that share a label in TFS? <p>I'm using TFS and I'd like to be able to get all files that have label XYZ. The only way that I can see to do this is to do "Get Specific Version", Label, Browse the label, pick a file, hit Get. Repeat for every file. If I have 20 files to get then this will be tedious and error prone. Doing a get on the label name at a root level of the repository doesn't work, it won't find the files in the subdirectories. Someone told me that it works on his system though, so I'm not sure what the issue is. </p>
<p>Someone suggested labels as a solution to this problem: I'd like to be able to mark a set of files across multiple solutions as belonging to a group. I'd like to be able to get all of the files in the group at once and put them in a directory. Is this possible with TFS? The files in question are all SQL procs etc. so they don't really need to be part of a solution to run, they're just scripts. But they do belong together logically, since they'll all be run after a new database is added. </p>
<p>Update: I'm concluding that labels in TFS are broken or worthless. If someone would care to educate me, feel free. But I've blown enough time on them today to decide that they're not worth anymore of it. </p>
| <p>Just do the "Get Specific Version" with the label option from a folder, and it will apply recursively. From the command line, this looks like:</p>
<p>tf get * /r /version:Lyourlabelname</p>
|
Branching hell, where is the risk vs productivity tipping point? <p>My company is floating the idea of extending our version numbers another notch (e.g. from major.minor.servicepack to major.minor.servicepack.customerfix) to allow for customer specific fixes.</p>
<p>This strikes me as a bad idea on the surface as my experience is the more branching a product does (and I believe the customer fixes are branches of the code base) the more overhead, the more dilution of effort and ultimately the less productive the development group becomes.</p>
<p>I've seen a lot of risk vs productivity discussions but just saying "I think this is a bad idea" isn't quite sufficient. What literature is there about the real costs of becoming too risk averse and adopting a heavy, customer specific, source code branching, development model?</p>
<p>A little clarification. I expect this model would mean the customer has control over what bug fixes go into their own private branch. I think they would rarely upgrade to the general trunk (it may not even exist in this model). I mean why would you if you could control your own private reality bubble?</p>
| <p>Can't help with literature, but customer-specific branching <em>is</em> a bad idea. Been there, done that. Debugging the stuff was pure hell, because of course you had to have all those customer-specific versions <em>available</em> to reproduce the error... some time later, the company had to do a <em>complete</em> rewrite of the application because the code base had become utterly <em>unmaintainable</em>. (Moving the customer-specific parts into configuration files so every customer was on the same code line.)</p>
<p>Don't go there.</p>
|
IE6 Red Cross and Border around image <h2>MAJOR UPDATE:</h2>
<h2><strong>I have a PNG fix working on the site. When I remove the PNG fix the red cross and border disapear. What's odd is that the problem only seems to do it with this particular image. There are other Alpha Blended PNG's on the same page that render fine.</strong> </h2>
<p>The image is not broken (you can see it) nor is it a link. But IE6 and 7 both put a box around it and a red cross on it. It also strips the styling. </p>
<p><img src="http://i44.tinypic.com/287pzf8.png" alt="alt text" /></p>
<p>UPDATE: The image is NOT a background image, and the image is definitely not broken. You can actually see the image, works fine in Safari, Firefox, Chrome and Opera.</p>
<p>It's a plain old regular image tag</p>
<pre><code><div class='container'>
<img src='../images/leader_concierge.png' class='page_leader' width="917" height="257" />
</div>
</code></pre>
<p>here's the css </p>
<pre><code>.page_leader { margin: 10px 0; }
</code></pre>
<p>and here's the exact same thing in safari</p>
<p><img src="http://i39.tinypic.com/257zptf.png" alt="alt text" /></p>
| <p>You are missing the replacement gif.</p>
<p>All PNG fix methods require that a transparent gif be available to replace the png image, it's part of how the substitution works. If that gif is missing, then you get this broken image appearance even tho the PNG draws fine.</p>
<p>In the case of iepngfix.htc, it expects the file to be at /images/spacer.gif</p>
|
Architecture question involving search & session state <p>I have a grid with several thousand rows that can be filtered and sorted. On each row you can click a details button, which will bring you a new page with detailed information about the page. Because this is a button, you can't middle click or right click and open in a new tab. In addition, when clicking back you lose your filters and search results.</p>
<p>To solve this problem, I considered the following: Switch the buttons to links, and when filtering and searching, use get instead of post requests. This way, you could switch to new pages with a right click or middle click, and if you did follow a link normally, back would work properly.</p>
<p>This change was not made however. We were asked add a 'next result / previous result' set of buttons on the details page, that would allow you to navigate. While not an elegant solution, it would at least work.</p>
<p>I proposed adding querystring parameters to the details page, that would regenerate the search query based on filter, and allow you to get the next and previous results in code. </p>
<p>A team member took issue with this solution. He believes that it is a waste of server resources to re-query the database. Instead, a solution was proposed to add session variable that included a list of results. You could then use that to navigate.</p>
<p>I took issue with that because you can't have multiple tabs open without breaking navigation, and new results aren't appended to the list in real time. Also, if you worried about optimization, session would be the last thing to use since it eats memory and prevents server replication... unless you store the results back in the database.</p>
<p>What's the best solution?</p>
| <p>Session doesn't sound like a winner, won't scale with lots of users.</p>
<p>Hitting the database repeatedly does seem unnecessary, but it depends on the cost - how many users, how often would they refresh/filter and what is the cost of that query? </p>
<p>If you do use querystrings you could cache the pages by parameter.</p>
<p>What about some AJAX code on that button to retrieve details - leave the underlying grid in place and display details in a div/panel or a new window/tab. </p>
|
Where is the documentation for CGI.pm? <p>A google search reveals nothing useful. Does Perl have a javadoc equivalent for its modules?</p>
<p>(Update -- I'm aware of perdoc, but that is more like a man page, which is hard to scan to find functionality... I'm looking for a function/operation list (w/ descriptions) similar to javadoc's presentation or php's documentation)</p>
| <pre><code>perldoc CGI
</code></pre>
<p>Or online on <a href="https://metacpan.org/pod/CGI" rel="nofollow">MetaCPAN</a>: </p>
|
Apply CSS Style to child elements <p>I want to apply styles only to the table inside the DIV with a particular class:</p>
<p>Note: I'd rather use a css-selector for children elements.</p>
<p>Why does the #1 works and #2 doesnt?</p>
<p>1:</p>
<pre><code>div.test th, div.test td, div.test caption {padding:40px 100px 40px 50px;}
</code></pre>
<p>2:</p>
<pre><code>div.test th, td, caption {padding:40px 100px 40px 50px;}
</code></pre>
<p>HTML: </p>
<pre><code><html>
<head>
<style>
div.test > th, td, caption {padding:40px 100px 40px 50px;}
</style>
</head>
<body>
<div>
<table border="2">
<tr><td>some</td></tr>
<tr><td>data</td></tr>
<tr><td>here</td></tr>
</table>
</div>
<div class="test">
<table border="2">
<tr><td>some</td></tr>
<tr><td>data</td></tr>
<tr><td>here</td></tr>
</table>
</div>
</body>
</html>
</code></pre>
<p>What am I doing wrong?</p>
| <p>This code "<code>div.test th, td, caption {padding:40px 100px 40px 50px;}</code>" applies a rule to all <code>th</code> elements which are contained by a <code>div</code> element with a class named <code>test</code>, in addition to <strong>all</strong> <code>td</code> elements and <strong>all</strong> <code>caption</code> elements.</p>
<p>It is not the same as "all <code>td</code>, <code>th</code> and <code>caption</code> elements which are contained by a <code>div</code> element with a class of <code>test</code>". To accomplish that you need to change your selectors:</p>
<p>'<code>></code>' isn't fully supported by some older browsers (I'm looking at you, Internet Explorer). </p>
<pre><code>div.test th,
div.test td,
div.test caption {
padding: 40px 100px 40px 50px;
}
</code></pre>
|
Is there a clean approach to justify text in Reporting Service? <p>I'm creating a Report using SQL Reporting Services and I need to justify the text inside a textbox. By justify a mean aligning the text to both margin, left AND right. Just like justifying text in MS Word.</p>
<p>I've been browsing a lot and found only a few smelly solutions. </p>
<p>Is there a clean way to do this?</p>
<p>Thanks,</p>
<p>Pedro</p>
| <p>My understanding is that there is not a direct way to do this at the moment, although it is on the development team's radar. </p>
|
Web-based .resx file editor? <p>I'm working on a SharePoint site, and the site eventually needs to be localized to many different languages. We can use resource files, but we'd like for the translators to be able to update those files while the site is live, without requiring developer assistance to recompile, redeploy, etc.</p>
<p>To me, I think the easiest way to do this would be to provide a web application to edit the .resx files as they sit in the App_GlobalResources directory. Does anyone know of some sort of a web-based .resx editor like that? I found one <a href="http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor.aspx" rel="nofollow">from LavaBlast</a>, but it displays the values for all languages at once. With the number of languages we plan on having, I think that would eventually get unwieldy.</p>
<p>Any suggestions are appreciated.</p>
| <p>I used the one you found: <a href="http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor.aspx" rel="nofollow">http://blog.lavablast.com/post/2008/02/RESX-file-Web-Editor.aspx</a> It took a couple of hours but it works a treat. I think that having the multiple languages editable at the same time is very helpful to avoid getting your resx files out of sync, and to see blank entries easily.</p>
|
Which is the best encryption mechanism, Triple DES or RC4? <p><a href="http://en.wikipedia.org/wiki/Triple%5Fdes" rel="nofollow">Triple DES</a> or <a href="http://en.wikipedia.org/wiki/RC4" rel="nofollow">RC4</a>?</p>
<p>I have the choice to employ either one.</p>
| <p>As a high level view the following comments on both should be useful.</p>
<ul>
<li><p>It is extremely easy to create a protocol based on RC4 (such as WEP) that is of extremely low strength (breakable with commodity hardware in minutes counts as extremely weak).</p></li>
<li><p>Triple DES is not great in that its strength comes though excessive cpu effort but it is of considerably greater strength (both theoretically in real world attacks) than RC4 so should be the default choice.</p></li>
</ul>
<p>Going somewhat deeper: </p>
<p>In the field of encryption with no well defined target application then the definition of 'best' is inherently hard since the 'fitness' of an algorithm is multi variant. </p>
<ul>
<li>Ease of implementation
<ul>
<li>Can you run it on commodity hardware?</li>
<li>Are implementations subject to accidental flaws that significantly reduce security while still allowing 'correctness' of behaviour.</li>
</ul></li>
<li>Cost of implementation
<ul>
<li>Power/silicon/time to encode/decode.</li>
</ul></li>
<li>Effort to break
<ul>
<li>Brute Force resilience. Pretty quantifiable</li>
<li>Resistance to cryptanalysis, less quantifiable, you might think so but perhaps the right person hasn't had a try yet:)</li>
</ul></li>
<li>Flexibility
<ul>
<li>Can you trade off one of the above for another</li>
<li>What's the maximum key size (thus upper limits of the Brute Force)</li>
<li>What sort of input size is required to get decent encryption, does it require salting.</li>
</ul></li>
</ul>
<p>Actually working out the effort to break itself requires a lot of time and effort, which is why you (as a non cryptographer) go with something already done rather than roll your own. It is also subject to change over time, hopefully solely as a result of improvements in the hardware available rather than fundamental flaws in the algorithm being discovered.</p>
<p>The core overriding concern is of course just that, is it secure? It should be noted that many older algorithms previously considered secure are no longer in that category. Some are so effectively broken that their use is simply pointless, you have no security whatsoever simply <em>obscurity</em> (useful but in no way comparable to real security).</p>
<p>Currently neither of the core algorithms of RC4 and TDES is in that category but the naive implementation of RC4 is considered extremely flawed in protocols where the message data can be forced to repeat. RC4 has several more significant theoretical flaws than TDES.</p>
<p>That said TDES is NOT better than RC4 in all the areas listed above. It is significantly more expensive to compute (and that expensiveness is not justified, other less costly crypto systems exist with comparable security to TDES)</p>
<p>Once you have a real world application you normally get one or both of the following:</p>
<ul>
<li>Constrains on your hardware to do the task</li>
<li>Constraints imposed be the data you are encrypting (this is used to transmit data which needs to be kept secret only for X days... for example)</li>
</ul>
<p>Then you can state, with tolerances and assumptions, what can achieve this (or if you simply can't) and go with that.</p>
<p>In the absence of any such constraints we can only give you the following:</p>
<h3>Ease of implementation</h3>
<p>Both have publicly available secure free implementations for almost any architecture and platform available.
RC4 implementations may not be as secure as you think if the message can be forced to repeat (see the WEP issues). Judicious use of salting may reduce this risk but this will NOT have been subject to the rigorous analysis that the raw implementations have been and as such should be viewed with suspision.</p>
<h3>Cost of implementation</h3>
<p>I have no useful benchmarks for RC4 (it is OLD) <a href="http://www.cryptopp.com/benchmarks.html">http://www.cryptopp.com/benchmarks.html</a> has some useful guides to put TDES in context with RC5 which is slower than RC4 (TDES is at least an order of magnitude slower than RC4) RC4 can encrypt a stream at approximately 7 cycles per byte in a fast implementation on modern x86 processors for comparison.</p>
<h3>Effort to break</h3>
<p>Brute Force resilience of TDES is currently believed to be high, even in the presence of many encryption outputs.
RC4 brute force resilience is orders of magnitude lower than TDES and further is <em>extremely</em> low in certain modes of operation (failure to discard initial bits of stream)</p>
<p>Resistance to cryptanalysis, There are publicly known flaws for Triple DES but they do not reduce the effectiveness of it to realistic attack in the next decade or two, the same is not true for RC4 where several flaws are known and combined they have produced reliable attacks on several protocols based on it.</p>
<h3>Flexibility</h3>
<p>TDES has very little flexibility (and your library may not expose them anyway)
RC4 has a lot more flexibility (the key used to initialize it can be arbitrarily long in theory, though the library may limit this.</p>
<p>Based on this and your statement that you must use one or the other you should consider the RC4 implementation only if the CPU cost of TripleDES makes it unrealistic to implement in your environment or the low level of security provided by RC4 is still considerably higher than your requirements specify.</p>
<p>I should also point out that systems exist which are empirically better in all areas than RC4 and TDES.
The <a href="http://www.ecrypt.eu.org/stream/">eSTREAM</a> project is evaluating various stream cyphers in the order of 5 or less cycles per byte though the cryptanalysis work on them is not really complete.
Many faster, stronger block cyphers exist to compete with TDES. <a href="http://en.wikipedia.org/wiki/Advanced%5FEncryption%5FStandard">AES</a> is probably the best known, and would be a candidate since it is of comparable (if not better) security but is much faster.</p>
|
How to redirect subfolder to query in Mod Rewrite for IIS 7.0? <p>I'm using Mod Rewrite for IIS 7.0 from iis.net and want to redirect requests:</p>
<ul>
<li><em>http://example.com/users/<strong>foo</em></strong> to <em>http://example.com/User.aspx?<strong>name=foo</em></strong></li>
<li><em>http://example.com/users/<strong>1</em></strong> to <em>http://example.com/User.aspx?<strong>id=1</em></strong></li>
</ul>
<p>I have created 2 rules:</p>
<pre><code><rule name="ID">
<match url="/users/([0-9])" />
<action type="Rewrite" url="/User.aspx?id={R:1}" />
</rule>
<rule name="Name">
<match url="/users/([a-z])" ignoreCase="true" />
<action type="Rewrite" url="/User.aspx?name={R:1}" />
</rule>
</code></pre>
<p>It passes a test into iis mmc test dialog, but doesn't in debug (URL like <em>http://localhost:9080/example.com/users/1</em> or <em>â¦/users/foo</em>) and doesn't on real IIS!</p>
<p>What have I done wrong?</p>
| <p>The obvious problem is that your current regexes only match one character in the user name or one number. You'll need to add a plus quantifier inside the parentheses in order to match multiple letters or numbers. See <a href="http://www.regular-expressions.info/repeat.html" rel="nofollow">this page</a> for more info about regex quantifiers. Note that you won't be matching plain URLs like "/users/" (no ID or name). Make sure this is what you intended.</p>
<p>The other problem you're running into is that IIS evaluates rewrite rules starting from the first character after the initial slash. So your rule to match <code>/users/([0-9])</code> won't match anything because when the regex evaluation happens, the URL looks like <code>users/foo</code> not <code>/users/foo</code>. The solution is to use <code>^</code> (which is the regex character that means "start of string") at the start of the pattern instead of a slash. Like this:</p>
<pre><code><rule name="ID">
<match url="^users/([0-9]+)" />
<action type="Rewrite" url="/User.aspx?id={R:1}" />
</rule>
<rule name="Name">
<match url="^users/([a-z]+)" ignoreCase="true" />
<action type="Rewrite" url="/Users.aspx?name={R:1}" />
</rule>
</code></pre>
<p>Note that you're choosing <code>Users.aspx</code> for one of these URLs and <code>User.aspx</code> (no plural) for the other. Make sure this is what you intended.</p>
<p>BTW, the way I figured these things out was by using <a href="http://learn.iis.net/page.aspx/467/using-failed-request-tracing-to-trace-rewrite-rules/" rel="nofollow">IIS Failed Request Tracing to troubleshoot rewrite rules</a>. This made diagnosing this really easy. I was able to make a test request and look through the trace to find where each rewrite rule is being evaluated (it's in a section of the trace called "PATTERN_MATCH". For the particular PATTERN_MATCH for one of your rules, I saw this:</p>
<blockquote>
<p>-PATTERN_MATCH<br>
Pattern /users/([0-9]+?)<br>
InputURL users/1<br>
Negate false<br>
Matched false</p>
</blockquote>
<p>Note the lack of the beginning slash. </p>
|
Cannot Find Symbol <p>I have created a small Java application to automatically test some expressions for a true/false condition.</p>
<p>I am getting two compiler errors in both jGRASP and with the javac command.</p>
<p>The code follows:</p>
<pre><code>public class MathTest {
public static void main(String[] args) {
int x = 10;
int y = 20;
int z = 30;
String string1 = "six";
String string2 = "six";
if (x < 10 || x > 10)
System.out.print("True");
else
System.out.print("False");
if (z - y == x && Math.abs(y - z) == z)
System.out.print("True");
else
System.out.print("False");
if (x < 10 && x < 10)
System.out.print("True");
else
System.out.print("False");
if (string1.equals(string2))
System.out.print("True");
else
System.out.print("False");
if (x > y || y > x)
System.out.print("True");
else
System.out.print("False");
if (!(x < y + z) || !(x + 10 <= 20))
System.out.print("True");
else
System.out.print("False");
if (string1 == string2)
System.out.print("True");
else
System.out.print("False");
}
}
</code></pre>
<p>The error message is:</p>
<pre>
MathTest.java:14: cannot find symbol
symbol : method abs(int)
location: class Math
if(z - y == x && Math.abs(y - z) == z)
^
./Math.java:13: cannot find symbol
symbol : method abs(int)
location: class Math
if(z - y == x && Math.abs(y - z) == z)
^
2 errors
</pre>
<p>What am I doing wrong?</p>
<p>In the unlikely event that my instructor or any administrator from Salt Lake Community College ever comes across this question, let me make my intentions clear. This question is posted in the greatest spirit of academic honesty. I ask this question to seek general advice and help in understanding the proper way to use the Java programming language. I in no way use the work of others and represent it as my own work. I use the answers provided here as a general aid in my understanding. I do all my own work and do not copy work provided by people answering my question.</p>
| <p>You have a Math class, and you're attempting to use the abs() method. </p>
<p>The question is: Is it your intention to provide this function or are you trying to use the one in java.lang.Math?</p>
<p>For the first, you have to make sure you're declaring that function.</p>
<p>For the second you have to make sure you're using the correct parameters types; see <a href="http://java.sun.com/javase/6/docs/api/java/lang/Math.html" rel="nofollow">Math</a>.</p>
<p>Does your Math class have the abs method?</p>
<p>It seems like your Math class is shadowing the Math class that comes in the core of the language.</p>
<p>Your Math class is loaded and the abs method could not be found (hence the "Cannot find symbol" message) </p>
|
SEO of asp.net meta tags <p>Simply wondering if any SEO specialists out there know if Google or other search providers index meta differently because of the id generated by asp.net</p>
<p>
| <p>Generally no, they will ignore meta tags and do whatever they please.</p>
<p>As <a href="http://stackoverflow.com/users/25028/stevemegson">stevemegson</a> notes, the description meta tag is useful for providing your own description to display on the SERP (no guarantees it will be used).</p>
<p>Heres a great quote from the <a href="http://en.wikipedia.org/wiki/Meta%5Ftag#The%5Fdescription%5Fattribute" rel="nofollow">Wiki page for Meta_Tag</a>:</p>
<blockquote>
<p>Major search engine robots are more
likely to quantify such extant factors
as the volume of incoming links from
related websites, quantity and quality
of content, technical precision of
source code, spelling, functional v.
broken hyperlinks, volume and
consistency of searches and/or viewer
traffic, time within website, page
views, revisits, click-throughs,
technical user-features, uniqueness,
redundancy, relevance, advertising
revenue yield, freshness, geography,
language and other intrinsic
characteristics.</p>
</blockquote>
|
Wavy underlines in a FlowDocument <p>In WPF, is there an easy way to add wavy underlines (like spelling errors in Word) to <code>FlowDocument</code> elements? There's the <code>Underline</code> class, but there seems to be no way to style it.</p>
| <p>You can create the wavy effect using the following changes to Robert Macne's solution</p>
<p>Add a visual brush to the Grid.Resources section:</p>
<pre><code><VisualBrush x:Key="WavyBrush" Viewbox="0,0,3,2" ViewboxUnits="Absolute" Viewport="0,0.8,6,4" ViewportUnits="Absolute" TileMode="Tile">
<VisualBrush.Visual>
<Path Data="M 0,1 C 1,0 2,2 3,1" Stroke="Red" StrokeThickness="0.2" StrokeEndLineCap="Square" StrokeStartLineCap="Square" />
</VisualBrush.Visual>
</VisualBrush>
</code></pre>
<p>And change the pen to:</p>
<pre><code><Pen Brush="{StaticResource WavyBrush}" Thickness="6" />
</code></pre>
|
Flipping UIViews From Top / Bottom <p>I'm well aware that there are only two available UIView transitions, UIViewAnimationTransitionFlipFromLeft and UIViewAnimationTransitionFlipFromRight. I'm wondering if there is anyway that I can implement / emulate a UIViewAnimationTransitionFlipFromTop or UIViewAnimationTransitionFlipFromBottom.</p>
<p>The only way I can think to do this is by flipping the x axis with the y axis, but I've not seen any information about how to do this. Just setting the coordinates of each axis won't fix the issue as the x-axis till remains the x-axis. </p>
<p>Does anyone have any ideas how this can be accomplished?</p>
| <p>You can do this by applying a CATransform3D to your main view's CALayer, with your secondary view's CALayer behind it. In <a href="http://stackoverflow.com/questions/372018/widget-flip-behavior-in-core-animation-cocoa/372419#372419">this response</a>, I point to a Mac implementation of this animation by Mike Lee. You should be able to reuse a significant portion of that code to recreate this effect on the iPhone.</p>
|
iPhone SDK: UIWebView <p>I'm working on an app that uses a UIWebView to display its help files. The webView lives in it's own view, DocViewController...when its called the </p>
<pre><code>- (void)viewDidLoad {
</code></pre>
<p>method uses</p>
<pre><code>[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:docPage ofType:@"html"]isDirectory:NO]]];
</code></pre>
<p>to load the proper doc page. However, once the first page is loaded, the view becomes static and new pages aren't loaded when the docPage changes and the view is toggled. Is there a way to clear the webView so new pages load when requested? </p>
<p>Edit:<br>
The first answer is confusing to me. As is the routine below works. It's just that it only works <em>once</em>. After the view is loaded the first time it does not change when this view is toggled on again and the requested html page is different. The view always displays the first html page requested and will not load new requests.</p>
<pre><code> - (void)viewDidLoad {
docPage = [NSString stringWithFormat: @"%d", hexpage];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[NSBundle mainBundle] pathForResource:docPage ofType:@"html"]isDirectory:NO]]];
}
</code></pre>
| <p><code>viewDidLoad</code> is only called once, unless the view is released and needs to be reloaded. This occurs usually only when the view controller receives a low memory warning. Instead of <code>viewDidLoad</code>, try putting that code in <code>viewWillAppear:</code>, which gets called every time the view will show on the screen.</p>
|
Cast received object to a List<object> or IEnumerable<object> <p>I'm trying to perform the following cast </p>
<pre><code>private void MyMethod(object myObject)
{
if(myObject is IEnumerable)
{
List<object> collection = (List<object>)myObject;
... do something
}
else
{
... do something
}
}
</code></pre>
<p>But I always end up with the following excepction: </p>
<p>Unable to cast object of type 'System.Collections.Generic.List<code>1[MySpecificType]' to type 'System.Collections.Generic.List</code>1[System.Object]' </p>
<p>I really need this to work because this method needs to be very generic to receive single objects and collections both of unspecified types. </p>
<p>Is this possible, or is there another way of accomplishing this. </p>
<p>Thank you.</p>
| <p>C# 4 will have covariant and contravariant template parameters, but until then you have to do something nongeneric like</p>
<pre><code>IList collection = (IList)myObject;
</code></pre>
|
How do I force MS SQL Server to perform an index join? <p>I'm working on an assignment where I'm supposed to compare different join methods in SQL Server, namely hash-join, merge-join and index-join.</p>
<p>I'm having difficulties getting SQL Server to perform an index-join. Can anyone show me how I can force it to use an index-join (using a join hint or similar), or just simply provide a simple query with a join on which SQL server uses the index-join method?</p>
| <p>You have <a href="http://msdn.microsoft.com/en-us/library/ms173815%28SQL.90%29.aspx">Loop, hash and merge joins (BOL)</a> only. No index joins.</p>
<p>For more than you ever needed to know, <a href="http://blogs.msdn.com/craigfr/archive/2006/07/26/679319.aspx">Craig Friedman's series on JOINs</a> (he's one of the team that designed the relation engine for SQL Server)</p>
|
What is the feasibility of porting a legacy C program to Python? <p>I have a program in C that communicates via UDP with another program (in Java) and then does process manipulation (start/stop) based on the UDP pkt exchange.
Now this C program has been legacy and I want to convert it to Python - do you think Python will be a good choice for the tasks mentioned?</p>
| <p>Yes, I do think that Python would be a good replacement. I understand that the <a href="http://twistedmatrix.com/trac/" rel="nofollow" title="Twisted">Twisted</a> Python framework is quite popular.</p>
|
Advertising rotation: What's the best to determine when and what ad should be displayed on the page? <p>A client I'm creating a site for wants a custom advertising "engine". The plan is to have a few ads on the site and fill the rest with Google Adsense until all the spots are full.</p>
<p>My problem is how to determine which ad to dipslay. (Assume for now that I only have 1 ad placement.) My thinking was I'd have a table with:</p>
<ul>
<li>year</li>
<li>month</li>
<li>impressions for the month (0 for unlimited)</li>
<li>used impressesion</li>
<li>clients</li>
<li>HTML code to display ad</li>
</ul>
<p>I could do something like to get the ads:</p>
<pre><code>SELECT *
FROM ad
WHERE impressions > used_impressions
OR impressesions = 0
ORDER BY RAND()
LIMIT 1
</code></pre>
<p>But, say I have 3 ads:</p>
<ul>
<li>1 ad -- 5000 impressions</li>
<li>1 ad -- 5000 impressions</li>
<li>Google Adsense filling the reaminder of the sites hits</li>
</ul>
<p>Statistically speaking all 3 ads would be displayed an equal number of times. By the end of the first week and 15000 hits on the site, the first 2 ads would have used all of their impressions and the remaining 3+ weeks of the month and not be displayed again; only Google Adsense would be displayed.</p>
<p>How do I space out the ads so they are spread out over the month?</p>
<p>I am using LAMP.</p>
| <p>Darryl,</p>
<p>I would suggest breaking the ad impressions down by day, so that</p>
<p>1 ad -- 5000/(monthsToDisplay/30)</p>
<p>This will give you a number of impressions you need to serve per day, and should help distribute things nicely over the weeks. So lets assume you have these variables or database fields:</p>
<p>totalImpressions = 5000;</p>
<p>dailyImpressions = totalImpressions/(monthsToDisplay/30)</p>
<p>Then you could do something like:</p>
<pre>SELECT * FROM ad WHERE (totalImpressions > used_impressions AND dailyImpressions > used_dailyImpressions) OR impressesions = 0 ORDER BY RAND() LIMIT 1</pre>
<p>Hope this made sense - it's early morning here, but I will check back later!</p>
<p>Berti</p>
|
jquery get() munching data? <p>I am trying to retrieve an entire webpage using get() and filter() out a specific section. This works fine when the page only includes the section I want to filter but if I input the entire page then it does not work.</p>
<p>Example:</p>
<pre><code> $(document).ready(function() {
$.get("source.html", function(data) {
$(data).filter(".spad").appendTo("#loadArea");
});
});
</code></pre>
<p>If source is:</p>
<pre><code><table class="spad" border="0" cellpadding="0" cellspacing="0"><thead><tr class="head"><th>&nbsp;</th><th class="sep">&nbsp;</th><th class="sep">&nbsp;</th><th id="h_a_5_0" colspan="2" class="sep">Length of day</th><th id="h_a_8_0" colspan="3" class="sep">Solar noon</th></tr><tr class="head"><th rowspan="2">Date</th><th class="sep" rowspan="2">Sunrise</th><th class="sep" rowspan="2">Sunset</th><th class="sep" rowspan="2">This day</th><th class="sep" rowspan="2">Difference</th><th class="sep" rowspan="2">Time</th><th class="sep" rowspan="2">Altitude</th><th class="sep NULL">Distance</th></tr><tr class="head"><th class="sep smaller">(10<sup>6</sup> km)</th></tr></thead><tbody><tr class="c0"><td>Mar 2, 2009</td><td>5:41 AM</td><td>6:19 PM</td><td>12h 37m 36s</td><td>&#8722; 1m 37s</td><td>12:00 Noon</td><td>69.7° </td><td>148.258</td></tr><tr class="c1"><td>Mar 3, 2009</td><td>5:42 AM</td><td>6:18 PM</td><td>12h 35m 58s</td><td>&#8722; 1m 37s</td><td>12:00 Noon</td><td>69.4° </td><td>148.294</td></tr><tr class="c0"><td>Mar 4, 2009</td><td>5:42 AM</td><td>6:17 PM</td><td>12h 34m 20s</td><td>&#8722; 1m 38s</td><td>12:00 Noon</td><td>69.0° </td><td>148.331</td></tr><tr class="c1"><td>Mar 5, 2009</td><td>5:43 AM</td><td>6:16 PM</td><td>12h 32m 42s</td><td>&#8722; 1m 38s</td><td>11:59 AM</td><td>68.6° </td><td>148.367</td></tr><tr class="c0"><td>Mar 6, 2009</td><td>5:43 AM</td><td>6:15 PM</td><td>12h 31m 03s</td><td>&#8722; 1m 38s</td><td>11:59 AM</td><td>68.2° </td><td>148.405</td></tr><tr class="c1"><td>Mar 7, 2009</td><td>5:44 AM</td><td>6:13 PM</td><td>12h 29m 25s</td><td>&#8722; 1m 38s</td><td>11:59 AM</td><td>67.8° </td><td>148.442</td></tr><tr class="c0"><td>Mar 8, 2009</td><td>5:45 AM</td><td>6:12 PM</td><td>12h 27m 46s</td><td>&#8722; 1m 38s</td><td>11:59 AM</td><td>67.4° </td><td>148.480</td></tr></tbody></table>
</code></pre>
<p>it works fine.</p>
<p>If i point the script at (or download it locally, this is not a cross domain ajax request thing) <a href="http://www.timeanddate.com/worldclock/astronomy.html?n=47" rel="nofollow">http://www.timeanddate.com/worldclock/astronomy.html?n=47</a> nothing shows up.</p>
<p>Any hints as to where I might be going wrong?</p>
| <p>You don't want <a href="http://docs.jquery.com/Traversing/filter" rel="nofollow"><code>filter()</code></a>; <code>filter()</code> removes elements from the set that don't match the given expression. You want <a href="http://docs.jquery.com/Traversing/find" rel="nofollow"><code>find()</code></a>:</p>
<pre><code>$(data).find(".spad").appendTo("#loadArea");
</code></pre>
|
Problem with adding custom sql to finder condition <p>I am trying to add the following custom sql to a finder condition and there is something not quite right.. I am not an sql expert but had this worked out with a friend who is..(yet they are not familiar with rubyonrails or activerecord or finder)</p>
<pre><code>status_search = "select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.created_at between "+status_date_start.to_s+" and "+status_date_end.to_s+")
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < "+status_date_start.to_s+")
and sc.status_id = '"+search[:status_id].to_s+"'
and sc.policy_id = p.id)" unless search[:status_id].blank?
</code></pre>
<p>My find statement:
Policy.find(:all,:include=>[{:client=>[:agent,:source_id,:source_code]},{:status_changes=>:status}],
:conditions=>[status_search])</p>
<p>and I am getting this error message in my log:</p>
<pre><code>ActiveRecord::StatementInvalid (Mysql::Error: Operand should contain 1 column(s): SELECT DISTINCT `policies`.id FROM `policies` LEFT OUTER JOIN `clients` ON `clients`.id = `policies`.client_id WHERE ((((policies.created_at BETWEEN '2009-01-01' AND '2009-03-10' OR policies.created_at = '2009-01-01' OR policies.created_at = '2009-03-10')))) AND (select p.*
from policies p
where exists
(select 0 from status_changes sc
where sc.policy_id = p.id
and sc.status_id = '2'
and sc.created_at between 2009-03-10 and 2009-03-10)
or exists
(select 0 from status_changes sc
where sc.created_at =
(select max(sc2.created_at)
from status_changes sc2
where sc2.policy_id = p.id
and sc2.created_at < 2009-03-10)
and sc.status_id = '2'
and sc.policy_id = p.id)) ORDER BY clients.created_at DESC LIMIT 0, 25):
</code></pre>
<p>what is the major malfunction here - why is it complaining about the columns?</p>
| <p>The conditions modifier is expecting a condition (e.g. a boolean expression that could go in a where clause) and you are passing it an entire query (a select statement).</p>
<p>It looks as if you are trying to do too much in one go here, and should break it down into smaller steps. A few suggestions:</p>
<ul>
<li>use the query with <code>find_by_sql</code> and don't mess with the conditions.</li>
<li>use the rails finders and filter the records in the rails code</li>
</ul>
<p>Also, note that constructing a query this way isn't secure if the values like <code>status_date_start</code> can come from users. Look up "sql injection attacks" to see what the problem is, and read the rails documentation & examples for <code>find_by_sql</code> to see how to avoid them.</p>
|
IOC dependency injection deployment (bin ? GAC ?) <p>Are there any deployment requirements for the most popular IOC containers (example: Windsor, Ninject, Unity, StructureMap, Autofac) ? Do they all deploy the same?</p>
<p>If you're on a shared host, what challenges will that present (ex. medium trust, etc...)</p>
<p>Can they be bin deployed? GAC deployed?</p>
<p>Any web-hosters that come "IOC-ready"?</p>
| <p>Most of the IOC frameworks works with private assemblies and i dont know much Web hosters that allows you to deploy files into the GAC.</p>
|
Ejb 3, message driven bean cooperating with a stateful session bean? <p>Hey! I'm relative new to both Java EE and Stackowerflow, please be kind :-) </p>
<p>I have a bunch of devices triggering Java messages to be sent on any state change. These devices are typically active for about 30-90 minute intervals. Each event message contains a device id in addition to the event details. </p>
<p>Central in my application is a message driven bean subscribing to those events. Every time I get an event I have to hit the database to look up some info about the device. </p>
<p>It would be absolutely terrific if I could associate a stateful session bean with each active device! If this had been a web application I would have used the http session to store a handle or reference to the stateful bean (I'm I right?). Is there any way that I can archive this from my message bean?</p>
| <p>It would be nice, except it can't be done like you explained. MDBs (and SLSBs) are stateless by definition so it's safe to keep a conversation only during the invocation.</p>
<p>You could eventually break the spec and create a static attribute somewhere (maybe in the MDB itself) but this would certainly be not portable, neither scalable.</p>
<p>My suggestion is to enable caching at the JPA level (see your persistence provider of preference for details), so you can lookup whatever data you need very fast (really fast). This is portable and cluster-friendly. That's the way I use to do it in my projects and I am very happy with it.</p>
<p>Hope it helps.</p>
|
Deleting and updating documents in Lucene index <p>Am using <code>Lucene.Net.dll</code>, version 2.0.0.4.</p>
<p>Looks like its <code>IndexWriter</code> class does not have methods for <code>DeleteDocument</code> or <code>UpdateDocument</code>. Am i missing something here? How do I achieve delete, update functionality in this version of Lucene.Net?</p>
<p>Version 2.1 Lucene.dll seems to have support for delete and update documents:</p>
<pre><code>public virtual void DeleteDocuments(Term term);
public virtual void UpdateDocument(Term term, Document doc);
</code></pre>
<p>In <a href="https://svn.apache.org/repos/asf/incubator/lucene.net/tags/Lucene.Net_2_1_0/" rel="nofollow">here</a> is the source code for verion 2.1, but I will have to download all the files one by one and then build a DLL out of it.</p>
<p>Can I download latest <code>Lucene.dll</code> and Highlighter from some site?</p>
| <p>I've documented how I update Lucene.NET Documents here:<br />
<a href="http://www.ifdefined.com/blog/post/2009/02/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx" rel="nofollow">http://www.ifdefined.com/blog/post/2009/02/Full-Text-Search-in-ASPNET-using-LuceneNET.aspx</a></p>
|
WCF contract changes that affect clients <p>I was curious if someone could outline which types of WCF contract (interface) changes on the server side would break a client trying to send in a message, and why. I believe WCF can handle certain discrepancies, but I'm not sure exactly what you can change safely, and what you can't.</p>
<ul>
<li>Add/remove parameters from an OperationContract?</li>
<li>Add/remove/change the DataContract's serialized properties?</li>
<li>Add/remove OperationContracts from a ServiceContract?</li>
</ul>
<p>A friend asked a similar question here:</p>
<p><a href="http://stackoverflow.com/questions/631935/does-adding-a-method-to-a-wcf-servicecontract-break-existing-clients">http://stackoverflow.com/questions/631935/does-adding-a-method-to-a-wcf-servicecontract-break-existing-clients</a></p>
<p>EDIT: As John Saunders pointed out, changing the contract is not usually a good idea, but there are things built in that allow for some version tolerance (ExtensionDataObject, etc.?). I would just like to know how flexible the version tolerance is.</p>
| <p>Check out this article on dasBlonde: <a href="http://web.archive.org/web/20100706022825/http://www.dasblonde.net/2006/01/05/VersioningWCFServiceContracts.aspx" rel="nofollow">Versioning WCF Service Contracts</a></p>
<p>It lists what changes will break existing clients:</p>
<ol>
<li>Remove operations</li>
<li>Change operation name</li>
<li>Remove operation parameters</li>
<li>Add operation parameters</li>
<li>Change an operation parameter name or data type</li>
<li>Change an operation's return value type</li>
<li>Change the serialized XML format for a parameter type (data contract) or operation (message contract) by explicitly using .NET attributes or custom serialization code</li>
<li>Modify service operation encoding formats (RPC Encoding vs. Document Literal)</li>
</ol>
<p><a href="http://searchwindevelopment.techtarget.com/tip/Designing-Windows-Communication-Foundation-service-contracts" rel="nofollow">This article by Michele</a> explains in more detail how you can design contracts to be more flexible.</p>
|
C# Enums and casting <p>If you declare an enum in C#, the default type is automatically int.</p>
<p>So then why in a case statement or other instances when using the enum do you have to explicitly recast in order to use the values? What's the point of having an underlying type if you have to explicitely case or am I just doing something wrong here?</p>
<pre><code>private enum MyEnum
{
Value1,
Value2,
Value3
}
switch (somevalue)
{
case (int)MyEnum.Value1:
someothervar = "ss";
break;
case (int)MyEnum.Value2:
someothervar = "yy";
break;
case (int)MyEnum.Value3:
someothervar = "gg";
break;
}
</code></pre>
| <p>What is the type of somevalue? If the type is MyEnum casting is un-necessary and should work without error. </p>
<p>If the type is int then yes you will have to cast up to a MyEnum in order to properly switch / case. But you can make this a bit simpler by casting the value instead of every case statement. For example</p>
<pre><code>switch( (MyEnum)somevalue ) {
case MyEnum.Value1: ...
}
</code></pre>
|
Determining type on the fly in OCaml's OOP construct <p>I am learning about OCaml's OOP constructs and partially implemented this today until I realized I have no idea how to represent a polymorphic match statement without using the type keyword outside of the object.</p>
<pre><code>class bar (param:string) =
object (code)
end;;
class foo param =
object (code)
initializer
match param with
string -> Printf.printf "param is a string"
| bar -> Printf.printf "param is a bar"
end;;
let b = new bar "a string";;
let f1 = new foo "test";;
let f2 = new foo b;;
</code></pre>
<p>Is it possible to determine the type of object passed in on-the-fly?</p>
| <p>That match isn't doing anything but binding 'param' to 'string', ocaml should say that the second match isn't used. I believe you'll have to use variant types to do the matching. Below is an example using polymorphic variant types.</p>
<pre><code>class bar (param:string) =
object (code)
end
class foo param =
object (code)
initializer
match param with
| `String str -> Printf.printf "param is a string"
| `Bar bar -> Printf.printf "param is a bar"
end
let b = new bar "a string"
let f1 = new foo (`String "test")
let f2 = new foo (`Bar b)
</code></pre>
|
How do you get PHP to return the timezone abbreviation AEST? <p>I can't seem to find a way to get Pear's Date class (or PHP's date function) to return AEST as the timezone abbreviation for the timezone Australia/Melbourne. It always returns EST. I tried all the ways of printing out the timezone available in Date::format, format2, format3. Anyone know how to fix this? I'm running PHP 5.1.6, Pear Date 1.5.0a1, and the latest PECL timezonedb.</p>
| <p>Have you checked what it says in the time zone database for Australia/Melbourne? It is probably based on the <a href="ftp://elsie.nci.nih.gov/pub/" rel="nofollow">Olson</a> database, and when I last looked (2009a edition), it was still saying EST is the abbreviation for Australia/Melbourne. So, unless you have fixed the time zone database to say AEST, it is likely to continue to say EST. This has been debated on the TZ mailing list a few times; there isn't a settled answer, so the abbreviation remains unchanged.</p>
|
How do I change the colour of map borders in Google Chart API? <p>Is there a way that you can change the colour of the country borders in a map provided by Google Chart API?</p>
<p>As you can see, the borders stand out a bit too much for my liking.</p>
<p><img src="http://chart.apis.google.com/chart?cht=t&chs=440x220&chtm=world&chco=404F64,DDFFDD,006600&chf=bg,s,344152&chld=AEAUBECAFRILITJPMXMYNLNZSEUKUSZA&chd=s:BbENBKBBBBNCBDfC" /></p>
<p>Here's the URL if you wanted to play with it:</p>
<pre><code>http://chart.apis.google.com/chart
?cht=t
&chs=440x220
&chtm=world
&chco=404F64,DDFFDD,006600
&chf=bg,s,344152
&chld=AEAUBECAFRILITJPMXMYNLNZSEUKUSZA
&chd=s:BbENBKBBBBNCBDfC
</code></pre>
| <p>Unfortunately, this option is not available in the Google Chart API, as far as I know. You can always mention this feature request on the <a href="http://groups.google.com/group/google-chart-api/topics" rel="nofollow">Google Chart API Group list</a></p>
|
Flex: Modifying Text Area <p>I'm making a text editor using Text Area. Which user can change font size, family and etc.<br />
This is my code on as:</p>
<pre><code> private function ChangeFont(event: Event):void
{
var mySelectedTextRange:TextRange = new TextRange(thistxtarea,true,
thistxtarea.selectionBeginIndex,
thistxtarea.selectionEndIndex);
mySelectedTextRange.fontSize = int(cmbbxFntSze.text);
thistxtarea.setFocus();
}
</code></pre>
<p>i have this combo box to enter desired font size:</p>
<pre><code><mx:ComboBox x="78" y="8" width="114" id="cmbbxFntFam" close="ChangeFont(event)"></mx:ComboBox>
</code></pre>
<p>How do I change font properties if the text inside is not highlight? For example I position the mouse pointer on last index of text inside my Text Area and I select on my combo box the desired font size. The following font size of letter that inputed in Text Area should be the selected font size on combo box. The code that I post works only if I highlight the desired text.</p>
| <p>This is to set the style</p>
<pre><code>private function setTextStyles(type:String, value:Object = null):void
{
if(thisindex != -1)
{
var tf:TextFormat;
var beginIndex:int = textArea.getTextField().selectionBeginIndex;
var endIndex:int = textArea.getTextField().selectionEndIndex;
textArea.getTextField().alwaysShowSelection = true;
if (beginIndex == endIndex)
{
tf = previousTextFormat;
}
else
tf = new TextFormat();
if (type == "bold" || type == "italic" || type == "underline")
{
tf[type] = value;
}
else if (type == "align")
{
if (beginIndex == endIndex)
{
tf = new TextFormat();
}
// Apply the paragraph styles to the whole paragraph instead of just
// the selected text
beginIndex = textArea.getTextField().getFirstCharInParagraph(beginIndex) - 1;
beginIndex = Math.max(0, beginIndex);
endIndex = textArea.getTextField().getFirstCharInParagraph(endIndex) +
textArea.getTextField().getParagraphLength(endIndex) - 1;
tf[type] = value;
previousTextFormat[type] = value;
if (!endIndex)
textArea.getTextField().defaultTextFormat = tf;
}
else if (type == "font")
{
tf[type] = cmbbxFntFam.text;
}
else if (type == "size")
{
var fontSize:uint = uint(cmbbxFntSze.text);
if (fontSize > 0)
tf[type] = fontSize;
}
else if (type == "color")
{
tf[type] = uint(clrpckerFontColor.selectedColor);
}
textFormatChanged = true;
if (beginIndex == endIndex)
{
previousTextFormat = tf;
}
else
{
textArea.getTextField().setTextFormat(tf,beginIndex,endIndex);//textArea.setTextFormat(tf,beginIndex,endIndex);
}
dispatchEvent(new Event("change"));
var caretIndex:int = textArea.getTextField().caretIndex;
var lineIndex:int = textArea.getTextField().getLineIndexOfChar(caretIndex);
textArea.invalidateDisplayList();
textArea.validateDisplayList();
textArea.validateNow();
// Scroll to make the line containing the caret under viewable area
while (lineIndex >= textArea.getTextField().bottomScrollV)
{
textArea.verticalScrollPosition++;
}
callLater(textArea.setFocus);
}
}
</code></pre>
<p>This code is use for getting the style from the textArea</p>
<pre><code> private function getTextStyles():void
{
if (!textArea)
return;
var tf:TextFormat;
var beginIndex:int = textArea.getTextField().selectionBeginIndex;
var endIndex:int = textArea.getTextField().selectionEndIndex;
if (textFormatChanged)
previousTextFormat = null;
if (beginIndex == endIndex)
{
tf = textArea.getTextField().defaultTextFormat;
if (tf.url != "")
{
var carIndex:int = textArea.getTextField().caretIndex;
if (carIndex < textArea.getTextField().length)
{
var tfNext:TextFormat=textArea.getTextField().getTextFormat(carIndex, carIndex + 1);
if (!tfNext.url || tfNext.url == "")
tf.url = tf.target = "";
}
else
tf.url = tf.target = "";
}
}
else
tf = textArea.getTextField().getTextFormat(beginIndex,endIndex);
if (cmbbxFntSze.text != tf.font)
setComboSelection(cmbbxFntFam, tf.font);
if (int(cmbbxFntSze.text) != tf.size)
setComboSelection(cmbbxFntSze,String(tf.size));
if (clrpckerFontColor.selectedColor != tf.color)
clrpckerFontColor.selectedColor = Number(tf.color);
if (btnBold.selected != tf.bold)
btnBold.selected = tf.bold;//Alert.show("bold");
if (btnItalic.selected != tf.italic)
btnItalic.selected = tf.italic;
if (btnUnderline.selected != tf.underline)
btnUnderline.selected = tf.underline;
if (tf.align == "left")
alignButtons.selectedIndex = 0;
else if (tf.align == "center")
alignButtons.selectedIndex = 1;
else if (tf.align == "right")
alignButtons.selectedIndex = 2;
else if (tf.align == "justify")
alignButtons.selectedIndex = 3;
if (textArea.getTextField().defaultTextFormat != tf)
textArea.getTextField().defaultTextFormat = tf;
previousTextFormat = tf;
textFormatChanged = false;
lastCaretIndex = textArea.getTextField().caretIndex;
thishtmltxt = textArea.htmlText;
textArea.validateNow();
}
</code></pre>
<p>Please check for minor errors, coz when i code this i have some commented traces</p>
|
Extracting list of values from lotus notes fields <p>I am migrating a Lotus Notes database to SQL Server using the LN java API. While traversing through each LN field in the documents I find all tabular info have field names like fld, fld_1, fld_2 etc where fld represents the name of a column and the numbering scheme is to take care of each individual row. Is there an simple way of extracting these info as arrays using the LN java API?</p>
| <p>Well "simple" can be an ambiguous term. </p>
<p>If you haven't solved this problem yet. You can write a method that loops around and grabs each field like this:</p>
<pre><code>import lotus.domino.*;
....
public static void main(String[] arg) {
for(int i=1 ;i<MAX_FIELD;i++) {
Item itm = doc.getFirstItem("field_"+String.valueOf(i));
if (itm != null) {
// if it's a multi-value field.
Vector v = item.getValues();
// do other stuff here with the values.
};
}
}
</code></pre>
<p>You'll need to make sure you import the appropriate NotesJava API's in your project. </p>
<p>Remember that each field on a document is effectively and array with 1 or more values. Those fields ("field_1", "field_2", etc) were defined arbitrarily by a developer. This is a common practice to emulate table-like data structures. Usually the fields represent columns not rows. But accessing the field in this way using the "item" object should give you access to the data.</p>
|
Selenium click() event seems not to be always triggered => results in timeout? <p>Here's what I do:</p>
<pre><code>selenium.click("link=mylink");
selenium.waitForPageToLoad(60000);
// do something, then navigate to a different page
// (window focus is never changed in-between)
selenium.click("link=mylink");
selenium.waitForPageToLoad(60000);
</code></pre>
<p>The link "mylink" does exist, the first invocation of click() always works. But the second click() sometimes seems to work, sometimes not.</p>
<p>It looks like the click() event is not triggered at all, because the page doesn't even start to load. Unfortunately this behaviour is underterministic.</p>
<p>Here's what I already tried:</p>
<ol>
<li><p>Set longer time timeout<br>
=> did not help</p></li>
<li><p>Wait for an element present after loading one page<br>
=> doesn't work either since the page does not even start to load</p></li>
</ol>
<p>For now I ended up invoking click() twice, so:</p>
<pre><code>selenium.click("link=mylink");
selenium.waitForPageToLoad(60000);
// do something, then navigate to a different page
// (window focus is never changed in-between)
selenium.click("link=mylink");
selenium.click("link=mylink");
selenium.waitForPageToLoad(60000);
</code></pre>
<p>That will work, but it's not a really nice solution. I've also seen in another forum where someone suggested to write something like a 'clickAndWaitWithRetry':</p>
<pre><code> try {
super.click("link=mylink");
super.waitForPageToLoad(60000);
}
catch (SeleniumException e) {
super.click("link=mylink");
super.waitForPageToLoad(60000);
}
</code></pre>
<p>But I think that is also not a proper solution....
Any ideas/explanations why the click() event is sometimes not triggered?</p>
| <p>Sometimes, seemingly randomly, Selenium just doesn't like to click certain anchor tags. I am not sure what causes it, but it happens. I find in those cases w/ a troublesome link instead of doing </p>
<pre><code>selenium.click(...)
</code></pre>
<p>do</p>
<pre><code>selenium.fireEvent( locator, 'click' );
</code></pre>
<p>As others have stated above me, I have specifically had issues with anchor tags that appear as follows:</p>
<pre><code><a href="javascript:...." >
</code></pre>
|
Can I get strongly typed bindings in WPF/XAML? <p>Using the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">MVVM</a>-pattern you set the DataContext to a specific ViewModel. Now is there any way to tell the XAML the type of the DataContext so that it will validate my bindings?</p>
<p>Looking for something like the typed viewdata in ASP.NET MVC.</p>
| <p>You can write each individual binding in a strongly-typed way:</p>
<pre><code><TextBox Text="{Binding Path=(vm:Site.Contact).(vm:Contact.Name)}" />
</code></pre>
<p>However this would not validate the fact that TextBox DataContext is of type ViewModel.Site (and I think this is not possible, but I may be wrong).</p>
|
Automatically add properties when running JUnit in Eclipse <p>In order to run my unit tests on my Eclipse, I need to set some properties for the VM.</p>
<p>Thus, when I first run my JUnit test, I go in "Open Run Dialog", then in my JUnit configuration for this test, I go in "Arguments" tab and put everything I need in the "VM arguments" text area.</p>
<p>Is there a way to automatically add a set of properties when I run my JUnit, so I will be able to only right-click on the test class, and click on "Run as > Junit Test" to run a test?</p>
<p>Technical information:
Eclipse 3.3.2, JUnit 4, Java 5</p>
<p><hr>
<strong>Edit</strong>, regarding response from Aaron Digulla:</p>
<p>These properties are used in Spring configuration files*. Thus, I can't use the idea given by Aaron, as Spring will be initialized before the test is run.</p>
<p>In addition to that, I just need to know if I can achieve that in a easy way in Eclipse. Thus the solution must not have any impact on the compilation of the application outside Eclipse, as my application will finally be compiled (and tested) by Maven2.</p>
<p>* few "unit" tests indeed need my Spring configuration to be run. Ok, I know that it is not real unit tests ;o)</p>
<p><strong>Edit 2</strong>: In fact, I was indeed starting the Spring configuration by a test unit. Thus, before starting Spring, I check the System properties, and if my properties are not set, then I give them the required value...</p>
<p>However, I am a little disappointed that Eclipse can't do that for me automatically...</p>
| <p>You could try this - go to </p>
<pre><code> Window->Preferences->Java->Installed JREs
</code></pre>
<p>ans select the JVM in use, than put a "Default VM" prameter like </p>
<pre><code> -DrunningInEclipse
</code></pre>
<p>Than you can check from within your TestCase:</p>
<pre><code> System.getProperty("runningInEclipse") != null
</code></pre>
|
What is the best implementation for AOP in .Net? <p>There is a lot of AOP implementation in C#, VB.net. this is some of AOP Implementations: </p>
<ul>
<li><a href="http://www.sharpcrafters.com/postsharp/features">PostSharp</a> </li>
<li><a href="http://loom.codeplex.com/">LOOM.NET</a></li>
<li><a href="http://aspectdotnet.codeplex.com/">Aspect.NET</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ff664572%28v=pandp.50%29.aspx">Enterprise Library 3.0 Policy Injection Application Block</a></li>
<li><a href="http://aspectdng.tigris.org/">AspectDNG</a></li>
<li><a href="http://dotspect.tigris.org/">DotSpect</a> (.SPECT)</li>
<li>The <a href="http://www.springframework.net/">Spring.NET</a> Framework as part of its functionality</li>
<li><a href="http://www.cs.columbia.edu/~eaddy/wicca/">Wicca</a> and Phx.Morph</li>
<li><a href="http://referaat.cs.utwente.nl/conference/5/paper/6755/aspect-oriented-design-methods.pdf">An exhaustive analysis on AOSD solutions for .NET</a> is available from Twente University</li>
<li><a href="http://s2container.net.seasar.org/en/index.html">Seasar.NET</a></li>
<li><a href="http://sourceforge.net/projects/aspectsharp/">Aspect#</a></li>
<li><a href="http://rogeralsing.com/2008/01/08/naspect-the-first-debuggable-aop-framework-for-net/">Puzzle.NAspect</a></li>
<li>Compose*</li>
<li>SetPoint</li>
<li>...</li>
</ul>
<p>What is the best implementation for AOP in .Net? What I should use?</p>
| <p>I think that <a href="http://www.castleproject.org/projects/dynamicproxy/">Castle Dynamic Proxy</a> is the solution of choice if dynamic interception can handle your needs. This framework is used internally by a lot of other frameworks that want to offer AOP capabilities. Typically, most of existing IoC containers now provide some dynamic interception mechanisms (Spring.NET, Castle Windsor, StructureMap, etc.) If you already work with an IoC container, maybe it could be easier to look at what it proposes.</p>
<p>If dynamic interception can't address your needs (weaving sealed class, intercepting non-virtual call, etc.), then you certainly want static weaving. <a href="http://www.postsharp.org/">PostSharp</a> is the reference in this domain.</p>
<p>Note that it also exists <a href="http://code.google.com/p/linfu/">Linfu</a>, that can be used to leverage both AOP fashions.</p>
|
Converting HTML files to PDF <p>I need to automatically generate a PDF file from an exisiting (X)HTML-document. The input files (reports) use a rather simple, table-based layout, so support for really fancy JavaScript/CSS stuff is probably not needed.</p>
<p>As I am used to working in Java, a solution that can easily be used in a java-project is preferable. It only needs to work on windows systems, though.</p>
<p>One way to do it that is feasable, but does not produce good quality output (at least out of the box) is using <a href="http://re.be/css2xslfo/index.xhtml">CSS2XSLFO</a>, and Apache FOP to create the PDF files. The problem I encountered was that while CSS-attributes are converted nicely, the table-layout is pretty messed up, with text flowing out of the table cell.</p>
<p>I also took a quick look at Jrex, a Java-API for using the Gecko rendering engine. </p>
<p>Is there maybe a way to grab the rendered page from the internet explorer rendering engine and send it to a PDF-Printer tool automatically? I have no experience in OLE programming in windows, so I have no clue what's possible and what is not.</p>
<p>Do you have an idea?</p>
<p><strong>EDIT</strong>: The FlyingSaucer/iText thing looks very promising. I will try to go with that.</p>
<p>Thanks for all the answers</p>
| <p>The <a href="http://code.google.com/p/flying-saucer/">Flying Saucer</a> XHTML renderer project has support for outputting XHTML to PDF. Have a look at an example <a href="http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html">here</a>.</p>
|
How to skin an ASP.NET GridView column? <p>The idea is simple - I want all Command columns in my GridViews to have a specific button image for, say, the "Delete" button. Sounds like a job for skins, but I cannot find the right syntax for that...</p>
| <p>Sounds like you want to template the GridView and add an image button to me. here is a link:
<a href="http://andybrudtkuhl.wordpress.com/2006/06/12/gridview-with-an-imagebutton/" rel="nofollow">http://andybrudtkuhl.wordpress.com/2006/06/12/gridview-with-an-imagebutton/</a></p>
|
Deleting duplicate records using a temporary table <p>Take the tsql query below:</p>
<pre><code>DECLARE @table TABLE(data VARCHAR(20))
INSERT INTO @table VALUES ('not duplicate row')
INSERT INTO @table VALUES ('duplicate row')
INSERT INTO @table VALUES ('duplicate row')
INSERT INTO @table VALUES ('second duplicate row')
INSERT INTO @table VALUES ('second duplicate row')
SELECT data
INTO #duplicates
FROM @table
GROUP BY data
HAVING COUNT(*) > 1
-- delete all rows that are duplicated
DELETE FROM @table
FROM @table o INNER JOIN #duplicates d
ON d.data = o.data
-- insert one row for every duplicate set
INSERT INTO @table(data)
SELECT data
FROM #duplicates
</code></pre>
<p>I understand what it is doing, but the last part of logic (after --insert one row for every duplicate set), doesn't make sense. Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section?</p>
<p>This query was found <a href="http://www.simple-talk.com/sql/t-sql-programming/removing-duplicates-from-a-table-in-sql-server/" rel="nofollow">here</a></p>
<p>Thanks</p>
| <blockquote>
<p>Where we have the set of code for --delete all rows that are duplicated, that gets rid of the duplicates so what's the part of the last section?</p>
</blockquote>
<p>First, it deletes all rows that ever had duplicates. That is, all rows, and original also. In the case above, only one row (<code>'not duplicate row'</code>) will remain in the table after <code>DELETE</code>. All four other rows will be deleted.</p>
<p>Then is populates the table with the deleted rows again, but now the duplicates are removed.</p>
<p>This is not the best way to delete duplicates.</p>
<p>The best way is:</p>
<pre><code>WITH q AS (
SELECT data, ROW_NUMBER() OVER (PARTITION BY data ORDER BY data) AS rn
FROM @table
)
DELETE
FROM q
WHERE rn > 1
</code></pre>
|
Sign in into a page using PHP <p>I have a PHP engine login page which i want to sign in using another PHP file without me physically inputting the details on that page, so i should be able to run a PHP file and sign into another login page on my server</p>
| <p>simply have your other PHP file post the required login credentials to your login page's action url</p>
|
Display Full Name in ASP.NET LoginName control <p>I have an .aspx page using a login control with custom authentication. I was wondering if it's possible to have a "Welcome [FirstName] [LastName]" message using the LoginName control instead of the [UserName] that is accessed by default. </p>
<p>I'm thinking of storing these info in the Session object if it's not possible.</p>
<p>Thanks!</p>
| <p>You'll need to override the <code>RenderContents</code> method or make your own LoginName control. Something like this will do the trick:</p>
<pre><code>protected override void RenderContents(HtmlTextWriter writer)
{
if (string.IsNullOrEmpty(Profile.FullName))
return;
nameToDisplay = HttpUtility.HtmlEncode(Profile.FullName);
string formatExpression = this.FormatString;
if (formatExpression .Length == 0)
{
writer.Write(nameToDisplay);
}
else
{
try
{
writer.Write(string.Format(CultureInfo.CurrentCulture, formatExpression, new object[1] { nameToDisplay });
}
catch (FormatException exception)
{
throw new FormatException("Invalid FormatString", exception1);
}
}
}
</code></pre>
<p>Also, see here for a brief article on <a href="http://www.ondotnet.com/pub/a/dotnet/2004/10/25/libertyonwhidbey.html" rel="nofollow">working with LoginName</a>.</p>
|
no mapping between account and security windows service <p>During the setup of windows service I get the error:</p>
<p>error 1001 no mapping between account and security windows service
We use a custom user account for the server. (administrator account)</p>
| <p>To avoid asking the same question again I'm posting my own findings below.</p>
<p>This page mentions something about file Gpttmpl.inf and some possible causes for the mapping error:</p>
<blockquote>
<ul>
<li>An account does not exist on domain member computers.</li>
<li>A SAM account name differs from its domain account name. </li>
<li>The client is running a Multilingual User Interface Pack (MUI) that uses a different default language than the domain controller.</li>
<li>A SAM account name was renamed on the client computers.</li>
</ul>
</blockquote>
<p><a href="http://support.microsoft.com/kb/890737" rel="nofollow">http://support.microsoft.com/kb/890737</a></p>
<p>I am getting similar error when the install on my Windows 7 PC is about to finish.</p>
<blockquote>
<p>Error 1001: No mapping between account names and and security IDs was done</p>
</blockquote>
<p>The MSI is generated from a VS 2010 setup project for a .NET Windows service targeting .NET Framework 4.</p>
<p>My MSI would install fine and the service would start fine when using VS 2008. Only after converting service solution to VS 2010 I started getting the issue, even though the domain account <code>/USERNAME=thisdomain\thisaccount /PASSWORD=thispasswd</code> exists and all the requirements above are taken care of.</p>
<p>I did overcome the issue temporarily by removing the original <code>/USERNAME= /PASSWORD=</code> values (meant for the server), from the <code>CustomActionData</code> property (right-click the setup project, select view, select Custom Actions, right-click the Install Primary output, select properties).</p>
<p>Rebuild the setup project and now the MSI ran/installed the service successfully. </p>
|
Deserialize Abstract Class <p>I have an abstract class 'Server' which I create in my JavaScript in my UI and then I want to have a method on my Web Service which does the following:</p>
<pre><code>public List<Database> GetDatabases(Server server)
{
Type type = server.GetType();
Server x = null;
if (typeof (SqlServer2005Server).Equals(type))
{
x = new SqlServer2005Server();
}
// Return the Databases from the server
return x.GetDatabases();
}
</code></pre>
<p>The issue I am having is that Server can not be deserialized as it is abstract, Do I need to have a method for each Server I have which inherits from the concrete type i.e</p>
<pre><code>public List<Database> GetDatabases(SqlServer2005Server server)
{
// Return the Databases from the server
return SqlServer2005Serverx.GetDatabases();
}
public List<Database> GetDatabases(OracleServer server)
{
// Return the Databases from the server
return SqlServer2005Serverx.GetDatabases();
}
</code></pre>
<p>I would really appreciate your help as i am not sure what is the best solution</p>
<p>The exact error I receive is:</p>
<blockquote>
<p>Instances of abstract classes cannot be created.</p>
</blockquote>
| <p>WCF will support inheritance, but you need to decorate your data contract with the known type attibute. For example:</p>
<pre><code>[DataContract]
[KnownType(typeof(Customer))]
class Contact
{
[DataMember]
public string FirstName
{get;set;}
[DataMember]
public string LastName
{get;set;}
}
[DataContract]
class Customer : Contact
{
[DataMember]
public int OrderNumber
{get;set;}
}
</code></pre>
<p>HTH.</p>
|
zcat to grep with file name <pre><code>ls -ltr|grep 'Mar 4'| awk '{print $9 }'|xargs zcat -fq |grep 12345
</code></pre>
<p>I'm now using this command to list the records that contain my numeric string how can i alos get this command to print the name of the file the strings were found in?</p>
<p>thanks</p>
| <p>Use <a href="http://linux.about.com/library/cmd/blcmdl1%5Fzgrep.htm" rel="nofollow">zgrep</a></p>
<p>BTW. what you're trying to do can be done with <a href="http://linux.about.com/od/commands/l/blcmdl1%5Ffind.htm" rel="nofollow">find</a></p>
<pre><code>find -newermt 'Mar 4' -and ! -newermt 'Mar 5' -exec zgrep -l '12345' {} \;
</code></pre>
|
Storing passwords in Castle Windsor configuration file? <p>I have the following:</p>
<pre><code>interface IDefectRepository { /* ... */ }
class MyDefectRepository : IDefectRepository
{
public MyDefectRepository(string url, string userName, string password)
{
// ...
}
// ...
}
</code></pre>
<p>I'm using <parameters> to pass the constructor parameters from Web.config. Is there any way that I can store the password encrypted in the Web.config file? Other suggestions?</p>
| <p>Try inheriting <code>MyDefectRepositoryWithEncryptedPasswords</code> from <code>MyDefectRepository</code>. In the <code>MyDefectRepositoryWithEncryptedPasswords</code> constructor decrypt the password and pass it to the <code>MyDefectRepository</code> constructor, like so:</p>
<pre><code>class MyDefectRepositoryWithEncryptedPasswords : MyDefectRepository
{
public MyDefectRepositoryWithEncryptedPasswords(string url, string userName, string encryptedPassword)
: base(url, userName, Decrypt(encryptedPassword))
{
}
public static string Decrypt(string encrypted)
{
// Do whatever...
}
}
</code></pre>
<p>Anyway, I don't think you should store encrypted passwords with two-way encryption methods. You should use some sort of hashing (of the cryptographic kind) and compare the hashes. That would require changing your constructor to receive not the password, but its hash.</p>
|
Implement prototype-similar functionality for WinForms controls hosted in IE <p>I'm using WinForms controls in IE. Something similar to this:</p>
<pre><code>var MyControl = new ActiveXObject("MyComponent.MyControl")
</code></pre>
<p>and I want to be able to use prototype feature for MyControl.:</p>
<pre><code>MyControl.prototype.newFunc = function(){alert('hi there');}
</code></pre>
<p>Is it possible at all? I thought about System.Runtime.InteropServices.Expando, but I can't find any comprehensive documentation about it.</p>
<p>Many Thanks,
Paul.</p>
| <p>I don't think that there is any way to modify the prototype of an ActiveX object because they do not inherit from the native js Object and therefore do not have a prototype.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.