Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
Does anyone know how to get the MS Office 2007 .NET C# Interop libraries to work with Vista?
I have a .NET C# application that I have setup to run as a Windows service. This program will open up a Word or Excel template depending on the situation and modify its contents and then save the document back out. All of this worked great when I was doing it on a Windows Server 2003 or XP machine using Office 2007. When I moved everything to a Server 2008 box, everything quit working. In Excel for example, I get a COM exception telling me that the Excel file cannot be opened when the file is clearly there and I can open it just fine when doing it manually. The windows service is running under the same user account that I log into the machine with and that account is an Administrator.
Does anyone have any idea what to do?
|
You should really avoiding running the Office clients as server side apps. Consider using xml as file format (xlsx for Office 2007, or using the Excel workbook xsd for (somewhat) older versions.) Then you would be freed from using the Excel API on the server.
|
On Vista and Windows Server 2008, services run in something called Session0. Before Vista, regular programs would run in Session0 alongside services.
This means that Session0 has become a desktop-less wasteland where your services can't even access explorer.exe. I'm pretty sure the problem is that Office applications are expecting to be able to access a few components that are normally on the desktop.
Since Excel, Word, etc. are only supported on a desktop-ed session, you only have a few choices:
1. Set the Desktop checkbox in the LogOn tab of your Service's properties and pray that it appeases the Office gods. (It probably wont.)
* After trying 1, go through your code and try and remove/work around anything that causes it to crash.
2. Use remoting/WCF to make a server that performs the interop work, and make your service communicate with it.
* You'll need to have a logged in interactive user and the user needs to start the server application somehow. Perhaps best to use autostart.
* You can try turning on Automatic login. <http://support.microsoft.com/kb/324737>
3. Try impersonating a Logged in user using CreateProcessAsUser and friends.
* Note: I don't know how well this works unless a user is actually logged in, so it might not be any more useful than 2 above, and is much harder to pull off. (Needs P/Invoke)
4. Rewrite your program to use the OpenXML sdk or use something like SpreadsheetGear.
|
Vista, Office Interop not working
|
[
"",
"c#",
"interop",
"ms-office",
"office-2007",
""
] |
Is there a .dll version of the [inclued](http://t3.dotgnu.info/blog/php/messy-programmers-beware.html) extension for [PHP](https://www.php.net/manual/en/intro.inclued.php)?
The manual's link for [Inclued on PECL4WIN](http://pecl4win.php.net/ext.php/php_inclued.dll) doesn't help. I don't have a compiler to build my own DLL.
NOTE: The spelling "inclued" is correct!
Edit: I don't have a compiler, but do know someone with one... that's really a last resort though.
|
Which version of PHP are you running? I know someone that can compile you a version.
## update
Alright, got this compiled - I've tested on my 5.2.6 build and it seems to work fine.
I've been told there may be problems using it in a threaded environment (e.g. Windows) but that's only a maybe. Also:
```
[13:10] <g0pz> the inclued dumpfiles will collide, because it uses PID # + increments
[13:11] <g0pz> but command line should work ok
[13:12] <g0pz> is the threaded apache version which'll have the same PID and well, a "possible" collision
```
So good luck with it :)
### [download](http://www.uvshock.co.uk/php_inclued.dll)
|
As best as I can tell, the Windows version doesn't exist anymore. Maybe whoever was maintaining it before had to stop for some reason.
I wonder what it takes to compile a PECL extension under Windows.
---
**Edit**
Here's some info on compiling a different PECL extension [on Windows](http://groups.google.co.uk/group/phpsoa/web/build-the-sca-sdo-pecl-extension). You may be able to extrapolate to the inclued extension.
---
**Edit**
[WAMP Server](http://www.wampserver.com/en/) comes with PECL & PEAR. I can actually run the command **pecl install inclued-alpha** from the Windows command-line and it goes out and tries to grab the inclued extension from the PECL site.
Unfortunately it dies when it unpacks the .tgz file and tries to compile it
```
ERROR: The DSP inclued.dsp does not exist.
```
|
PHP Inclued for Windows?
|
[
"",
"php",
"windows",
"pecl",
""
] |
I have an application I am writing in PHP5, using the CodeIgniter framework.
I have it running on both Windows (using Xampp) and Ubuntu (using standard Apache, PHP, MySQL stack).
I have a form, that takes XML, parses it (using simpleXML) and posts the results into a database.
On Windows - no problem, works as intended.
On Linux - big problem. It errors out.
I have double checked the XML, and it's fine.
I removed a large amount of the XML, and it seems that it is OK.
I think it's related to the size of the XML string being posted from the form, but am not sure. Again, on Windows it's OK - on Linux, it errors out.
The size of the data posted in the form is ~160k (yeah, that's a lot of text, but it's automated - AND it's gonna eventually be about 200k).
The error is below.
Any help much appreciated.
> Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /var/www/ci/system/application/controllers/system.php:49 Stack trace: #0 /var/www/ci/system/application/controllers/system.php(49): SimpleXMLElement->\_\_construct('') #1 [internal function]: System->add\_system() #2 /var/www/ci/system/codeigniter/CodeIgniter.php(233): call\_user\_func\_array(Array, Array) #3 /var/www/ci/index.php(115): require\_once('/var/www/ci/sys...') #4 {main} thrown in /var/www/ci/system/application/controllers/system.php on line 49
Line 49 looks like this:
`$xml = new SimpleXMLElement($this->input->post('form_systemXML'));`
EDIT - FIXED
Found the issue. Suhosin is installed on Ubuntu. in the file /etc/php5/apache2/conf.d/suhosin.ini, I enabled the line `suhosin.post.max_value_length = 65000` and changed the value to 195000. Restarted Apache, and all good. Thanks for the pointers guys.
|
It seems like you're running the [Suhosin](http://www.hardened-php.net/suhosin/) PHP extension.
Please have a look at the configuration documentation at: <http://www.hardened-php.net/suhosin/configuration.html>.
The relevant option seems to be (I've never used the Suhosin extension): [suhosin.post.max\_value\_length](http://www.hardened-php.net/suhosin/configuration.html#suhosin.post.max_value_length) and/or [suhosin.request.max\_value\_length](http://www.hardened-php.net/suhosin/configuration.html#suhosin.request.max_value_length)
|
Please check your PHP configuration on the Linux box and compare it to your Windows settings. Especially the following settings:
* memory\_limit
* post\_max\_size
* magic\_quotes\_gpc
* max\_input\_time
Perhaps you can do a dump of the data posted to the script
```
print_r($_POST);
```
to see what data is really coming into the server.
|
PHP SimpleXML, CodeIgniter and Apache with Suhosin
|
[
"",
"php",
"xml",
"apache",
"simplexml",
"suhosin",
""
] |
My style of coding includes the following idiom:
```
class Derived : public Base
{
public :
typedef Base super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
```
This enables me to use "super" as an alias to Base, for example, in constructors:
```
Derived(int i, int j)
: super(i), J(j)
{
}
```
Or even when calling the method from the base class inside its overridden version:
```
void Derived::foo()
{
super::foo() ;
// ... And then, do something else
}
```
It can even be chained (I have still to find the use for that, though):
```
class DerivedDerived : public Derived
{
public :
typedef Derived super; // note that it could be hidden in
// protected/private section, instead
// Etc.
} ;
void DerivedDerived::bar()
{
super::bar() ; // will call Derived::bar
super::super::bar ; // will call Base::bar
// ... And then, do something else
}
```
Anyway, I find the use of "typedef super" very useful, for example, when Base is either verbose and/or templated.
The fact is that super is implemented in Java, as well as in C# (where it is called "base", unless I'm wrong). But C++ lacks this keyword.
So, my questions:
* is this use of typedef super common/rare/never seen in the code you work with?
* is this use of typedef super Ok (i.e. do you see strong or not so strong reasons to not use it)?
* should "super" be a good thing, should it be somewhat standardized in C++, or is this use through a typedef enough already?
**Edit:** Roddy mentionned the fact the typedef should be private. This would mean any derived class would not be able to use it without redeclaring it. But I guess it would also prevent the super::super chaining (but who's gonna cry for that?).
**Edit 2:** Now, some months after massively using "super", I wholeheartedly agree with Roddy's viewpoint: "super" should be private.
|
Bjarne Stroustrup mentions in *Design and Evolution of C++* that `super` as a keyword was considered by the ISO C++ Standards committee the first time C++ was standardized.
Dag Bruck proposed this extension, calling the base class "inherited." The proposal mentioned the multiple inheritance issue, and would have flagged ambiguous uses. Even Stroustrup was convinced.
After discussion, Dag Bruck (yes, the same person making the proposal) wrote that the proposal was implementable, technically sound, and free of major flaws, and handled multiple inheritance. On the other hand, there wasn't enough bang for the buck, and the committee should handle a thornier problem.
Michael Tiemann arrived late, and then showed that a typedef'ed super would work just fine, using the same technique that was asked about in this post.
So, no, this will probably never get standardized.
If you don't have a copy, *Design and Evolution* is well worth the cover price. Used copies can be had for about $10.
|
I've always used "inherited" rather than super. (Probably due to a Delphi background), and I always make it **private**, to avoid the problem when the 'inherited' is erroneously omitted from a class but a subclass tries to use it.
```
class MyClass : public MyBase
{
private: // Prevents erroneous use by other classes.
typedef MyBase inherited;
...
```
My standard 'code template' for creating new classes includes the typedef, so I have little opportunity to accidentally omit it.
I don't think the chained "super::super" suggestion is a good idea- If you're doing that, you're probably tied in very hard to a particular hierarchy, and changing it will likely break stuff badly.
|
Using "super" in C++
|
[
"",
"c++",
"coding-style",
""
] |
I have to create the sin function from scratch in my Comp Sci class, and I am getting close to a solution. However, I am still having a few problems. If I put in a value of .5PI or less it works, but otherwise I get the incorrect result. Here is the code I have so far:
```
double i=1;
double sinSoFar = 0;
int term = 1;
while(i >= .000001)
{
i = pow(-1, term + 1) * pow(sinOf, 2*term-1) / factorial(2*term-1);
sinSoFar=sinSoFar + i;
term++;
}
```
|
Like Federico pointed, the problem probably is in your factorial() or pow(). I ran a test that worked fine replacing your functions with the pow() function provided in the Math class, and this factorial():
```
public static long factorial(long n) {
if (n < 0) throw new RuntimeException("Underflow error in factorial");
else if (n > 20) throw new RuntimeException("Overflow error in factorial");
else if (n == 0) return 1;
else return n * factorial(n-1);
}
```
|
Some advices:
* Start with term = 0. The canonical MacLaurin expansion also does
* compute the powers and the factorial *while you are cycling* (that is, updating them at each step). Maybe the problem is within pow() or factorial().
EDIT. Suggestion: once you have computed the k-th term, you can compute the (k+1)-th one by:
* Multiplying by (-1)
* Multiplying by sinOf^2
* Dividing by (2k+2)(2k+3)
In this way you can completely *avoid* the computation of powers and factorials.
|
Making a custom Sin() function in Java
|
[
"",
"java",
"trigonometry",
""
] |
I have to refactor a large C# application, and I found a lot of functions that are never used. How can I check for unused code, so I can remove all the unused functions?
|
Yes, ReSharper does this. Right click on your solution and selection "Find Code Issues". One of the results is "Unused Symbols". This will show you classes, methods, etc., that aren't used.
|
It's a great question, but be warned that you're treading in dangerous waters here. When you're deleting code you will have to make sure you're compiling and testing often.
One great tool come to mind:
NDepend - this tool is just amazing. It takes a little while to grok, and after the first 10 minutes I think most developers just say "Screw it!" and delete the app. Once you get a good feel for NDepend, it gives you amazing insight to how your apps are coupled. Check it out: <http://www.ndepend.com/>. Most importantly, this tool will allow you to view methods which do not have any direct callers. It will also show you the inverse, a complete call tree for any method in the assembly (or even between assemblies).
Whatever tool you choose, it's not a task to take lightly. Especially if you're dealing with public methods on library type assemblies, as you may never know when an app is referencing them.
|
Find unused code
|
[
"",
"c#",
".net",
"refactoring",
""
] |
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.
However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.
Is there any better way? I went with the CopyTo-approach.
|
Which version of .NET are you using? If it's .NET 3.5, I'd just call `ToArray()` and be done with it.
If you only have a non-generic IEnumerable, do something like this:
```
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
```
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
```
public static void T[] PerformQuery<T>()
{
IEnumerable query = ...;
T[] array = query.Cast<T>().ToArray();
return array;
}
```
|
Put the following in your .cs file:
```
using System.Linq;
```
You will then be able to use the following extension method from System.Linq.Enumerable:
```
public static TSource[] ToArray<TSource>(this System.Collections.Generic.IEnumerable<TSource> source)
```
I.e.
```
IEnumerable<object> query = ...;
object[] bob = query.ToArray();
```
|
Best way to convert IList or IEnumerable to Array
|
[
"",
"c#",
"nhibernate",
""
] |
I'm having a small problem in Java. I have an interface called Modifiable. Objects implementing this interface are Modifiable.
I also have a ModifyCommand class (with the Command pattern) that receive two Modifiable objects (to swap them in a list further on - that's not my question, I designed that solution already).
The ModifyCommand class starts by making clones of the Modifiable objects. Logically, I made my Modifiable interface extends Cloneable. The interface then defines a clone() method that its implementing classes must redefine.
Then, in ModifyCommand, I can do : firstModifiableObject.clone(). My logic is that classes implementing Modifiable will have to redefine the clone method from Object, as they will be Cloneable (that's what I want to do).
The thing is, when I define classes implements Modifiable and I want to override clone(), it won't let me, stating that the clone() method from the Object class hides the one from Modifiable.
What should I do? I'm under the impression that "I'm doing it wrong"...
Thanks,
Guillaume.
Edit : it think I will forget the clone() thing. I will either a) assume that the object passed to the Modifiable object (implementing the interface) is already cloned or b) make another method called, for example, copy(), that would basically do a deep-copy of the Modifiable object (or maybe the Generic solution will work...).
|
If you're using java 1.5 or higher, you can get the behavior you want and remove casting this way:
```
public interface Modifiable<T extends Modifiable<T>> extends Cloneable {
T clone();
}
public class Foo implements Modifiable<Foo> {
public Foo clone() { //this is required
return null; //todo: real work
}
}
```
Since Foo extends Object, this still satisfies the original contract of the Object class. Code that doesn't refine the clone() method correctly will not compile, because of the additional constraints imposed by the Modifiable interface. As a bonus, calling code doesn't have to cast the result of the clone method.
|
You don't need to redefine the clone method on the interface Modifiable.
Check the documentation: <http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html>
I understand that you are trying to force everyone to override clone method(), but you can't do it.
In another way, you cannot override a class on a interface:
The clone() method is always associated whit the Object.class and not the cloneable interface. You just can override it on another object, not in a interface.
|
Mandatory cloneable interface in Java
|
[
"",
"java",
"interface",
"overriding",
"clone",
""
] |
I know about [`SortedSet`](https://docs.oracle.com/javase/9/docs/api/java/util/SortedSet.html), but in my case I need something that implements `List`, and not `Set`. So is there an implementation out there, in the API or elsewhere?
It shouldn't be hard to implement myself, but I figured why not ask people here first?
|
There's no Java collection in the standard library to do this. [`LinkedHashSet<E>`](https://docs.oracle.com/javase/9/docs/api/java/util/LinkedHashSet.html) preserves ordering similarly to a `List`, though, so if you wrap your set in a `List` when you want to use it as a `List` you'll get the semantics you want.
Alternatively, the [Commons Collections](https://commons.apache.org/proper/commons-collections/) (or `commons-collections4`, for the generic version) has a `List` which does what you want already: [`SetUniqueList`](https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html) / [`SetUniqueList<E>`](https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/list/SetUniqueList.html).
|
Here is what I did and it works.
Assuming I have an `ArrayList` to work with the first thing I did was created a new `LinkedHashSet`.
```
LinkedHashSet<E> hashSet = new LinkedHashSet<E>()
```
Then I attempt to add my new element to the `LinkedHashSet`. The add method does not alter the `LinkedHasSet` and returns false if the new element is a duplicate. So this becomes a condition I can test before adding to the `ArrayList`.
```
if (hashSet.add(E)) arrayList.add(E);
```
This is a simple and elegant way to prevent duplicates from being added to an array list. If you want you can encapsulate it in and override of the add method in a class that extends the `ArrayList`. Just remember to deal with `addAll` by looping through the elements and calling the add method.
|
Is there a no-duplicate List implementation out there?
|
[
"",
"java",
"list",
"collections",
"duplicates",
""
] |
I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable
```
public interface ISelectable : INotifyPropertyChanged
{
event EventHandler IsSelected;
bool Selected { get; set; }
string DisplayText { get; }
}
```
I want to keep track of which object is selected regardless of how it is selected. The user could click on the representation of the object in the ListBox but it could also be that an object is selected via code. If the user selects an object via the ListBox I cast the the selected item to an ISelectable and set the Selected property to true.
```
ISelectable selectable = (ISelectable)e.AddedItems[0];
selectable.Selected = true;
```
My problem is that when I select the object using code I can't get ListBox to change the selected item. I'm using a DataTemplate to show the selected object in a different color which means everything is displayed correctly. But the ListBox has the last object the user clicked as the SelectedItem which means that item can't be clicked without first selecting another object in the list.
Anyone got any idea on how to solve this? I pretty sure I can accomplish what I want by writing some custom code to handle the Mouse and Keyboard events but I rather not. I have tried adding a SelectedItem property to the collection and bind it to the ListBox's SelectItemProperty but no luck.
|
You could also accomplish this by data binding ListBoxItem.IsSelected to your Selected property. The idea is to set the binding for each of the ListBoxItems as they are created. This can be done using a style that targets each of the ListBoxItems generated for the ListBox.
This way when an item in the ListBox is selected/unselected, the corresponding Selected property will be updated. Likewise setting the Selected property in code will be reflected in the ListBox
For this to work the Selected property must raise the PropertyChanged event.
```
<List.Resources>
<Style TargetType="ListBoxItem">
<Setter
Property="IsSelected"
Value="{Binding
Path=DataContext.Selected,
RelativeSource={RelativeSource Self}}"
/>
</Style>
</List.Resources>
```
|
Have you looked at the list box's SelectedItemChanged and SelectedIndexChanged events?
These should be triggered whenever a selection is changed, no matter how it is selected.
|
How do I synchronize the SelectedItem of a ListBox?
|
[
"",
"c#",
"wpf",
"listbox",
""
] |
What I'd like to avoid:
```
ManagementClass m = new ManagementClass("Win32_LogicalDisk");
ManagementObjectCollection managementObjects = m.GetInstances();
List<ManagementObject> managementList = new List<ManagementObject>();
foreach(ManagementObject m in managementObjects){
managementList.Add(m);
}
```
Isn't there a way to get that collection into a List that looks something like:
```
List<ManagementObject> managementList = new List<ManagementObjec>(collection_array);
```
|
What version of the framework? With 3.5 you could presumably use:
```
List<ManagementObject> managementList = managementObjects.Cast<ManagementObject>().ToList();
```
(edited to remove simpler version; I checked and `ManagementObjectCollection` only implements the non-generic `IEnumerable` form)
|
You could use
```
using System.Linq;
```
That will give you a ToList<> extension method for ICollection<>
|
Fastest Convert from Collection to List<T>
|
[
"",
"c#",
"collections",
""
] |
How do I detect if a process is already running under the Windows Task Manager? I'd like to get the memory and cpu usage as well.
|
Have you looked into the [System.Diagnostics.Process](https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process) Class.
|
Simple example...
```
bool processIsRunning(string process)
{
return (System.Diagnostics.Process.GetProcessesByName(process).Length != 0);
}
```
Oops... forgot the mem usage, etc...
```
bool processIsRunning(string process)
{
System.Diagnostics.Process[] processes =
System.Diagnostics.Process.GetProcessesByName(process);
foreach (System.Diagnostics.Process proc in processes)
{
Console.WriteLine("Current physical memory : " + proc.WorkingSet64.ToString());
Console.WriteLine("Total processor time : " + proc.TotalProcessorTime.ToString());
Console.WriteLine("Virtual memory size : " + proc.VirtualMemorySize64.ToString());
}
return (processes.Length != 0);
}
```
(I'll leave the mechanics of getting the data out of the method to you - it's 17:15 here, and I'm ready to go home. :)
|
Detecting a Process is already running in windows using C# .net
|
[
"",
"c#",
".net",
"windows",
"winforms",
""
] |
Can you recommend a Java library for reading, parsing, validating and mapping rows in a comma separated value (CSV) file to Java value objects (JavaBeans)?
|
We have used
<http://opencsv.sourceforge.net/>
with good success
I also came across another question with good links:
[Java lib or app to convert CSV to XML file?](https://stackoverflow.com/questions/123/csv-file-to-xml)
|
[Super CSV](http://supercsv.sourceforge.net) is a great choice for reading/parsing, validating and mapping CSV files to POJOs!
We (the Super CSV team) have just released a new version (you can [download](http://supercsv.sourceforge.net/downloading.html) it from SourceForge or Maven).
# Reading a CSV file
The following example uses `CsvDozerBeanReader` (a new reader we've just released that uses [Dozer](http://dozer.sourceforge.net/) for bean mapping with deep mapping and index-based mapping support) - it's based on the example from our [website](http://supercsv.sourceforge.net/examples_dozer.html). If you don't need the Dozer functionality (or you just want a simple standalone dependency), then you can use `CsvBeanReader` instead (see this [code example](http://supercsv.sourceforge.net/examples_reading.html)).
## Example CSV file
Here is an example CSV file that represents responses to a survey. It has a header and 3 rows of data, all with 8 columns.
```
age,consentGiven,questionNo1,answer1,questionNo2,answer2,questionNo3,answer3
18,Y,1,Twelve,2,Albert Einstein,3,Big Bang Theory
,Y,1,Thirteen,2,Nikola Tesla,3,Stargate
42,N,1,,2,Carl Sagan,3,Star Wars
```
## Defining the mapping from CSV to POJO
Each row of CSV will be read into a [SurveyResponse](http://supercsv.sourceforge.net/xref-test/org/supercsv/mock/dozer/SurveyResponse.html) class, each of which has a List of [Answer](http://supercsv.sourceforge.net/xref-test/org/supercsv/mock/dozer/Answer.html)s. In order for the mapping to work, your classes should be valid Javabeans (i.e have a default no-arg constructor and have getters/setters defined for each field).
In Super CSV you define the mapping with a simple String array - each element of the array corresponds to a column in the CSV file.
With `CsvDozerBeanMapper` you can use:
* simple field mappings (e.g. `firstName`)
* deep mappings (e.g. `address.country.code`)
* indexed mapping (e.g. `middleNames[1]` - zero-based index for arrays or Collections)
* deep + indexed mapping (e.g. `person.middleNames[1]`)
The following is the field mapping for this example - it uses a combination of these:
```
private static final String[] FIELD_MAPPING = new String[] {
"age", // simple field mapping (like for CsvBeanReader)
"consentGiven", // as above
"answers[0].questionNo", // indexed (first element) + deep mapping
"answers[0].answer",
"answers[1].questionNo", // indexed (second element) + deep mapping
"answers[1].answer",
"answers[2].questionNo",
"answers[2].answer" };
```
## Conversion and Validation
Super CSV has a useful library of [cell processors](http://supercsv.sourceforge.net/cell_processors.html), which can be used to convert the Strings from the CSV file to other data types (e.g. Date, Integer), or to do constraint validation (e.g. mandatory/optional, regex matching, range checking).
Using cell processors is *entirely optional* - without them each column of CSV will be a String, so each field must be a String also.
The following is the cell processor configuration for the example. As with the field mapping, each element in the array represents a CSV column. It demonstrates how cell processors can transform the CSV data to the data type of your field, and how they can be chained together.
```
final CellProcessor[] processors = new CellProcessor[] {
new Optional(new ParseInt()), // age
new ParseBool(), // consent
new ParseInt(), // questionNo 1
new Optional(), // answer 1
new ParseInt(), // questionNo 2
new Optional(), // answer 2
new ParseInt(), // questionNo 3
new Optional() // answer 3
};
```
## Reading
Reading with Super CSV is very flexible: you supply your own `Reader` (so you can read from a file, the classpath, a zip file, etc), and the delimiter and quote character are configurable via [preferences](http://supercsv.sourceforge.net/preferences.html) (of which there are a number of pre-defined configurations that cater for most usages).
The code below is pretty self-explanatory.
1. Create the reader (with your `Reader` and preferences)
2. (Optionally) read the header
3. Configure the bean mapping
4. Keep calling `read()` until you get a `null` (end of file)
5. Close the reader
**Code:**
```
ICsvDozerBeanReader beanReader = null;
try {
beanReader = new CsvDozerBeanReader(new FileReader(CSV_FILENAME),
CsvPreference.STANDARD_PREFERENCE);
beanReader.getHeader(true); // ignore the header
beanReader.configureBeanMapping(SurveyResponse.class, FIELD_MAPPING);
SurveyResponse surveyResponse;
while( (surveyResponse =
beanReader.read(SurveyResponse.class, processors)) != null ) {
System.out.println(
String.format("lineNo=%s, rowNo=%s, surveyResponse=%s",
beanReader.getLineNumber(), beanReader.getRowNumber(),
surveyResponse));
}
} finally {
if( beanReader != null ) {
beanReader.close();
}
}
```
**Output:**
```
lineNo=2, rowNo=2, surveyResponse=SurveyResponse [age=18, consentGiven=true, answers=[Answer [questionNo=1, answer=Twelve], Answer [questionNo=2, answer=Albert Einstein], Answer [questionNo=3, answer=Big Bang Theory]]]
lineNo=3, rowNo=3, surveyResponse=SurveyResponse [age=null, consentGiven=true, answers=[Answer [questionNo=1, answer=Thirteen], Answer [questionNo=2, answer=Nikola Tesla], Answer [questionNo=3, answer=Stargate]]]
lineNo=4, rowNo=4, surveyResponse=SurveyResponse [age=42, consentGiven=false, answers=[Answer [questionNo=1, answer=null], Answer [questionNo=2, answer=Carl Sagan], Answer [questionNo=3, answer=Star Wars]]]
```
## More Information
You can find a lot more information on the [website](http://supercsv.sourceforge.net)!
|
Can you recommend a Java library for reading (and possibly writing) CSV files?
|
[
"",
"java",
"parsing",
"csv",
""
] |
If I have a `Linq` to `SQL` expression like this:
```
from subscription in dbContext.Subscriptions
where subscription.Expires > DateTime.Now
select subscription
```
I want this to to use the SQL Servers `GETDATE()` function instead of the time of the machine running the `C#` program.
The next question would be how to translate this:
```
DateTime.Now.AddDays(2)
```
to this:
```
DATEADD(dd, 2, GETDATE())
```
|
Try [this](http://peteohanlon.wordpress.com/2008/01/11/sql-server-getdate-and-linq-to-sql/):
```
[Function(Name="GetDate", IsComposable=true)]
public DateTime GetSystemDate()
{
MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
return (DateTime)this.ExecuteMethodCall(this, mi, new object[]{}).ReturnValue;
}
```
**EDIT**: this needs to be a part of your DataContext class.
Now you can use GetSystemDate() instead of DateTime.Now in your queries.
As for date differences take a look at System.Data.Linq.SqlClient namespace, especially DayDiffXXX functions of SqlMethods class.
|
If you don't mind querying the database before every use, I would suggest the following workaround: Use ExecuteQuery in one place to get the date in the data context like this:
```
public partial class YourDataContext
{
public DateTime GetDate()
{
return ExecuteQuery<DateTime>("SELECT GETDATE()").First();
}
}
```
and then you can write
```
from subscription in dbContext.Subscriptions
where subscription > dbContext.GetDate().AddDays(2)
select subscription
```
|
How do I use SQL's GETDATE() and DATEADD() in a Linq to SQL expression?
|
[
"",
"sql",
"linq-to-sql",
""
] |
What's the most efficient way of getting the value of the SERIAL column after the INSERT statement? I.e. I am looking for a way to replicate `@@IDENTITY` or `SCOPE_IDENTITY` functionality of MS SQL
|
The value of the last SERIAL insert is stored in the SQLCA record, as the second entry in the sqlerrd array. Brian's answer is correct for ESQL/C, but you haven't mentioned what language you're using.
If you're writing a stored procedure, the value can be found thus:
```
LET new_id = DBINFO('sqlca.sqlerrd1');
```
It can also be found in `$sth->{ix_sqlerrd}[1]` if using DBI
There are variants for other languages/interfaces, but I'm sure you'll get the idea.
|
I have seen this used.
```
if LOCAL_SQLCA^.sqlcode = 0 then
/* return serial */
Result := LOCAL_SQLCA^.sqlerrd[1]
else
/* return error code */
Result := -(Abs(LOCAL_SQLCA^.sqlcode));
```
|
Informix: how to get an id of the last inserted record
|
[
"",
"sql",
"informix",
"identity",
""
] |
So, simple procedure, calculate a factorial number. Code is as follows.
```
int calcFactorial(int num)
{
int total = 1;
if (num == 0)
{
return 0;
}
for (num; num > 0; num--)
{
total *= num;
}
return total;
}
```
Now, this works fine and dandy (There are certainly quicker and more elegant solutions, but this works for me) for most numbers. However when inputting larger numbers such as 250 it, to put it bluntly, craps out. Now, the first couple factorial "bits" for 250 are { 250, 62250, 15126750, 15438000, 3813186000 } for reference.
My code spits out { 250, 62250, 15126750, 15438000, **-481781296** } which is obviously off. My first suspicion was perhaps that I had breached the limit of a 32 bit integer, but given that 2^32 is 4294967296 I don't think so. The only thing I can think of is perhaps that it breaches a **signed** 32-bit limit, but shouldn't it be able to think about this sort of thing? If being signed is the problem I can solve this by making the integer unsigned but this would only be a temporary solution, as the next iteration yields 938043756000 which is far above the 4294967296 limit.
So, is my problem the signed limit? If so, what can I do to calculate large numbers (Though I've a "LargeInteger" class I made a while ago that may be suited!) without coming across this problem again?
|
2^32 doesn't give you the limit for signed integers.
The signed integer limit is actually [2147483647](http://msdn.microsoft.com/en-us/library/296az74e(VS.80).aspx) (if you're developing on Windows using the MS tools, other toolsuites/platforms would have their own limits that are probably similar).
You'll need a C++ large number library [like this one](http://mattmccutchen.net/bigint/).
|
In addition to the other comments, I'd like to point out two serious bugs in your code.
* You have no guard against negative numbers.
* The factorial of zero is one, not zero.
|
When I calculate a large factorial, why do I get a negative number?
|
[
"",
"c++",
"signed",
"factorial",
""
] |
I have an oc4j installation bereft of any release notes or version documentation. In the absence of such documents, how do I know for sure, which version of oc4j I am using?
|
Check Server header in HTTP headers. For example with wget or curl;
```
wget -S <url-to-server>
curl -I <url-to-server>
```
or with browser, which can show HTTP headers.
There should be a header something like
```
Server: Oracle-Application-Server-10g/10.1.3.1.0 Oracle-HTTP-Server
```
|
If you have access to the OC4J JAR file, you can do:
```
java -jar oc4j.jar -version
```
|
How to determine the version of oc4j being used?
|
[
"",
"java",
"oracle",
"oc4j",
""
] |
Why does the C++ STL not provide any "tree" containers, and what's the best thing to use instead?
I want to store a hierarchy of objects as a tree, rather than use a tree as a performance enhancement...
|
There are two reasons you could want to use a tree:
You want to mirror the problem using a tree-like structure:
For this we have [boost graph library](https://www.boost.org/doc/libs/1_70_0/libs/graph/doc/index.html)
Or you want a container that has tree like access characteristics
For this we have
* [`std::map`](https://en.cppreference.com/w/cpp/container/map) (and [`std::multimap`](https://en.cppreference.com/w/cpp/container/multimap))
* [`std::set`](https://en.cppreference.com/w/cpp/container/set) (and [`std::multiset`](https://en.cppreference.com/w/cpp/container/multiset))
Basically the characteristics of these two containers is such that they practically have to be implemented using trees (though this is not actually a requirement).
See also this question:
[C tree Implementation](https://stackoverflow.com/questions/181630/whats-a-good-and-stable-c-tree-implementation)
|
Probably for the same reason that there is no tree container in boost. There are many ways to implement such a container, and there is no good way to satisfy everyone who would use it.
Some issues to consider:
* Are the number of children for a node fixed or variable?
* How much overhead per node? - ie, do you need parent pointers, sibling pointers, etc.
* What algorithms to provide? - different iterators, search algorithms, etc.
In the end, the problem ends up being that a tree container that would be useful enough to everyone, would be too heavyweight to satisfy most of the people using it. If you are looking for something powerful, [Boost Graph Library](http://www.boost.org/doc/libs/1_36_0/libs/graph/doc/table_of_contents.html) is essentially a superset of what a tree library could be used for.
Here are some other generic tree implementations:
* [Kasper Peeters' tree.hh](http://tree.phi-sci.com/)
* [Adobe's forest](http://stlab.adobe.com/group__forest__related.html)
* [core::tree](http://archive.gamedev.net/archive/reference/programming/features/coretree1/)
|
Why does the C++ STL not provide any "tree" containers?
|
[
"",
"c++",
"data-structures",
"tree",
"stl",
""
] |
For a particular application, I need the screen saver to be disabled while it's running. The operator COULD manually turn it off, and then back on later, but the easiest thing to do would be to just keep the screen saver at bay while the application is running.
How do I do this? I've found code for actually turning off the screen saver with SPI\_SETSCREENSAVEACTIVE, but I don't think that's what I want.
|
[theoldnewthing](https://devblogs.microsoft.com/oldnewthing/20090820-00/?p=17043 "Raymond Chen, The New Old Thing") has your answer: Use [`SetThreadExecutionState(ES_DISPLAY_REQUIRED)`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-setthreadexecutionstate).
This is used by video players and PowerPoint.
|
**EDIT - I have an updated answer using the modern Power Availability Request API (supersedes `SetThreadExecutionState`) here: <https://stackoverflow.com/a/63632916/67824>**
```
[FlagsAttribute]
public enum EXECUTION_STATE : uint
{
ES_SYSTEM_REQUIRED = 0x00000001,
ES_DISPLAY_REQUIRED = 0x00000002,
// Legacy flag, should not be used.
// ES_USER_PRESENT = 0x00000004,
ES_AWAYMODE_REQUIRED = 0x00000040,
ES_CONTINUOUS = 0x80000000,
}
public static class SleepUtil
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE esFlags);
}
public void PreventSleep()
{
if (SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS
| EXECUTION_STATE.ES_DISPLAY_REQUIRED
| EXECUTION_STATE.ES_SYSTEM_REQUIRED
| EXECUTION_STATE.ES_AWAYMODE_REQUIRED) == 0) //Away mode for Windows >= Vista
SleepUtil.SetThreadExecutionState(EXECUTION_STATE.ES_CONTINUOUS
| EXECUTION_STATE.ES_DISPLAY_REQUIRED
| EXECUTION_STATE.ES_SYSTEM_REQUIRED); //Windows < Vista, forget away mode
}
```
Credit: [P/Invoke](http://www.pinvoke.net/default.aspx/kernel32/SetThreadExecutionState.html), [deadpoint](https://stackoverflow.com/questions/629240/prevent-windows-from-going-into-sleep-when-my-program-is-running/629286#629286)
|
Need to disable the screen saver / screen locking in Windows C#/.Net
|
[
"",
"c#",
"screensaver",
""
] |
If I want to construct a std::string with a line like:
```
std::string my_string("a\0b");
```
Where i want to have three characters in the resulting string (a, null, b), I only get one. What is the proper syntax?
|
### Since C++14
we have been able to create [literal `std::string`](https://en.cppreference.com/w/cpp/string/basic_string/operator%22%22s)
```
#include <iostream>
#include <string>
int main()
{
using namespace std::string_literals;
std::string s = "pl-\0-op"s; // <- Notice the "s" at the end
// This is a std::string literal not
// a C-String literal.
std::cout << s << "\n";
}
```
### Before C++14
The problem is the `std::string` constructor that takes a `const char*` assumes the input is a C-string. C-strings are `\0` terminated and thus parsing stops when it reaches the `\0` character.
To compensate for this, you need to use the constructor that builds the string from a char array (not a C-String). This takes two parameters - a pointer to the array and a length:
```
std::string x("pq\0rs"); // Two characters because input assumed to be C-String
std::string x("pq\0rs",5); // 5 Characters as the input is now a char array with 5 characters.
```
Note: C++ `std::string` is **NOT** `\0`-terminated (as suggested in other posts). However, you can extract a pointer to an internal buffer that contains a C-String with the method `c_str()`.
Also check out [Doug T's answer](https://stackoverflow.com/questions/164168/how-do-you-construct-a-stdstring-with-an-embedded-null#164257) below about using a `vector<char>`.
Also check out [RiaD](https://stackoverflow.com/a/34723611/14065) for a C++14 solution.
|
If you are doing manipulation like you would with a c-style string (array of chars) consider using
```
std::vector<char>
```
You have more freedom to treat it like an array in the same manner you would treat a c-string. You can use copy() to copy into a string:
```
std::vector<char> vec(100)
strncpy(&vec[0], "blah blah blah", 100);
std::string vecAsStr( vec.begin(), vec.end());
```
and you can use it in many of the same places you can use c-strings
```
printf("%s" &vec[0])
vec[10] = '\0';
vec[11] = 'b';
```
Naturally, however, you suffer from the same problems as c-strings. You may forget your null terminal or write past the allocated space.
|
How do you construct a std::string with an embedded null?
|
[
"",
"c++",
"null",
"stdstring",
""
] |
Here's the information [according to the official documentation](http://www.php.net/manual/en/language.basic-syntax.php):
> There are four different pairs of
> opening and closing tags which can be
> used in PHP. Two of those, `<?php ?>`
> and `<script language="php"> </script>`,
> are always available. The other two
> are short tags and ASP style tags, and
> can be turned on and off from the
> php.ini configuration file. As such,
> while some people find short tags and
> ASP style tags convenient, they are
> less portable, and **generally not
> recommended**.
In my experience most servers *do* have short tags enabled. Typing
```
<?=
```
is far more convenient than typing
```
<?php echo
```
The programmers convenience is an important factor, so **why** are they not recommended?
|
There must be a clear distinction between the PHP short tag (`<?`) and shorthand echo tag (`<?=`)
The former is prohibited by the [PHP Coding standard](https://www.php-fig.org/psr/psr-1/), mostly out of common sense because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts *do* support shorttags but "lots" isn't all of them. If you want to share your scripts, it's best to use the full syntax.
Whereas the shorthand echo tag `<?=` cannot be disabled and therefore is fully acceptable to use.
I agree that `<?` is easier on programmers than `<?php` but it is possible to do a bulk find-and-replace as long as you use the same form each time.
I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them.
As ThiefMaster mentions in the comments, **[as of PHP 5.4, `<?= ... ?>` tags are supported everywhere, regardless of shorttags settings](https://www.php.net/ChangeLog-5.php#5.4.0)**. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use `<?php echo ... ?>`.
Also, you need to know that **[ASP tags <% , %> , <%= , and script tag are removed from PHP 7](https://www.php.net/manual/en/language.basic-syntax.phptags.php)**. So if you would like to support long-term portable code and would like switching to the most modern tools consider changing that parts of code.
|
I'm too fond of `<?=$whatever?>` to let it go. Never had a problem with it. I'll wait until it bites me in the ass. In all seriousness, 85% of (my) clients have access to php.ini in the **rare** occasion they are turned off. The other 15% use mainstream hosting providers, and virtually all of them have them enabled. I love 'em.
|
Are PHP short tags acceptable to use?
|
[
"",
"php",
"php-shorttags",
""
] |
I've got a list in a Python program that contains a series of numbers, which are themselves ASCII values. How do I convert this into a "regular" string that I can echo to the screen?
|
You are probably looking for 'chr()':
```
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(chr(i) for i in L)
'hello, world'
```
|
Same basic solution as others, but I personally prefer to use map instead of the list comprehension:
```
>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'
```
|
How do I convert a list of ascii values to a string in python?
|
[
"",
"python",
"string",
"ascii",
""
] |
How can I monitor the memory being used by a native C DLL that is being called from Java via JNI? Using standard Java monitoring tools and options I can see the Java memory space, but I cannot view any memory used by the C DLL. Java is using ~70MB, but the task in the Task Manager shows 200Mb+, and I'd like to see what's in that 130MB extra if possible.
|
You can monitor the native heap with counters in the performance montitor. (perfmon32) however it wont break it down for you on a per DLL basis, even jvm.dll will be included here.
Most profiling tools out there can attach to a process and capture and track memory allocations and deallocations. This allows them to speculate where leaks are.
One pretty good one i found when recently trying to track down memory leaks in native code which was called from Java is [Memory Validator](http://www.softwareverify.com/cpp/memory/index.html)
|
Have you tried using [Process Viewer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to dig deeper.
If you have the source to the DLL you could rebuild with debug libraries and possibly a mem allocation tracker - and debug using visual C++ debugger (you'll need to tell it to use the java application).
If you haven't got the source - then the options are limited.
|
Monitoring memory usage for a C DLL called with Java via JNI?
|
[
"",
"java",
"c",
"memory",
"dll",
"java-native-interface",
""
] |
I'm trying to configure my WAR project build to fail if the line or branch coverage is below given thresholds. I've been using the configuration provided on page 455 of the excellent book [Java Power Tools](http://oreilly.com/catalog/9780596527938/), but with no success. Here's the relevant snippet of my project's Maven 2 POM:
```
<build>
...
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<check>
<!-- Per-class thresholds -->
<lineRate>80</lineRate>
<branchRate>80</branchRate>
<!-- Project-wide thresholds -->
<totalLineRate>90</totalLineRate>
<totalBranchRate>90</totalBranchRate>
</check>
<executions>
<execution>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
<execution>
<id>coverage-tests</id>
<!-- The "verify" phase occurs just before "install" -->
<phase>verify</phase>
<goals>
<goal>clean</goal>
<goal>check</goal>
</goals>
</execution>
</executions>
<instrumentation>
<excludes>
<exclude>au/**/*Constants.*</exclude>
</excludes>
<ignores>
<ignore>au/**/*Constants.*</ignore>
</ignores>
</instrumentation>
</configuration>
</plugin>
...
</plugins>
...
</build>
```
As I say, the coverage report works fine, the problem is that the "install" goal isn't failing as it should if the line or branch coverage is below my specified thresholds. Does anyone have this working, and if so, what does your POM look like and which version of Cobertura and Maven are you using? I'm using Maven 2.0.9 and Cobertura 2.2.
I've tried Googling and reading the Cobertura docs, but no luck (the latter are sparse to say the least).
|
To my knowledge, *if the `<haltOnFailure>` element is set to true and any of the specified checks fails, then Cobertura will cause the build to fail* which is what you're asking for. But actually, this element defaults to `true` if you do not specify it so you **don't have to** add it to your [configuration checks](http://mojo.codehaus.org/cobertura-maven-plugin/usage.html#Check). Failing the build below any coverage threshold is (or at least should be) the default behavior.
**EDIT:** I did some further testing and `haltOnFailure` seems to be working as expected on my environment (Maven 2.2.1. and versions 2.3, 2.2, 2.1 of the plugin i.e. versions 1.9.2, 1.9, 1.8 of cobertura on Linux). I'm updating this answer with the result below.
Actually, I've added an `<execution>` element to my pom. I may be misinterpreting the part of [cobertura:check](http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html)'s documentation that says it "*Binds by default to the lifecycle phase: `verify`*" but, without the `<execution>` element, [cobertura:check](http://mojo.codehaus.org/cobertura-maven-plugin/check-mojo.html) wasn't triggered during the *verify* phase of my build. Below the setup I've use for the cobertura-maven-plugin:
```
<project>
...
<build>
...
<plugins>
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>cobertura-maven-plugin</artifactId>
<version>2.3</version>
<configuration>
<check>
<!--<haltOnFailure>true</haltOnFailure>--><!-- optional -->
<!-- Per-class thresholds -->
<lineRate>80</lineRate>
<branchRate>80</branchRate>
<!-- Project-wide thresholds -->
<totalLineRate>90</totalLineRate>
<totalBranchRate>90</totalBranchRate>
</check>
</configuration>
<executions>
<execution>
<phase>verify</phase>
<goals>
<!--<goal>clean</goal>--><!-- works if uncommented -->
<goal>check</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
```
I get the following result when running `mvn clean install` on a freshly generated maven project (with `mvn archetype:create`) patched with the plugin configuration mentioned above:
```
$ mvn archetype:create -DgroupId=com.mycompany.samples -DartifactId=cobertura-haltonfailure-testcase
...
$ mvn clean install
[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] Building cobertura-haltonfailure-testcase
[INFO] task-segment: [clean, install]
[INFO] ------------------------------------------------------------------------
[INFO] [clean:clean {execution: default-clean}]
[INFO] Deleting directory /home/pascal/Projects/cobertura-haltonfailure-testcase/target
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/classes
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Compiling 1 source file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/test-classes
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.samples.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.09 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [jar:jar {execution: default-jar}]
[INFO] Building jar: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/cobertura-haltonfailure-testcase-1.0-SNAPSHOT.jar
[INFO] Preparing cobertura:check
[WARNING] Removing: check from forked lifecycle, to prevent recursive invocation.
[INFO] [resources:resources {execution: default-resources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/main/resources
[INFO] [compiler:compile {execution: default-compile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [cobertura:instrument {execution: default}]
[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Instrumenting 1 file to /home/pascal/Projects/cobertura-haltonfailure-testcase/target/generated-classes/cobertura
Cobertura: Saved information on 1 classes.
Instrument time: 337ms
[INFO] Instrumentation was successful.
[INFO] [resources:testResources {execution: default-testResources}]
[WARNING] Using platform encoding (UTF-8 actually) to copy filtered resources, i.e. build is platform dependent!
[INFO] skip non existing resourceDirectory /home/pascal/Projects/cobertura-haltonfailure-testcase/src/test/resources
[INFO] [compiler:testCompile {execution: default-testCompile}]
[INFO] Nothing to compile - all classes are up to date
[INFO] [surefire:test {execution: default-test}]
[INFO] Surefire report directory: /home/pascal/Projects/cobertura-haltonfailure-testcase/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.mycompany.samples.AppTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.098 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO] [cobertura:check {execution: default}]
[INFO] Cobertura 1.9.2 - GNU GPL License (NO WARRANTY) - See COPYRIGHT file
Cobertura: Loaded information on 1 classes.
[ERROR] com.mycompany.samples.App failed check. Line coverage rate of 0.0% is below 80.0%
Project failed check. Total line coverage rate of 0.0% is below 90.0%
[INFO] ------------------------------------------------------------------------
[ERROR] BUILD ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Coverage check failed. See messages above.
[INFO] ------------------------------------------------------------------------
[INFO] For more information, run Maven with the -e switch
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 18 seconds
[INFO] Finished at: Sat Oct 24 21:00:39 CEST 2009
[INFO] Final Memory: 17M/70M
[INFO] ------------------------------------------------------------------------
$
```
I didn't test with maven 2.0.9, but on my machine, `haltOnFailure` generates a BUILD ERROR and halt the build. I don't see any differences with your plugin configuration, I can't reproduce the behavior you describe.
|
Add the following to the <check/> configuration.
```
<haltOnFailure>true</haltOnFailure>
```
|
How to get Cobertura to fail M2 build for low code coverage
|
[
"",
"java",
"maven-2",
"build-automation",
"code-coverage",
"cobertura",
""
] |
Could someone supply some code that would get the xpath of a System.Xml.XmlNode instance?
Thanks!
|
Okay, I couldn't resist having a go at it. It'll only work for attributes and elements, but hey... what can you expect in 15 minutes :) Likewise there may very well be a cleaner way of doing it.
It is superfluous to include the index on every element (particularly the root one!) but it's easier than trying to work out whether there's any ambiguity otherwise.
```
using System;
using System.Text;
using System.Xml;
class Test
{
static void Main()
{
string xml = @"
<root>
<foo />
<foo>
<bar attr='value'/>
<bar other='va' />
</foo>
<foo><bar /></foo>
</root>";
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
XmlNode node = doc.SelectSingleNode("//@attr");
Console.WriteLine(FindXPath(node));
Console.WriteLine(doc.SelectSingleNode(FindXPath(node)) == node);
}
static string FindXPath(XmlNode node)
{
StringBuilder builder = new StringBuilder();
while (node != null)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
builder.Insert(0, "/@" + node.Name);
node = ((XmlAttribute) node).OwnerElement;
break;
case XmlNodeType.Element:
int index = FindElementIndex((XmlElement) node);
builder.Insert(0, "/" + node.Name + "[" + index + "]");
node = node.ParentNode;
break;
case XmlNodeType.Document:
return builder.ToString();
default:
throw new ArgumentException("Only elements and attributes are supported");
}
}
throw new ArgumentException("Node was not in a document");
}
static int FindElementIndex(XmlElement element)
{
XmlNode parentNode = element.ParentNode;
if (parentNode is XmlDocument)
{
return 1;
}
XmlElement parent = (XmlElement) parentNode;
int index = 1;
foreach (XmlNode candidate in parent.ChildNodes)
{
if (candidate is XmlElement && candidate.Name == element.Name)
{
if (candidate == element)
{
return index;
}
index++;
}
}
throw new ArgumentException("Couldn't find element within parent");
}
}
```
|
Jon's correct that there are any number of XPath expressions that will yield the same node in an an instance document. The simplest way to build an expression that unambiguously yields a specific node is a chain of node tests that use the node position in the predicate, e.g.:
```
/node()[0]/node()[2]/node()[6]/node()[1]/node()[2]
```
Obviously, this expression isn't using element names, but then if all you're trying to do is locate a node within a document, you don't need its name. It also can't be used to find attributes (because attributes aren't nodes and don't have position; you can only find them by name), but it will find all other node types.
To build this expression, you need to write a method that returns a node's position in its parent's child nodes, because `XmlNode` doesn't expose that as a property:
```
static int GetNodePosition(XmlNode child)
{
for (int i=0; i<child.ParentNode.ChildNodes.Count; i++)
{
if (child.ParentNode.ChildNodes[i] == child)
{
// tricksy XPath, not starting its positions at 0 like a normal language
return i + 1;
}
}
throw new InvalidOperationException("Child node somehow not found in its parent's ChildNodes property.");
}
```
(There's probably a more elegant way to do that using LINQ, since `XmlNodeList` implements `IEnumerable`, but I'm going with what I know here.)
Then you can write a recursive method like this:
```
static string GetXPathToNode(XmlNode node)
{
if (node.NodeType == XmlNodeType.Attribute)
{
// attributes have an OwnerElement, not a ParentNode; also they have
// to be matched by name, not found by position
return String.Format(
"{0}/@{1}",
GetXPathToNode(((XmlAttribute)node).OwnerElement),
node.Name
);
}
if (node.ParentNode == null)
{
// the only node with no parent is the root node, which has no path
return "";
}
// the path to a node is the path to its parent, plus "/node()[n]", where
// n is its position among its siblings.
return String.Format(
"{0}/node()[{1}]",
GetXPathToNode(node.ParentNode),
GetNodePosition(node)
);
}
```
As you can see, I hacked in a way for it to find attributes as well.
Jon slipped in with his version while I was writing mine. There's something about his code that's going to make me rant a bit now, and I apologize in advance if it sounds like I'm ragging on Jon. (I'm not. I'm pretty sure that the list of things Jon has to learn from me is exceedingly short.) But I think the point I'm going to make is a pretty important one for anyone who works with XML to think about.
I suspect that Jon's solution emerged from something I see a lot of developers do: thinking of XML documents as trees of elements and attributes. I think this largely comes from developers whose primary use of XML is as a serialization format, because all the XML they're used to using is structured this way. You can spot these developers because they're using the terms "node" and "element" interchangeably. This leads them to come up with solutions that treat all other node types as special cases. (I was one of these guys myself for a very long time.)
This feels like it's a simplifying assumption while you're making it. But it's not. It makes problems harder and code more complex. It leads you to bypass the pieces of XML technology (like the `node()` function in XPath) that are specifically designed to treat all node types generically.
There's a red flag in Jon's code that would make me query it in a code review even if I didn't know what the requirements are, and that's `GetElementsByTagName`. Whenever I see that method in use, the question that leaps to mind is always "why does it have to be an element?" And the answer is very often "oh, does this code need to handle text nodes too?"
|
How to get xpath from an XmlNode instance
|
[
"",
"c#",
".net",
"xml",
".net-2.0",
""
] |
We've got a fairly large amount of code that just made the jump to Java 5. We've been using generics in those components targeted at being released in the Java 5 version, but the remaining code is, of course, full of raw types. I've set the compiler to generate an error for raw types and started manually clearing them, but at the present rate it'll take a *very* long time to go through with it (there are about *2500* errors). And that's with Eclipse's helpful Infer Generic Type quick fix, which always gets rid of the errors, but often generates code that needs further work.
Is there any better way to dealing with this? Are there any automated tools better than Eclipse? Any way to apply the refactoring to *all* occurences instead of doing them one-by-one? Or do you just ignore the warnings?
|
I would suggest ignoring the warnings. Otherwise, you'll be putting a lot of time into updating the legacy code without making any improvements to its functionality.
**Update:** Great comment from [Luke](https://stackoverflow.com/users/25920/luke) that I thought should get more visibility:
*"Generics are a way to catch run time bugs at compile time. Unless this legacy code has bugs in it that you think are related to casting I would leave it alone (if it ain't broke, don't fix it)"*
|
As far as I know, you're going about it as efficiently as possible. It's
obviously not perfect, but you'll finish eventually.
I recommend that you do it in stages, however; there are likely parts of the
code that would benefit more from this than others, focus on those. Trying to
do it all in one sweep runs the risk of introducing new bugs to your code. We
have one such place where we have a collection that holds context-dependent
data, and generics actually can't work for it.
Basically, do what you're doing, but do it in stages as part of other work,
instead of trying to fix it all in one throw.
|
Generics in legacy code
|
[
"",
"java",
"generics",
"migration",
"legacy-code",
""
] |
I just noticed that you can not use standard math operators on an `enum` such as `++` or `+=`.
So what is the best way to iterate through all of the values in a C++ `enum`?
|
The typical way is as follows:
```
enum Foo {
One,
Two,
Three,
Last
};
for ( int fooInt = One; fooInt != Last; fooInt++ )
{
Foo foo = static_cast<Foo>(fooInt);
// ...
}
```
Please note, the enum `Last` is meant to be skipped by the iteration. Utilizing this "fake" `Last` enum, you don't have to update your terminating condition in the for loop to the last "real" enum each time you want to add a new enum.
If you want to add more enums later, just add them before Last. The loop in this example will still work.
Of course, this breaks down if the enum values are specified:
```
enum Foo {
One = 1,
Two = 9,
Three = 4,
Last
};
```
This illustrates that an enum is not really meant to iterate through. The typical way to deal with an enum is to use it in a switch statement.
```
switch ( foo )
{
case One:
// ..
break;
case Two: // intentional fall-through
case Three:
// ..
break;
case Four:
// ..
break;
default:
assert( ! "Invalid Foo enum value" );
break;
}
```
If you really want to enumerate, stuff the enum values in a vector and iterate over that. This will properly deal with the specified enum values as well.
|
```
#include <iostream>
#include <algorithm>
namespace MyEnum
{
enum Type
{
a = 100,
b = 220,
c = -1
};
static const Type All[] = { a, b, c };
}
void fun( const MyEnum::Type e )
{
std::cout << e << std::endl;
}
int main()
{
// all
for ( const auto e : MyEnum::All )
fun( e );
// some
for ( const auto e : { MyEnum::a, MyEnum::b } )
fun( e );
// all
std::for_each( std::begin( MyEnum::All ), std::end( MyEnum::All ), fun );
return 0;
}
```
|
How can I iterate over an enum?
|
[
"",
"c++",
"enums",
""
] |
Is there explicit support for Single Table Inheritance in Django? Last I heard, the feature was still under development and debate.
Are there libraries/hacks I can use in the meantime to capture the basic behavior? I have a hierarchy that mixes different objects. The canonical example of a corporation structure with an Employee class, subclasses for types of employees, and a manager\_id (parent\_id) would be a good approximation of the problem I am solving.
In my case, I would like to represent the idea that an employee can manage other employees while being managed by a different employee. There are not separate classes for Manager and Worker, which makes this hard to spread across tables. Sub-classes would represent types of employees-programmers, accountants, sales, etc and would be independent of who supervises who (OK, I guess it's no longer a typical corporation in some respect).
|
There are currently two forms of inheritance in Django - MTI (model table inheritance) and ABC (abstract base classes).
I wrote a [tutorial](http://web.archive.org/web/20090227074910/http://thisweekindjango.com/articles/2008/jun/17/abstract-base-classes-vs-model-tab/) on what's going on under the hood.
You can also reference the official docs on [model inheritance](http://docs.djangoproject.com/en/dev/topics/db/models/#model-inheritance).
|
## Summary
Django's [proxy models](https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-models) provide the basis for Single Table Inheritance.
However, some effort is required to make it work.
Skip to the end for a re-usable example.
## Background
[Martin Fowler](https://martinfowler.com/eaaCatalog/singleTableInheritance.html) describes Single Table Inheritance (STI) as follows:
> Single Table Inheritance maps all fields of all classes of an inheritance structure into a single table.
This is precisely what Django's [proxy model inheritance](https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-models) does.
Note, that, according to this [blog post from 2010](https://lincolnloop.com/blog/using-proxy-models-customize-django-admin/), `proxy` models have been around since Django 1.1.
A "normal" Django model is a *concrete* model, i.e. it has a dedicated table in the database.
There are two types of Django model that do *not* have dedicated database tables, viz. *abstract* models and *proxy* models:
* Abstract models act as *superclasses* for concrete models. An abstract model can define fields, but it does not have a database table. The fields are only added to the database tables for its concrete subclasses.
* Proxy models act as *subclasses* for concrete models. A proxy model cannot define new fields. Instead, it operates on the database table associated with its concrete superclass. In other words, a Django concrete model and its proxies all share a single table.
Django's proxy models provide the basis for Single Table Inheritance, viz. they allow different models to share a single table, and they allow us to define proxy-specific behavior on the Python side. However, Django's default object-relational mapping (ORM) does not provide all the behavior that would be expected, so a little customization is required. How much, that depends on your needs.
Let's build a minimal example, step by step, based on the simple data-model in the figure below:
[](https://i.stack.imgur.com/xiJOA.png)
## Step 1: basic "proxy model inheritance"
Here's the content of `models.py` for a basic proxy inheritance implementation:
```
from django.db import models
class Party(models.Model):
name = models.CharField(max_length=20)
person_attribute = models.CharField(max_length=20)
organization_attribute = models.CharField(max_length=20)
class Person(Party):
class Meta:
proxy = True
class Organization(Party):
class Meta:
proxy = True
```
`Person` and `Organization` are two types of parties.
Only the `Party` model has a database table, so *all* the fields are defined on this model, including any fields that are specific either to `Person` or to `Organization`.
Because `Party`, `Person`, and `Organization` all use the `Party` database table, we can define a single `ForeignKey` field to `Party`, and assign instances of any of the three models to that field, as implied by the inheritance relation in the figure. Note, that, without inheritance, we would need a separate `ForeignKey` field for each model.
For example, suppose we define an `Address` model as follows:
```
class Address(models.Model):
party = models.ForeignKey(to=Party, on_delete=models.CASCADE)
```
We can then initialize an `Address` object using e.g. `Address(party=person_instance)` or `Address(party=organization_instance)`.
So far, so good.
However, if we try to get a list of objects corresponding to a proxy model, using e.g. `Person.objects.all()`, we get a list of *all* `Party` objects instead, i.e. both `Person` objects and `Organization` objects. This is because the proxy models still use the model manager from the superclass (i.e. `Party`).
## Step 2: add proxy model managers
To make sure that `Person.objects.all()` only returns `Person` objects, we need to assign a separate [model manager](https://docs.djangoproject.com/en/3.0/topics/db/models/#proxy-model-managers) that filters the `Party` queryset. To enable this filtering, we need a field that indicates which proxy model should be used for the object.
To be clear: creating a `Person` object implies adding a row to the `Party` table. The same goes for `Organization`. To distinguish between the two, we need a column to indicate if a row represents a `Person` or an `Organization`. For convenience and clarity, we add a field (i.e. column) called `proxy_name`, and use that to store the name of the proxy class.
So, enter the `ProxyManager` model manager and the `proxy_name` field:
```
from django.db import models
class ProxyManager(models.Manager):
def get_queryset(self):
return super().get_queryset().filter(proxy_name=self.model.__name__)
class Party(models.Model):
proxy_name = models.CharField(max_length=20)
name = models.CharField(max_length=20)
person_attribute = models.CharField(max_length=20)
organization_attribute = models.CharField(max_length=20)
def save(self, *args, **kwargs):
self.proxy_name = type(self).__name__
super().save(*args, **kwargs)
class Person(Party):
class Meta:
proxy = True
objects = ProxyManager()
class Organization(Party):
class Meta:
proxy = True
objects = ProxyManager()
```
Now the queryset returned by `Person.objects.all()` will only contain `Person` objects (and the same for `Organization`).
However, this does not work in the case of a `ForeignKey` relation to `Party`, as in `Address.party` above, because that will always return a `Party` instance, regardless of the value of the `proxy_name` field (also see [docs](https://docs.djangoproject.com/en/3.0/topics/db/models/#querysets-still-return-the-model-that-was-requested)). For example, suppose we create an `address = Address(party=person_instance)`, then `address.party` will return a `Party` instance, instead of a `Person` instance.
## Step 3: extend the `Party` constructor
One way to deal with the related-field issue is to extend the `Party.__new__` method, so it returns an instance of the class specified in the 'proxy\_name' field. The end result looks like this:
```
class Party(models.Model):
PROXY_FIELD_NAME = 'proxy_name'
proxy_name = models.CharField(max_length=20)
name = models.CharField(max_length=20)
person_attribute = models.CharField(max_length=20)
organization_attribute = models.CharField(max_length=20)
def save(self, *args, **kwargs):
""" automatically store the proxy class name in the database """
self.proxy_name = type(self).__name__
super().save(*args, **kwargs)
def __new__(cls, *args, **kwargs):
party_class = cls
try:
# get proxy name, either from kwargs or from args
proxy_name = kwargs.get(cls.PROXY_FIELD_NAME)
if proxy_name is None:
proxy_name_field_index = cls._meta.fields.index(
cls._meta.get_field(cls.PROXY_FIELD_NAME))
proxy_name = args[proxy_name_field_index]
# get proxy class, by name, from current module
party_class = getattr(sys.modules[__name__], proxy_name)
finally:
return super().__new__(party_class)
```
Now `address.party` will actually return a `Person` instance if the `proxy_name` field is `Person`.
As a last step, we can make the whole thing re-usable:
## Step 4: make it re-usable
To make our rudimentary Single-Table Inheritance implementation re-usable, we can use Django's abstract inheritance:
`inheritance/models.py`:
```
import sys
from django.db import models
class ProxySuper(models.Model):
class Meta:
abstract = True
proxy_name = models.CharField(max_length=20)
def save(self, *args, **kwargs):
""" automatically store the proxy class name in the database """
self.proxy_name = type(self).__name__
super().save(*args, **kwargs)
def __new__(cls, *args, **kwargs):
""" create an instance corresponding to the proxy_name """
proxy_class = cls
try:
field_name = ProxySuper._meta.get_fields()[0].name
proxy_name = kwargs.get(field_name)
if proxy_name is None:
proxy_name_field_index = cls._meta.fields.index(
cls._meta.get_field(field_name))
proxy_name = args[proxy_name_field_index]
proxy_class = getattr(sys.modules[cls.__module__], proxy_name)
finally:
return super().__new__(proxy_class)
class ProxyManager(models.Manager):
def get_queryset(self):
""" only include objects in queryset matching current proxy class """
return super().get_queryset().filter(proxy_name=self.model.__name__)
```
Then we can implement our inheritance structure as follows:
`parties/models.py`:
```
from django.db import models
from inheritance.models import ProxySuper, ProxyManager
class Party(ProxySuper):
name = models.CharField(max_length=20)
person_attribute = models.CharField(max_length=20)
organization_attribute = models.CharField(max_length=20)
class Person(Party):
class Meta:
proxy = True
objects = ProxyManager()
class Organization(Party):
class Meta:
proxy = True
objects = ProxyManager()
class Placement(models.Model):
party = models.ForeignKey(to=Party, on_delete=models.CASCADE)
```
More work may be required, depending on your needs, but I believe this covers some of the basics.
|
Single Table Inheritance in Django
|
[
"",
"python",
"django",
"django-models",
"single-table-inheritance",
""
] |
I am trying to detect which web in sharepoint that the user is looking at right now. One approach could be to read the URls from the browser and try to compare them to a reference URL to the sharepoint solution. I have not yet been able to locate any solution that works in both IE and Firefox.
The idea is to write a small C# app that will harvest the URLs and do the comparing.
TIA
|
It is possible to do this in a very hacky and prone to breakage way using the Win32 API function FindWindow.
The following C++ example that finds a running instance of the windows Calculator and gets the value of the edit field in it. You should be able to do something similar in C#. Disclaimer: I haven't actually checked to make sure this code compiles, sorry. :)
```
float GetCalcResult(void)
{
float retval = 0.0f;
HWND calc= FindWindow("SciCalc", "Calculator");
if (calc == NULL) {
calc= FindWindow("Calc", "Calculator");
}
if (calc == NULL) {
MessageBox(NULL, "calculator not found", "Error", MB_OK);
return 0.0f;
}
HWND calcEdit = FindWindowEx(calc, 0, "Edit", NULL);
if (calcEdit == NULL) {
MessageBox(NULL, "error finding calc edit box", "Error", MB_OK);
return 0.0f;
}
long len = SendMessage(calcEdit, WM_GETTEXTLENGTH, 0, 0) + 1;
char* temp = (char*) malloc(len);
SendMessage(calcEdit, WM_GETTEXT, len, (LPARAM) temp);
retval = atof(temp);
free(temp);
return retval;
}
```
In order to find out the right parameters to use in FindWindow and FindWindowEx, use the Visual Studio tool Spy++ to inspect a running instance of your browser window. Sorry, I don't have a code sample for web browsers on-hand, but it should be possible. Note that your solution will be Windows OS specific, and also changes to the UI architecture in future versions of the web browsers could cause your solution to stop working.
Using this method to lift the URL right out of the address bar obviously only works for the current tab. I can't see how this would work for all tabs unless you did something really tricky like simulating user input to cycle through the tabs. That would be very intrusive and a user could easily mess up your application by interrupting it with input of their own, but it might work if you're writing something that runs unattended, like an automated test script. If that is the case, you may want to look into other tools like [AutoIt](http://www.autoitscript.com/autoit3/).
This advice is all paraphrased from a [blog post](http://www.elenkist.com/bushido_burrito/blog/?p=15) I once wrote. Good luck!
|
Its fairly easy in IE using the ActiveX shell application object in Javascript. Below is the sample code:
```
function GetURL()
{
var oShell = new ActiveXObject('shell.application');
var oColl = oShell.Windows();
for (var i = 0;i<oColl.count;i++)
{
try
{
var Title = oColl(i).document.title;
if (Title.indexOf('DesiredTitle') != -1)
{
alert ('Title-'+oColl(i).document.title);
alert ('Location-'+oColl(i).location);
}
}
catch (err)
{
alert (err);
}
}
}
```
I am still trying to find out a way in firefox.
|
How do I get the URLs from any tab in any open browser
|
[
"",
"c#",
"sharepoint",
"url",
""
] |
I'm working on a large, aging code base for an MFC app. The code has been worked on by many developers over time, and as a result, we have three different ways throughout the code of dealing with the possibility of an allocation failure with new.
The first way is to test for NULL on the result of new. We don't use nothrownew.obj so this is clearly an error that needs to be cleaned up.
The second is to catch CMemoryException\* (yes, C++ exceptions are enabled in the compiler). From what I understand, MFC overrides the standard operator new, and throws this thing instead. I am fairly certain that this second method is correct in the MFC application itself. MFC overrides new, with its strange CMemoryException throwing version.
The last comes from our base of people who are good with C++, but aren't neccessarily MFC programmers. They are catching const std::bad\_alloc&.
What I really don't know is what to expect for static libraries linked into the application. This is were the vast majority of the code that uses bad\_alloc lives. Assuming these libraries are not compiled with MFC or ATL, and are written in standard C++ only, can they expect to catch bad\_alloc? Or will the presence of MFC in the application they link to infect them with the global new operator and render their attempts to fail cleanly on a bad allocation moot?
If you have an answer, could you explain how this works, or point me to the right reference to sort this out?
|
It will depend on the compile options for the static libraries to be linked to the application.
If the libraries are compiled with a configuration to use the **static** Standard C++ run-time then I would expect the `operator new` from the Standard C++ run-time to be called.
If libraries are compiled with a configuration to use the Standard C++ run-time **DLL** then the resolution of these functions will be delayed until program load and *should* be resolved to the MFC replacements of `operator new`.
I also included a link to this Herb Sutter [article](http://www.gotw.ca/publications/mill16.htm) regarding handle allocation errors that you may find useful.
|
Congratulations -- you seem to have stumped all of us. :-)
In theory, if MFC provides an overload for the global `new` function, then it should be used by *all* code in the program. But since the static libraries were compiled without knowing about that, I can't say for certain that it would.
The best I can suggest is to write some test code to find out. (I won't have access to my Windows system for the next few hours, or I'd do so myself and give you an answer.)
|
Do c++ static libraries without mfc that are linked to an MFC project throw bad_alloc or CMemoryException*?
|
[
"",
"c++",
"exception",
"mfc",
""
] |
Would you guys think that a master page should be part of the company's framework or it should be part of each application? Or perhaps the company's framework should only have a interface to provide the least functionality to all master pages ?
Currenlty we face two problems: Firstly, the original idea was to have a common layout for every and each business application. That's why the master page seats at the company's framework. Secondly, some applications needed to have a different layout, what has caused some pain as the whole logic for menus, CSS classes and etc were at the framework ...
Can you guys tell me what your thoughts are?
Thanks,
|
I would try to move UI elements like common controls into your framework libraries, and create a master page for each application *in* the application. This will give you the ability to maintain common UI elements across your applications through the use of common controls, and will provide the flexibility to create different layouts for each application.
Something else to consider is the use of different master pages in the same app for different purposes. For example, you might use one master page for internal staff, one for customers, etc. Or you might use one master page for normal browsers, and another for devices like blackberry.
|
Share some CSS and design library (templates, images, palette,) but a single shared master page is unlikely to be flexible enough.
|
Master Pages - Design question
|
[
"",
"c#",
"asp.net",
"master-pages",
""
] |
Hi I want to have two tables each have an INT "id" column which will auto-increment but I don't want either "id" columns to ever share the same number. What is this called and what's the best way to do it? Sequence? Iterator? Index? Incrementor?
Motivation: we're migrating from one schema to a another and have a web-page that reads both tables and shows the (int) ID, but I can't have the same ID used for both tables.
I'm using SQL Server 9.0.3068.
Thanks!
|
Just configure the identity increment to be >1 e.g. table one uses IDENTITY (1, 10) [1,11,21...] and table two uses IDENTITY (2, 10) [2,12,22...]. This will also give you some room for expansion if needed later.
|
I think using a [GUID](http://en.wikipedia.org/wiki/Guid) would be the most straightforward way, if I understand you correctly.
```
SELECT NEWID()
```
|
Share auto-incremented primary key between two tables
|
[
"",
"sql",
"sql-server",
""
] |
I have the following JavaScript code to pop up a window in Internet Explorer. The code is executed from a page within a Microsoft CRM modal dialog box. (RequestID is a string that is always the same in the test system - at the moment it contains "abcdefg" - without the quotes).
```
var cancelUrl = "CancelRequest.aspx?RequestID=" + RequestID;
alert("About to open a window.\n\n" + cancelUrl);
window.open(cancelUrl);
alert("Window opened");
```
I expect to see a message telling me that I am about to open a window. I then expect to see a window open and get another message about the window having been opened. I don't really care about the order of the last two events; the alerts are there so I know the code has been executed.
I have two PCs and a virtual PC. All running IE7. On the Windows 2003 VPC, the messages and pop-up appear every time without fail.
On the Vista PC and WinXP PC, the messages appear but the pop-up only appears intermittently. (I think this may be the case on the Vista PC too).
All three have identical settings in IE. All have the IE pop-up blocker disabled and have no other pop-up blockers installed.
Can anyone shed any light on this?
|
Ah, I think I got it... missed it in the description...
You are **trying to open a non-modal** window **from a modal dialog** in **IE**.
This AFAIK, should not work.
Try opening another modal window instead.
Effectively you are saying...
on window A, open up modal window B, now open up non-modal window C, which isn't really valid.
|
This code is simple. Use debugger and see what is going on.
Check that site with FireFox or Chrome, they have JS debuggers.
**Edit:**
Add try/catch block around `window.open()` and see if there is some exception there.
**Edit 2:**
I see now that you are sending characters as RequestId. You should check if that URL can handle that kind of value. Since name is `RequestId` I'd say that there is big chance that there should be numeric only parameter. If that is correct, then it can happen that server side crashes when you try to open window and then nothing happens. Reason more to set try/catch block and test.
|
Strange behaviour opening pop-up window in Internet Explorer
|
[
"",
"javascript",
"internet-explorer",
"popup",
"microsoft-dynamics",
""
] |
I have code like this:
```
class RetInterface {...}
class Ret1: public RetInterface {...}
class AInterface
{
public:
virtual boost::shared_ptr<RetInterface> get_r() const = 0;
...
};
class A1: public AInterface
{
public:
boost::shared_ptr<Ret1> get_r() const {...}
...
};
```
**This code does not compile.**
In visual studio it raises
> C2555: overriding virtual function return type differs and is not
> covariant
If I do not use `boost::shared_ptr` but return raw pointers, the code compiles (I understand this is due to [covariant return types](http://en.wikipedia.org/wiki/Parameter_covariance#C.2B.2B) in C++). I can see the problem is because `boost::shared_ptr` of `Ret1` is not derived from `boost::shared_ptr` of `RetInterface`. But I want to return `boost::shared_ptr` of `Ret1` for use in other classes, else I must cast the returned value after the return.
1. Am I doing something wrong?
2. If not, why is the language like this - it should be extensible to handle conversion between smart pointers in this scenario? Is there a desirable workaround?
|
Firstly, this is indeed how it works in C++: the return type of a virtual function in a derived class must be the same as in the base class. There is the special exception that a function that returns a reference/pointer to some class X can be overridden by a function that returns a reference/pointer to a class that derives from X, but as you note this doesn't allow for *smart* pointers (such as `shared_ptr`), just for plain pointers.
If your interface `RetInterface` is sufficiently comprehensive, then you won't need to know the actual returned type in the calling code. In general it doesn't make sense anyway: the reason `get_r` is a `virtual` function in the first place is because you will be calling it through a pointer or reference to the base class `AInterface`, in which case you can't know what type the derived class would return. If you are calling this with an actual `A1` reference, you can just create a separate `get_r1` function in `A1` that does what you need.
```
class A1: public AInterface
{
public:
boost::shared_ptr<RetInterface> get_r() const
{
return get_r1();
}
boost::shared_ptr<Ret1> get_r1() const {...}
...
};
```
Alternatively, you can use the visitor pattern or something like my [Dynamic Double Dispatch](http://www.ddj.com/dept/cpp/184429055) technique to pass a callback in to the returned object which can then invoke the callback with the correct type.
|
There is a neat solution posted in [this blog post](https://www.fluentcpp.com/2017/09/12/how-to-return-a-smart-pointer-and-use-covariance/) (from Raoul Borges)
An excerpt of the bit prior to adding support for mulitple inheritance and abstract methods is:
```
template <typename Derived, typename Base>
class clone_inherit<Derived, Base> : public Base
{
public:
std::unique_ptr<Derived> clone() const
{
return std::unique_ptr<Derived>(static_cast<Derived *>(this->clone_impl()));
}
private:
virtual clone_inherit * clone_impl() const override
{
return new Derived(*this);
}
};
class concrete: public clone_inherit<concrete, cloneable>
{
};
int main()
{
std::unique_ptr<concrete> c = std::make_unique<concrete>();
std::unique_ptr<concrete> cc = c->clone();
cloneable * p = c.get();
std::unique_ptr<clonable> pp = p->clone();
}
```
I would encourage reading the full article. Its simply written and well explained.
|
How can I use covariant return types with smart pointers?
|
[
"",
"c++",
"covariance",
"smart-pointers",
""
] |
I am using VS 2008/C# and binding a local List of helper classes as the DataSource for a DataGridView control. Calling the Remove() method on my List of helper classes fires the CellFormatting event of the DataGridView, which makes sense (a bit).
When removing whatever happens to be the DataBoundItem of the last row in the grid (so long as the grid has more than one row) the DataGridView's Rows collection is not updated before this event fires. So, in the CellFormatting event handler, I get an IndexOutOfRangeException as the Rows collection is one too large.
I've tried removing the row using the DataGridView.Rows.Remove() method, and binding using a BindingSource rather than binding the List directly as the data source.
I found a few references to this occurance via Google, but answers were either not forthcoming or said to use a Delete() method on either the DataGridView or the DataGridView.Rows collection - neither of which currently exist.
Sorting does not appear to be the issue either, as performing/not performing a sort results in the same outcome.
The only exception to the "last row" being a problem for removal is if the DataGridView contains only one row - in which case everything works fine.
|
I've had this problem in the past, and if I remember correctly there's one of two things you can do. When you remove the record from the collection, set the datasource property on your datagridview to null, and then rebind it to your list. That should do the trick.
Alternatively, you can handle the DataError event on your dataGridview and in the method you can say e.Cancel = true to suppress the exception, or you can further deal with it there.
|
First just disable the property of `Datagridview` as
```
dataGridView1.AllowUserToAddRows = false;
```
and then just remove the last rows as many rows as you want either with for loop by keeping -1.
```
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
dataGridView1.Rows.RemoveAt(dataGridView1.Rows.Count - 1);
```
|
Remove Last Row Databound DataGridView C#
|
[
"",
"c#",
"datagridview",
""
] |
What is the best way to unit test a method that doesn't return anything? Specifically in c#.
What I am really trying to test is a method that takes a log file and parses it for specific strings. The strings are then inserted into a database. Nothing that hasn't been done before but being VERY new to TDD I am wondering if it is possible to test this or is it something that doesn't really get tested.
|
If a method doesn't return anything, it's either one of the following
* **imperative** - You're either asking the object to do something to itself.. e.g change state (without expecting any confirmation.. its assumed that it will be done)
* **informational** - just notifying someone that something happened (without expecting action or response) respectively.
Imperative methods - you can verify if the task was actually performed. Verify if state change actually took place. e.g.
```
void DeductFromBalance( dAmount )
```
can be tested by verifying if the balance post this message is indeed less than the initial value by dAmount
Informational methods - are rare as a member of the public interface of the object... hence not normally unit-tested. However if you must, You can verify if the handling to be done on a notification takes place. e.g.
```
void OnAccountDebit( dAmount ) // emails account holder with info
```
can be tested by verifying if the email is being sent
*Post more details about your actual method and people will be able to answer better.*
**Update**: Your method is doing 2 things. I'd actually split it into two methods that can now be independently tested.
```
string[] ExamineLogFileForX( string sFileName );
void InsertStringsIntoDatabase( string[] );
```
String[] can be easily verified by providing the first method with a dummy file and expected strings. The second one is slightly tricky.. you can either use a Mock (google or search stackoverflow on mocking frameworks) to mimic the DB or hit the actual DB and verify if the strings were inserted in the right location. Check [this thread](https://stackoverflow.com/questions/31837/best-books-about-tdd) for some good books... I'd recomment Pragmatic Unit Testing if you're in a crunch.
In the code it would be used like
```
InsertStringsIntoDatabase( ExamineLogFileForX( "c:\OMG.log" ) );
```
|
Test its side-effects. This includes:
* Does it throw any exceptions? (If it should, check that it does. If it shouldn't, try some corner cases which might if you're not careful - null arguments being the most obvious thing.)
* Does it play nicely with its parameters? (If they're mutable, does it mutate them when it shouldn't and vice versa?)
* Does it have the right effect on the state of the object/type you're calling it on?
Of course, there's a limit to how *much* you can test. You generally can't test with every possible input, for example. Test pragmatically - enough to give you confidence that your code is designed appropriately and implemented correctly, and enough to act as supplemental documentation for what a caller might expect.
|
Unit testing void methods?
|
[
"",
"c#",
".net",
"unit-testing",
"tdd",
"void",
""
] |
Kinda long title, but anyways...
I've been looking at these examples, specifically on the parts on writing and reading the size of the message to the byte streams
<http://doc.trolltech.com/4.4/network-fortuneclient-client-cpp.html>
<http://doc.trolltech.com/4.4/network-fortuneserver-server-cpp.html>
But I can't seem to figure it out in C#.
```
StreamWriter writer = new StreamWriter(tcpClient.GetStream());
writer.Write(data.Length + data);
```
This doesn't work very well at all. Could someone give me a nudge in the right direction?
|
Generally you would send the length first. Both ends should agree on what a length looks like - for example, you might be happy to use fixed 4-byte length prefix as binary:
```
byte[] data = ...
int len = data.Length;
byte[] prefix = Bitconverter.GetBytes(len);
stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes
stream.Write(data, 0, data.Length);
```
Obviously the caller needs to do the same - i.e. read the first 4 bytes to get the length. For reading, the receiver should take care not to read too much data. One way is with a limiting stream - for example, [this class](http://code.google.com/p/protobuf-net/source/browse/trunk/protobuf-net/SubStream.cs) can be used to get a Stream that won't read too much.
If you don't want the overhead of always sending 4 bytes, then some more interesting encodings are possible - for example, using the msb as a continuation block.
For info, [protobuf-net](http://code.google.com/p/protobuf-net/) is a binary serializer designed around Google's "protocol buffers" message-based format. It handles a lot of the details for you, and might be of interest if you don't want to spend lots of time writing serialization code. There are examples for sockets in the QuickStart project, [for example here](http://code.google.com/p/protobuf-net/source/browse/trunk/QuickStart/3%20Sockets.cs)
|
Instead of `data.Length`, try:
```
writer.Write(chr(data.Length) + data);
```
This will prefix every data block with one byte indicating its length (up to 255 bytes long). As you requested, this is only a nudge. :)
Update: I just remembered that C# is all Unicode and stuff, so chr() probably gives you more than one byte. Adjust to fit.
|
C# streaming sockets, how to separate messages?
|
[
"",
"c#",
"sockets",
""
] |
How can I fetch images from a server?
I've got this bit of code which allows me to draw some images on a canvas.
```
<html>
<head>
<script type="text/javascript">
function draw(){
var canvas = document.getElementById('canv');
var ctx = canvas.getContext('2d');
for (i=0;i<document.images.length;i++){
ctx.drawImage(document.images[i],i*150,i*130);
}
}
</script>
</head>
<body onload="draw();">
<canvas id="canv" width="1024" height="1024"></canvas>
<img src="http://www.google.com/intl/en_ALL/images/logo.gif">
<img src="http://l.yimg.com/a/i/ww/beta/y3.gif">
<img src="http://static.ak.fbcdn.net/images/welcome/welcome_page_map.png">
</body>
</html>
```
Instead of looping over document.images, i would like to continually fetch images from a server.
```
for (;;) {
/* how to fetch myimage??? */
myimage = fetch???('http://myserver/nextimage.cgi');
ctx.drawImage(myimage, x, y);
}
```
|
Use the built-in [JavaScript Image object](http://www.w3schools.com/htmldom/dom_obj_image.asp).
Here is a very simple example of using the Image object:
```
myimage = new Image();
myimage.src = 'http://myserver/nextimage.cgi';
```
Here is a more appropriate mechanism for your scenario from the comments on this answer.
Thanks [olliej](https://stackoverflow.com/users/784/olliej)!
> It's worth noting that you can't synchronously request a resource, so you should actually do something along the lines of:
```
myimage = new Image();
myimage.onload = function() {
ctx.drawImage(myimage, x, y);
}
myimage.src = 'http://myserver/nextimage.cgi';
```
|
If you want to draw an image to a canvas you also need to wait for the image to actually load, so the correct thing to do will be:
```
myimage = new Image();
myimage.onload = function() {
context.drawImage(myimage, ...);
}
myimage.src = 'http://myserver/nextimage.cgi';
```
|
How to fetch a remote image to display in a canvas?
|
[
"",
"javascript",
"image",
"canvas",
""
] |
I have a class called EventConsumer which defines an event EventConsumed and a method OnEventConsumed as follows:
```
public event EventHandler EventConsumed;
public virtual void OnEventConsumed(object sender, EventArgs e)
{
if (EventConsumed != null)
EventConsumed(this, e);
}
```
I need to add attributes to the at OnEventConsumed runtime, so I'm generating a subclass using System.Reflection.Emit. What I want is the MSIL equivalent of this:
```
public override void OnEventConsumed(object sender, EventArgs e)
{
base.OnEventConsumed(sender, e);
}
```
What I have so far is this:
```
...
MethodInfo baseMethod = typeof(EventConsumer).GetMethod("OnEventConsumed");
MethodBuilder methodBuilder = typeBuilder.DefineMethod("OnEventConsumed",
baseMethod.Attributes,
baseMethod.CallingConvention,
typeof(void),
new Type[] {typeof(object),
typeof(EventArgs)});
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
// load the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Callvirt, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
...
```
I create the type, create an instance of the type, and call its OnEventConsumed function, and I get:
```
Common Language Runtime detected an invalid program.
```
...which is not exactly helpful. What am I doing wrong? What's the correct MSIL to call the base class's event handler?
|
Here's the IL from a sample app:
```
.method public hidebysig virtual instance void OnEventConsumed(object sender, class [mscorlib]System.EventArgs e) cil managed
{
.maxstack 8
L_0000: nop
L_0001: ldarg.0
L_0002: ldarg.1
L_0003: ldarg.2
L_0004: call instance void SubclassSpike.BaseClass::OnEventConsumed(object, class [mscorlib]System.EventArgs)
L_0009: nop
L_000a: ret
}
```
So I think you aren't loading the instance because you aren't doing a ldarg.0
|
I was actually really close - the problem was that I wasn't loading the 'this' argument, and that Callvirt calls the subclass method, where I actually wanted Call. So that section becomes:
```
// load 'this' and the first two args onto the stack
ilGenerator.Emit(OpCodes.Ldarg_0);
ilGenerator.Emit(OpCodes.Ldarg_1);
ilGenerator.Emit(OpCodes.Ldarg_2);
// call the base method
ilGenerator.EmitCall(OpCodes.Call, baseMethod, new Type[0] );
// return
ilGenerator.Emit(OpCodes.Ret);
```
Now it works fine.
|
What's the MSIL to call a base class's event handler?
|
[
"",
"c#",
"cil",
"reflection.emit",
""
] |
I'd like to invoke bash using a string as input. Something like:
```
sh -l -c "./foo"
```
I'd like to do this from Java. Unfortunately, when I try to invoke the command using `getRuntime().exec`, I get the following error:
```
foo": -c: line 0: unexpected EOF while looking for matching `"'
foo": -c: line 1: syntax error: unexpected end of file
```
It seems to be related to my string not being terminated with an EOF.
Is there a way to insert a platform specific EOF into a Java string? Or should I be looking for another approach, like writing to a temp script before invoking "sh" ?
|
Use this:
```
Runtime.getRuntime().exec(new String[] {"sh", "-l", "-c", "./foo"});
```
Main point: don't put the double quotes in. That's only used when writing a command-line in the shell!
e.g., `echo "Hello, world!"` (as typed in the shell) gets translated to:
```
Runtime.getRuntime().exec(new String[] {"echo", "Hello, world!"});
```
(Just forget for the moment that the shell normally has a builtin for `echo`, and is calling `/bin/echo` instead. :-))
|
Windows command lines behave differently from UNIX, Mac OS X and GNU/Linux.
On Windows the process receives the input text verbatim after the executable name (and space). It's then up to the program to parse the command line (which is usually done implicitly, the programmer is often clueless about the process).
In GNU/Linux the shell processes the command line, guaranteeing the familiar array of strings passed to C's `main` function. You don't have that shell. The best approach (even on Windows) is to **use one of the form of exec where you pass each command line argument individually in its own `String`**.
```
Process exec(String[] cmdarray)
Process exec(String[] cmdarray, String[] envp)
Process exec(String[] cmdarray, String[] envp, File dir)
```
**Or better, `java.lang.ProcessBuilder`.**
You can get a shell to do the parsing for you if you really want. This would make your example look something like (untested):
```
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "sh -l -c \"echo foo; echo bar;\""
});
```
|
Using Quotes within getRuntime().exec
|
[
"",
"java",
"exec",
"runtime.exec",
""
] |
Consider this:
```
public class TestClass {
private String a;
private String b;
public TestClass()
{
a = "initialized";
}
public void doSomething()
{
String c;
a.notify(); // This is fine
b.notify(); // This is fine - but will end in an exception
c.notify(); // "Local variable c may not have been initialised"
}
}
```
I don't get it. "b" is never initialized but will give the same run-time error as "c", which is a compile-time error. Why the difference between local variables and members?
**Edit**: making the members private was my initial intention, and the question still stands...
|
The rules for definite assignment are quite difficult (read chapter 16 of JLS 3rd Ed). It's not practical to enforce definite assignment on fields. As it stands, it's even possible to observe final fields before they are initialised.
|
The language defines it this way.
Instance variables of object type default to being initialized to null.
Local variables of object type are not initialized by default and it's a compile time error to access an undefined variable.
See section 4.12.5 for SE7 (same section still as of SE14)
<http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.12.5>
|
Uninitialized variables and members in Java
|
[
"",
"java",
"oop",
"variables",
""
] |
My database application is going to be deployed at multiple sites in different time zones.
I need a T-SQL function that will determine the UTC timestamp of midnight on January 1 of the current year for YTD calculations. All of the data is stored in UTC timestamps.
For example, Chicago is UTC-6 with Daylight Savings Time (DST), the function needs to return '2008-01-01 06:00:00' if run any time in 2008 in Chicago. If run in New York (GMT-5 + DST) next year, it needs to return '2009-01-01 05:00:00'.
I can get the current year from `YEAR(GETDATE())`. I thought I could do a `DATEDIFF` between `GETDATE()` and `GETUTCDATE()` to determine the offset but the result depends on whether the query is run during DST or not. I do not know of any built in T-SQL functions for determining the offset or whether or not the current time is DST or not?
Does anyone have a solution to this problem in T-SQL? I could hard code it or store it in a table but would prefer not to. I suppose that this is a perfect situation for using CLR Integration in SQL Server 2005. I am just wondering if there is a T-SQL solution that I am unaware of?
|
Check out this previous question and answer for related information:
[Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005](https://stackoverflow.com/questions/24797/effectively-converting-dates-between-utc-and-local-ie-pst-time-in-sql-2005#25073)
(To summarize, you do need to build time zone and DST tables in Sql Server 2005. In the next version of Sql Server we get some help with time zones.)
|
Hmm, I guess I'm not understanding the problem. If the database app is already storing UTC timestamps for all of it's transactions, and you want to sum up some values since the first of the year "local time", your condition would have to be something like:
```
(timestamp + (getutcdate() - getdate())) > cast('01/01/2008' as datetime)
```
The DST can be **on** or **off** depending on when in the year the query is run - but `getdate()` takes it into account, so you have to dynamically calculate the offset every time.
|
Determine Time Zone Offset in T-SQL
|
[
"",
"sql",
"sql-server",
"sql-server-2005",
"timezone",
""
] |
What are some strategies to achieve code separation in AJAX applications?
I am building a PHP application that I would like to have a nice AJAX front end on. I have long since learned to use some kind of templating in my PHP code to make sure I maintain good separation between my logic and display code, but I'm having trouble finding good ways to do this with the JavaScript code on the front end. I'm using jQuery to make the fetching of XML data and DOM manipulation easy, but I'm finding that the logic and layout code is starting to intermix.
The real problem is that I get XML data from the back end that then has to be reformatted and helpful text has to be wrapped around it (directions and the like). I've thought about sending over already formatted HTML, but that would require extensive reworking of the backend, and there must be a better way than what I have come up with on my own.
|
* write your templates in the HTML page, probably within a hidden element.
* fetch data via AJAX calls, i find easier to use JSON, so you don't have to 'reformat' XML, it's only data.
* apply the template to the data to generate HTML and insert into the displayed page.
check some jQuery templating plugins: [jsRepeater](http://plugins.jquery.com/project/jsrepeater), [jTemplates](http://plugins.jquery.com/project/jTemplates), [noTemplate](http://plugins.jquery.com/project/noTemplate), [Template](http://plugins.jquery.com/project/Template)
|
I've been asking similar questions lately ([here](https://stackoverflow.com/questions/251814/jquery-and-organized-code) and [here](https://stackoverflow.com/questions/247209/javascript-how-do-you-organize-this-mess)) and I've found a couple things that can help. I understand the same issues that you're finding with UI interaction being forced into code.
**1:** Write "classes" for the functionality and pass in the elements to modify in the constuctor, whether it's the ID for the element or the element itself, up to you.
**2:** Write "events" for the sections that may vary depending on the page or control. By events, I mean just placeholder methods that you can overwrite with actual functions. So for examples...
```
var FilterControl = function() {
//the "event"
var self = this;
this.onLoadComplete = function() { };
//This is the command that calls the event
this.load = function() {
//do some work
...
//Call the event
self.onLoadComplete();
};
};
//somewhere else in the code
var filter = new FilterControl();
filter.onLoadComplete = function() {
//unique calls just for this control
};
```
**3:** Get an IDE that is more Javascript friendly. I **love** my Visual Studio, but [Apanta](http://apanta.com) makes a outstanding IDE that has a really powerful Javascript IDE (it allows you to drag .JS files into a *File References* dialog so you get intellisense for all those Javascript documents solving one of the main reasons why it's hard to split up Javascript!
|
Code separation in AJAX applications
|
[
"",
"php",
"jquery",
"ajax",
""
] |
I've been working with the Joomla framework and I have noticed that they use a convention to designate private or protected methods (they put an underscore "`_`" in front of the method name), but they do not explicitly declare any methods `public`, `private`, or `protected`. Why is this? Does it have to do with portability? Are the `public`, `private`, or `protected` keywords not available in older versions of PHP?
|
public, private and protected are PHP5 keywords. unfortunately, PHP4 still has a very high install base (especially amongst shared hosting services).
here's a [pretty pic](http://www.nexen.net/images/stories/phpversion/200807/evolution.milieu.png) showing july usage rates (text in french). **spoiler**: php4 still has over a 35% usage rate sadly.
|
There's some good arguments for not using `private` methods and properties over here: <http://aperiplus.sourceforge.net/visibility.php>
Includes: makes coding and reading code harder. Makes re-using classes and debugging harder.
I'm not sold either way, but I would like to see an informed rebuttal of that article, if one exists.
|
Why not use 'protected' or 'private' in PHP?
|
[
"",
"php",
"encapsulation",
""
] |
I need to be able to receive a fax in a java application. I was wondering what are some ways of doing this. Efax? Use a fax to email provider?
|
I suggest using fax to email. I've been using [RapidFax](http://www.rapidfax.com) for the past year or so, and it is fairly inexpensive and fast. I'm happy with it.
Alternatively, there are some Web Service based fax services, like [InterFax](http://www.interfax.net).
|
We use [Ringcentral.com](http://www.ringcentral.com) which sends the fax as a PDF to an email address. We then access the PDF by accessing the POP3 account programatically (sp?).
|
How can I programmatically receive faxes? Preferable in java
|
[
"",
"java",
"fax",
""
] |
I want to make a link call a Javascript function through the onclick event and not do anything else (follow the link). What is the best way to do that? I usually do this:
```
<a href="#" onclick="foo()">Click</a>
```
But I'm not sure that is the best way and in this case it is navigating to page.html# which isn't good for what I'm doing.
|
Usually, you should always have a fall back link to make sure that clients with JavaScript disabled still has some functionality. This concept is called unobtrusive JavaScript. Example... Let's say you have the following search link:
```
<a href="search.php" id="searchLink">Search</a>
```
You can always do the following:
```
var link = document.getElementById('searchLink');
link.onclick = function() {
try {
// Do Stuff Here
} finally {
return false;
}
};
```
That way, people with javascript disabled are directed to search.php while your viewers with JavaScript view your enhanced functionality.
**Edit:** As [nickf](https://stackoverflow.com/users/9021/nickf) pointed out in comment #2, a try and catch will prevent the link to follow if there is an error in your handler.
|
Just make sure to return `false` from your onclick handler. E.g. `foo()` should be defined as:
```
function foo() {
// ... do stuff
return false;
}
```
Someone pointed out in the comments that you may need to change your HTML slightly for that to work:
```
<a href="#" onclick="return foo()">Click</a>
```
Or just put it in the HTML:
```
<a href="#" onclick="foo(); return false;">Click</a>
```
|
What is the right way to change the behavior of an <a> tag?
|
[
"",
"javascript",
"ajax",
""
] |
I have a collection of Boost unit tests I want to run as a console application.
When I'm working on the project and I run the tests I would like to be able to debug the tests, and I would like to have the console stay open after the tests run.
I see that if I run in release mode the console window stays up after the program exits, but in debug mode this is not the case.
I do not want to add 'system("pause");' or any other hacks like reading a character to my program. I just want to make Visual Studio pause after running the tests with debugging like it would if I were running in release mode. I would also like it if the output of tests were captured in one of Visual Studio's output windows, but that also seems to be harder than it should be.
How can I do this?
|
Boost test offers the following [usage recommendations for Visual Studio](http://www.boost.org/doc/libs/1_56_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html) that would enable you to run the unit tests automatically at the end of compilation and capture the output into the build window.
The nice side effect of this trick is it enable you to treat test failures as compilation errors. "...you could jump through these errors using usual keyboard shortcuts/mouse clicks you use for compilation error analysis..."
|
Try to run the application with the `Ctrl` + `F5` combination.
|
How do I make Visual Studio pause after executing a console application in debug mode?
|
[
"",
"c++",
"visual-studio",
"unit-testing",
"boost",
"console",
""
] |
I want to create an ini file to store some settings for my application. Is it a good idea to find where the jar file is located and create an ini file there? If yes, then how can I find the location of the jar file?
But if you know a better solution for something like this, I would like to hear some of them.
**EDIT**: I'm using mac and I want to run the same application in windows. I could write something in the System.getProperty("user.home") directory, but I want to keep the system clean, if the user decides to remove the app. There is no a better way to store the settings file, for example in the same directory with the application?
|
You can locate your application directory using the ClassLoader. See: [Java: finding the application directory](http://illegalargumentexception.blogspot.com/2008/04/java-finding-application-directory.html). Rather than an *.INI* file, use a *.properties* file - you can load and save this via the [Properties](http://java.sun.com/javase/6/docs/api/java/util/Properties.html) class.
As others have noted, you should not write user settings to your application directory. What if the user does not have write access to the application directory? What if your application is being used by multiple users on the same system at the same time? Neither of these situations are unusual, even on Windows.
You might still want to load some settings from the application directory - perhaps the administrator has configured default settings there.
A common convention is to save user settings to the user's home directory:
```
/home/user/.eclipse
C:\Documents and Settings\User\.eclipse
```
Although this means you might leave stray files behind, this can be beneficial if the user re-installs the app. Document such things in a README. Here is how to create and get a reference to the directory:
```
public static File getSettingsDirectory() {
String userHome = System.getProperty("user.home");
if(userHome == null) {
throw new IllegalStateException("user.home==null");
}
File home = new File(userHome);
File settingsDirectory = new File(home, ".myappdir");
if(!settingsDirectory.exists()) {
if(!settingsDirectory.mkdir()) {
throw new IllegalStateException(settingsDirectory.toString());
}
}
return settingsDirectory;
}
```
On unix-like operating systems, starting the directory name with a period (".myappdir") will make the directory hidden. On Windows, it will be located below *My Documents*, so users will not see the directory unless they go looking for it.
|
If the settings are only written by your application (rather than edited manually), consider using the [Preferences API](http://docs.oracle.com/javase/8/docs/technotes/guides/preferences/index.html).
|
How to create an .INI file to store some settings in Java?
|
[
"",
"java",
"settings",
"configuration-files",
""
] |
To save some typing and clarify my code, is there a standard version of the following method?
```
public static boolean bothNullOrEqual(Object x, Object y) {
return ( x == null ? y == null : x.equals(y) );
}
```
|
With Java 7 you can now directly do a null safe equals:
[Objects.equals(x, y)](http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html)
(The Jakarta Commons library ObjectUtils.equals() has become obsolete with Java 7)
|
if by some chance you are have access to the Jakarta Commons library there is [ObjectUtils.equals()](http://commons.apache.org/lang/apidocs/org/apache/commons/lang3/ObjectUtils.html#equals(java.lang.Object,%20java.lang.Object)) and lots of other useful functions.
EDIT: misread the question initially
|
Is there a Java standard "both null or equal" static method?
|
[
"",
"java",
"null",
"equals",
""
] |
I have a structure like this:
```
<ul>
<li>text1</li>
<li>text2</li>
<li>text3</li>
</ul>
```
How do I use javascript or jQuery to get the text as an array?
```
['text1', 'text2', 'text3']
```
My plan after this is to assemble it into a string, probably using `.join(', ')`, and get it in a format like this:
```
'"text1", "text2", "text3"'
```
|
```
var optionTexts = [];
$("ul li").each(function() { optionTexts.push($(this).text()) });
```
...should do the trick. To get the final output you're looking for, `join()` plus some concatenation will do nicely:
```
var quotedCSV = '"' + optionTexts.join('", "') + '"';
```
|
Without redundant intermediate arrays:
```
var arr = $('li').map(function(i,el) {
return $(el).text();
}).get();
```
See jsfiddle [demo](http://jsfiddle.net/cC8fT/)
|
Get an array of list element contents in jQuery
|
[
"",
"javascript",
"jquery",
""
] |
I'm using a ListView in C# to make a grid. I would like to find out a way to be able to highlight a specific cell, programatically. I only need to highlight one cell.
I've experimented with Owner Drawn subitems, but using the below code, I get highlighted cells, but no text! Are there any ideas on how to get this working? Thanks for your help.
```
//m_PC.Location is the X,Y coordinates of the highlighted cell.
void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
if ((e.ItemIndex == m_PC.Location.Y) && (e.Item.SubItems.IndexOf(e.SubItem) == m_PC.Location.X))
e.SubItem.BackColor = Color.Blue;
else
e.SubItem.BackColor = Color.White;
e.DrawBackground();
e.DrawText();
}
```
|
You can do this without owner-drawing the list:
```
// create a new list item with a subitem that has white text on a blue background
ListViewItem lvi = new ListViewItem( "item text" );
lvi.UseItemStyleForSubItems = false;
lvi.SubItems.Add( new ListViewItem.ListViewSubItem( lvi,
"subitem", Color.White, Color.Blue, lvi.Font ) );
```
The Color arguments to the ListViewSubItem constructor are controlling the foreground and background color of the subitem. The critical thing to do here is set `UseItemStyleForSubItems` to False on the list item, otherwise your color changes will be ignored.
I think your owner-draw solution would have worked as well, but you have to remember to change the text (foreground) color when you change the background to blue, otherwise the text will be hard to see.
|
Figured it out. Here's code to toggle the highlight of a specific subitem.
```
listView1.Items[1].UseItemStyleForSubItems = false;
if (listView1.Items[1].SubItems[10].BackColor == Color.DarkBlue)
{
listView1.Items[1].SubItems[10].BackColor = Color.White;
listView1.Items[1].SubItems[10].ForeColor = Color.Black;
}
else
{
listView1.Items[1].SubItems[10].BackColor = Color.DarkBlue;
listView1.Items[1].SubItems[10].ForeColor = Color.White;
}
```
|
C# ListView Detail, Highlight a single cell
|
[
"",
"c#",
"listview",
"highlight",
"ownerdrawn",
""
] |
I'm using an Informix (Version 7.32) DB. On one operation I create a temp table with the ID of a regular table and a serial column (so I would have all the IDs from the regular table numbered continuously). But I want to insert the info from the regular table ordered by ID something like:
```
CREATE TEMP TABLE tempTable (id serial, folio int );
INSERT INTO tempTable(id,folio)
SELECT 0,folio FROM regularTable ORDER BY folio;
```
But this creates a syntax error (because of the ORDER BY)
Is there any way I can order the info then insert it to the tempTable?
UPDATE: The reason I want to do this is because the regular table has about 10,000 items and in a jsp file, it has to show every record, but it would take to long, so the real reason I want to do this is to *paginate* the output. This version of Informix doesn't have `Limit` nor `Skip`. I can't renumber the serial because is in a relationship, and this is the only solution we could get a fixed number of results on one page (for example 500 results per page). In the Regular table has skipped id's (called folio) because they have been deleted. if i were to put
```
SELECT * FROM regularTable WHERE folio BETWEEN X AND Y
```
I would get maybe 300 in one page, then 500 in the next page
|
You might try it iterating a cursor over the SELECT ... ORDER BY and doing the INSERTs within the loop.
|
You can do this by breaking up the SQL into two temp tables:
```
CREATE TEMP TABLE tempTable1 (
id serial,
folio int);
SELECT folio FROM regularTable ORDER BY folio
INTO TEMP tempTable2;
INSERT INTO tempTable1(id,folio) SELECT 0,folio FROM tempTable2;
```
|
Insert into temp values (select.... order by id)
|
[
"",
"sql",
"insert",
"informix",
""
] |
When using Maven to build an executable JAR, how do I specify the JVM arguments that are used when the JAR is executed?
I can specify the main class using `<mainClass>`. I suspect there's a similar attribute for JVM arguments. Specially I need to specify the maximum memory (example -Xmx500m).
Here's my assembly plugin:
```
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.me.myApplication</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
```
Edit/Follow-up: It seems that it might not be possible to specify JVM arguments for an executable JAR according to [this](http://forums.sun.com/thread.jspa?threadID=633125&messageID=3667132) and [this](http://www.javalobby.org/forums/thread.jspa?threadID=15486&tstart=0#91817576) post.
|
I don't know of any such mechanism. The JVM configuration is specified by the calling java command.
Here's the jar file specification which conspicuously doesn't mention any attribute other than Main-Class for stand-alone execution:
<http://java.sun.com/javase/6/docs/technotes/guides/jar/jar.html>
|
First off, let me say that anything this tricky is probably hard for a reason.
This approach that may work for you if you really need it. As written, it assumes "java" is on the caller's path.
Overview:
1. Declare a Bootstrapper class as the main class in the jar's manifest.
2. The bootstrapper spawns another process in which we call java (passing in any command-line arguments you want) on the "real" main class.
3. Redirect the child processes System.out and System.err to the bootstrapper's respective streams
4. Wait for the child process to finish
Here's a [good background article](http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html).
**src/main/java/scratch/Bootstrap.java** - this class is defined in pom.xml as
the jar's mainclass: `<mainClass>scratch.Bootstrap</mainClass>`
```
package scratch;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Bootstrap {
class StreamProxy extends Thread {
final InputStream is;
final PrintStream os;
StreamProxy(InputStream is, PrintStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null) {
os.println(line);
}
} catch (IOException ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
}
private void go(){
try {
/*
* Spin up a separate java process calling a non-default Main class in your Jar.
*/
Process process = Runtime.getRuntime().exec("java -cp scratch-1.0-SNAPSHOT-jar-with-dependencies.jar -Xmx500m scratch.App");
/*
* Proxy the System.out and System.err from the spawned process back to the user's window. This
* is important or the spawned process could block.
*/
StreamProxy errorStreamProxy = new StreamProxy(process.getErrorStream(), System.err);
StreamProxy outStreamProxy = new StreamProxy(process.getInputStream(), System.out);
errorStreamProxy.start();
outStreamProxy.start();
System.out.println("Exit:" + process.waitFor());
} catch (Exception ex) {
System.out.println("There was a problem execting the program. Details:");
ex.printStackTrace(System.err);
if(null != process){
try{
process.destroy();
} catch (Exception e){
System.err.println("Error destroying process: "+e.getMessage());
}
}
}
}
public static void main(String[] args) {
new Bootstrap().go();
}
}
```
**src/main/java/scratch/App.java** - this is the normal entry point for your program
```
package scratch;
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World! maxMemory:"+Runtime.getRuntime().maxMemory() );
}
}
```
Calling: `java -jar scratch-1.0-SNAPSHOT-jar-with-dependencies.jar`
Returns:
```
Hello World! maxMemory:520290304
Exit:0
```
|
How to specify JVM argument for Maven built executable JAR
|
[
"",
"java",
"maven-2",
"jar",
"executable-jar",
""
] |
Can someone explain why there is the need to add an out or in parameter to indicate that a generic type is Co or Contra variant in C# 4.0?
I've been trying to understand why this is important and why the compiler can't just figure it out..
Thanks,
Josh
|
Eric Lippert, who works on the langauge, has a series of posts on msdn that should help clarify the issues involved:
<http://blogs.msdn.com/ericlippert/archive/tags/Covariance+and+Contravariance/default.aspx>
When reading the articles shown at that link, start at the bottom and work up.
Eventually you'll get to [#7 (Why do we need a syntax at all?)](http://blogs.msdn.com/ericlippert/archive/2007/10/29/covariance-and-contravariance-in-c-part-seven-why-do-we-need-a-syntax-at-all.aspx).
|
We don't actually *need* them, any more then we need `abstract` on classes or both `out` and `ref`. They exist just so that we, as programmers, can make our intention crystal clear, so that maintenance programmer know what we are doing, and the compiler can verify that we are doing it right.
|
Why do we need new keywords for Covariance and Contravariance in C#?
|
[
"",
"c#",
"c#-4.0",
"covariance",
"contravariance",
""
] |
I'm running into a common pattern in the code that I'm writing, where I need to wait for all threads in a group to complete, with a timeout. The timeout is supposed to be the time required for *all* threads to complete, so simply doing `Thread.Join(timeout)` for each thread won't work, since the possible timeout is then `timeout * numThreads`.
Right now I do something like the following:
```
var threadFinishEvents = new List<EventWaitHandle>();
foreach (DataObject data in dataList)
{
// Create local variables for the thread delegate
var threadFinish = new EventWaitHandle(false, EventResetMode.ManualReset);
threadFinishEvents.Add(threadFinish);
var localData = (DataObject) data.Clone();
var thread = new Thread(
delegate()
{
DoThreadStuff(localData);
threadFinish.Set();
}
);
thread.Start();
}
Mutex.WaitAll(threadFinishEvents.ToArray(), timeout);
```
However, it seems like there should be a simpler idiom for this sort of thing.
|
I still think using Join is simpler. Record the expected completion time (as Now+timeout), then, in a loop, do
```
if(!thread.Join(End-now))
throw new NotFinishedInTime();
```
|
With .NET 4.0 I find [System.Threading.Tasks](http://msdn.microsoft.com/en-us/library/dd235608.aspx) a lot easier to work with. Here's spin-wait loop which works reliably for me. It blocks the main thread until all the tasks complete. There's also [Task.WaitAll](http://msdn.microsoft.com/en-us/library/dd270695.aspx), but that hasn't always worked for me.
```
for (int i = 0; i < N; i++)
{
tasks[i] = Task.Factory.StartNew(() =>
{
DoThreadStuff(localData);
});
}
while (tasks.Any(t => !t.IsCompleted)) { } //spin wait
```
|
Waiting for all threads to complete, with a timeout
|
[
"",
"c#",
"multithreading",
""
] |
What is the best way to refresh a `DataGridView` when you update an underlying data source?
I'm updating the datasource frequently and wanted to display the outcome to the user as it happens.
I've got something like this (and it works), but setting the `DataGridView.DataSource` to `null` doesn't seem like the right way.
```
List<ItemState> itemStates = new List<ItemState>();
dataGridView1.DataSource = itemStates;
for (int i = 0; i < 10; i++) {
itemStates.Add(new ItemState { Id = i.ToString() });
dataGridView1.DataSource = null;
dataGridView1.DataSource = itemStates;
System.Threading.Thread.Sleep(500);
}
```
|
Well, it doesn't get much better than that. Officially, you should use
```
dataGridView1.DataSource = typeof(List);
dataGridView1.DataSource = itemStates;
```
It's still a "clear/reset source" kind of solution, but I have yet to find anything else that would reliably refresh the DGV data source.
|
I ran into this myself. My recommendation: If you have ownership of the datasource, don't use a [List](https://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). Use a [BindingList](https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx). The [BindingList](https://msdn.microsoft.com/en-us/library/ms132679(v=vs.110).aspx) has events that fire when items are added or changed, and the [DataGridView](https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx) will automatically update itself when these events are fired.
|
Refresh DataGridView when updating data source
|
[
"",
"c#",
".net",
"winforms",
"datagridview",
""
] |
What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?
|
```
date('Z');
```
returns the UTC offset in seconds.
|
```
// will output something like +02:00 or -04:00
echo date('P');
```
|
UTC Offset in PHP
|
[
"",
"php",
"timezone",
"utc",
""
] |
For example VK\_LEFT, VK\_DELETE, VK\_ESCAPE, VK\_RETURN, etc. How and where are they declared? Are they constants, #defines, or something else? Where do they come from?
If possible, please provide a file name/path where they are declared. Or some other info as specific as possible.
|
These are declared using `#define` in the file `winuser.h` in the Platform SDK. In my installation of Visual Studio 2008, the full path is
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\Include\WinUser.h
```
|
There are also online copies of winuser.h , very handy sometimes :
<http://www.woodmann.com/fravia/sources/WINUSER.H>
<http://doc.ddart.net/msdn/header/include/winuser.h.html>
A bit of googling will get you more of those.
|
How are Windows VK_ constants declared?
|
[
"",
"c++",
"windows",
"winapi",
""
] |
This is just to satisfy my own curiosity.
Is there an implementation of this:
```
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f3759df - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
return x;
}
```
in C#? If it exists, post the code.
I guess I should have mentioned I was looking for a "safe" implementation... Either way, the BitConverter code solves the problem. The union idea is interesting. I'll test it and post my results.
Edit:
As expected, the unsafe method is the quickest, followed by using a union (inside the function), followed by the BitConverter. The functions were executed 10000000 times, and the I used the System.Diagnostics.Stopwatch class for timing. The results of the calculations are show in brackets.
```
Input: 79.67
BitConverter Method: 00:00:01.2809018 (0.1120187)
Union Method: 00:00:00.6838758 (0.1120187)
Unsafe Method: 00:00:00.3376401 (0.1120187)
```
For completeness, I tested the built-in Math.Pow method, and the "naive" method (1/Sqrt(x)).
```
Math.Pow(x, -0.5): 00:00:01.7133228 (0.112034710535584)
1 / Math.Sqrt(x): 00:00:00.3757084 (0.1120347)
```
The difference between 1 / Math.Sqrt() is so small that I don't think one needs to resort to the Unsafe Fast InvSqrt() method in C# (or any other unsafe method). Unless one *really* needs to squeeze out that last bit of juice from the CPU... 1/Math.Sqrt() is also much more accurate.
|
You should be able to use the StructLayout and FieldOffset attributes to fake a union for plain old data like floats and ints.
```
[StructLayout(LayoutKind.Explicit, Size=4)]
private struct IntFloat {
[FieldOffset(0)]
public float floatValue;
[FieldOffset(0)]
public int intValue;
// redundant assignment to avoid any complaints about uninitialized members
IntFloat(int x) {
floatValue = 0;
intValue = x;
}
IntFloat(float x) {
intValue = 0;
floatValue = x;
}
public static explicit operator float (IntFloat x) {
return x.floatValue;
}
public static explicit operator int (IntFloat x) {
return x.intValue;
}
public static explicit operator IntFloat (int i) {
return new IntFloat(i);
}
public static explicit operator IntFloat (float f) {
return new IntFloat(f);
}
}
```
Then translating InvSqrt is easy.
|
Use [BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) if you want to avoid unsafe code.
```
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.SingleToInt32Bits(x);
i = 0x5f3759df - (i >> 1);
x = BitConverter.Int32BitsToSingle(i);
x = x * (1.5f - xhalf * x * x);
return x;
}
```
The code above uses new methods introduced in .NET Core 2.0. For .NET Framework, you have to fall back to the following (which performs allocations):
```
float InvSqrt(float x)
{
float xhalf = 0.5f * x;
int i = BitConverter.ToInt32(BitConverter.GetBytes(x), 0);
i = 0x5f3759df - (i >> 1);
x = BitConverter.ToSingle(BitConverter.GetBytes(i), 0);
x = x * (1.5f - xhalf * x * x);
return x;
}
```
Otherwise, the C# code is exactly the same as the C code you gave, except that the method needs to be marked as unsafe:
```
unsafe float InvSqrt(float x) { ... }
```
|
Is it possible to write Quake's fast InvSqrt() function in C#?
|
[
"",
"c#",
""
] |
I'm making a program that fits the wizard concept ideally; the user is walked through the steps to create a character for a game.
However, I'm realizing that the limitations of the wizard are making it difficult to design "elegant" logic flow. For example, because all pages of the wizard are initalized at the same time, I can't have the values entered in one page available to the next one. I have to put a button on each page to get the values from a previous page rather than simply having fields auto-populated.
I've thought about alternatives to using the wizard. I think the best idea is to have some buttons on one panel that change the information on another panel, e.g. a splitter window.
However, I can't find any documentation in wxPython on how to dynamically change the panel. Everything I've found so far is really pretty static, hence the use of the wizard. Even the "wxPython in Action" book doesn't mention it.
Are there any tutorials for making "dynamic panels" or better management of a wizard?
|
Here is a simple example. This way you can make your "wizard" work like a finite state machine where states are different pages that are initialized on demand. Also, the data is shared between pages.
```
import wx
import wx.lib.newevent
(PageChangeEvent, EVT_PAGE_CHANGE) = wx.lib.newevent.NewEvent()
class Data:
foo = None
bar = None
class Page1(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 1 - foo")
self.foo = wx.TextCtrl(self)
goto_page2 = wx.Button(self, label="Go to page 2")
for c in (label, self.foo, goto_page2):
sizer.Add(c, 0, wx.TOP, 5)
goto_page2.Bind(wx.EVT_BUTTON, self.OnPage2)
def OnPage2(self, event):
self.data.foo = self.foo.Value
wx.PostEvent(self.parent, PageChangeEvent(page=Page2))
class Page2(wx.Panel):
def __init__(self, parent, data):
wx.Panel.__init__(self, parent)
self.parent = parent
self.data = data
sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(sizer)
label = wx.StaticText(self, label="Page 2 - bar")
self.bar = wx.TextCtrl(self)
goto_finish = wx.Button(self, label="Finish")
for c in (label, self.bar, goto_finish):
sizer.Add(c, 0, wx.TOP, 5)
goto_finish.Bind(wx.EVT_BUTTON, self.OnFinish)
def OnFinish(self, event):
self.data.bar = self.bar.Value
wx.PostEvent(self.parent, PageChangeEvent(page=finish))
def finish(parent, data):
wx.MessageBox("foo = %s\nbar = %s" % (data.foo, data.bar))
wx.GetApp().ExitMainLoop()
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
self.data = Data()
self.current_page = None
self.Bind(EVT_PAGE_CHANGE, self.OnPageChange)
wx.PostEvent(self, PageChangeEvent(page=Page1))
def OnPageChange(self, event):
page = event.page(self, self.data)
if page == None:
return
if self.current_page:
self.current_page.Destroy()
self.current_page = page
page.Layout()
page.Fit()
page.Refresh()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
```
|
The wxPython demo has an example of a "dynamic" wizard. Pages override GetNext() and GetPrev() to show pages dynamically. This shows the basic technique; you can extend it to add and remove pages, change pages on the fly, and rearrange pages dynamically.
The wizard class is just a convenience, though. You can modify it, or create your own implementation. A style that seems popular nowadays is to use an HTML-based presentation; you can emulate this with the wxHtml control, or the IEHtmlWindow control if your app is Windows only.
|
Alternatives to a wizard
|
[
"",
"python",
"wxpython",
"wizard",
""
] |
Considering the criteria listed below, which of Python, Groovy or Ruby would you use?
* *Criteria (Importance out of 10, 10 being most important)*
* Richness of API/libraries available (eg. maths, plotting, networking) (9)
* Ability to embed in desktop (java/c++) applications (8)
* Ease of deployment (8)
* Ability to interface with DLLs/Shared Libraries (7)
* Ability to generate GUIs (7)
* Community/User support (6)
* Portability (6)
* Database manipulation (3)
* Language/Semantics (2)
|
I think it's going to be difficult to get an objective comparison. I personally prefer Python. To address one of your criteria, Python was designed from the start to be an embeddable language. It has a very rich C API, and the interpreter is modularized to make it easy to call from C. If Java is your host environment, you should look at Jython, an implementation of Python inside the Java environment (VM and libs).
|
Having worked with all 3 of them, this is what I can say:
* **Python**
+ has very mature libraries
+ libraries are documented
+ documentation can be accessed from your debugger/shell at runtime through the docstrings
+ you can develop code without an IDE
* **Ruby**
+ has some great libraries ( even though some are badly documented )
+ Ruby's instrospection mechanisms are great. They make writing code pretty easy ( even if documentation is not available )
+ you can develop code without an IDE
* **Groovy**
+ you can benefit from everything Java has to offer
+ syntax is somewhat inspired from Ruby
+ it's hard to write code without an IDE. You have no way to debug stuff from your console ( this is something you can easily do in Python/Ruby ) and the available Groovy plugins have a lot of catching up to do. I wrote some apps using Groovy and as they get bigger I regret not going with Ruby/Python ( debugging would have been WAY more easier ). If you'll only develop from an IDE, Groovy's a cool language.
|
Python vs Groovy vs Ruby? (based on criteria listed in question)
|
[
"",
"python",
"ruby",
"scripting",
"groovy",
""
] |
At the moment I use PHP for almost everything I develop for the Web but its linguistic limitations are starting to annoy me. However, as I developed some practices and maintain some PHP libraries that help me a lot, I don't feel I'd be ready to just switch to LISP throwing away all my PHP output. It could even be impossible on the servers where all I have access to is a regular LAMP hosting account.
Ergo, my questions are:
Could LISP code be just combined with PHP one? Are there solutions for side-by-side LISP/PHP, interface for their interoperability or perphaps just an implementation of one for the other? Or is it a mutually exclusive choice?
|
It's not a mutually-exclusive choice, you can run both on one system, in the same way that perl and php (for example) are run side-by-side on many systems.
There's a [good post here](http://ubuntuforums.org/archive/index.php/t-277873.html) on a similar topic, which suggests using sockets to communicate between both languages -
> If you want to go the PHP<->Lisp route the easyest thing to do would be to make PHP communicate with your Lisp-process using sockets.
>
> <http://php.net/manual/en/ref.sockets.php>
>
> <http://www.sbcl.org/manual/Networking.html>
This approach does still leave you with the potential added complexity and maintenance issues you get from having 2 languages in your project, but might be a fit for your particular use case.
|
You would most likely not want to write code in PHP once you've started developing in Lisp. (New capitalization since circa 80s, by the way)
Hunchentoot is a popular server that gives you the basics in terms of connecting dispatchers to requests. There's a series of [screencasts on writing a reddit clone](http://lispcast.com/drupal/node/3) at LispCast.com
[UnCommon Web](http://common-lisp.net/project/ucw/) (sounds like a pun on Peter Norvig's description of Scheme in PAIP) is from what I can tell a more complete framework based heavily on the idea of continuations, much like [Seaside](http://seaside.st) for Smalltalk.
[Weblocks](http://common-lisp.net/project/cl-weblocks/) is yet another continuation-based web framework that looks nice. The author (at `defmacro.org`) writes good articles, and I like what I've seen in the sample app for Weblocks.
|
Combining Lisp and PHP code in the same application
|
[
"",
"php",
"web-applications",
"interop",
"lisp",
""
] |
I've been developing a GUI library for Windows (as a personal side project, no aspirations of usefulness). For my main window class, I've set up a hierarchy of option classes (using the [Named Parameter Idiom](http://www.parashift.com/c++-faq-lite/named-parameter-idiom.html)), because some options are shared and others are specific to particular types of windows (like dialogs).
The way the Named Parameter Idiom works, the functions of the parameter class have to return the object they're called on. The problem is that, in the hierarchy, each one has to be a *different* class -- the `createWindowOpts` class for standard windows, the `createDialogOpts` class for dialogs, and the like. I've dealt with that by making all the option classes templates. Here's an example:
```
template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
public: ///////////////////////////////////////////////////////////////
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return static_cast<optType&>(*this); }; // Where to put the upper-left corner of the window; if not specified, the system sets it to a default position
optType& at(int x, int y, int width, int height) { mX=x; mY=y; mWidth=width; mHeight=height; return static_cast<optType&>(*this); }; // Sets the position and size of the window in a single call
optType& background(HBRUSH b) { mBackground=b; return static_cast<optType&>(*this); }; // Sets the default background to this brush
optType& background(INT_PTR b) { mBackground=HBRUSH(b+1); return static_cast<optType&>(*this); }; // Sets the default background to one of the COLOR_* colors; defaults to COLOR_WINDOW
optType& cursor(HCURSOR c) { mCursor=c; return static_cast<optType&>(*this); }; // Sets the default mouse cursor for this window; defaults to the standard arrow
optType& hidden() { mStyle&=~WS_VISIBLE; return static_cast<optType&>(*this); }; // Windows are visible by default
optType& icon(HICON iconLarge, HICON iconSmall=0) { mIcon=iconLarge; mSmallIcon=iconSmall; return static_cast<optType&>(*this); }; // Specifies the icon, and optionally a small icon
// ...Many others removed...
};
template <class T>
class _createWindowOpts: public _sharedWindowOpts<T> {
public: ///////////////////////////////////////////////////////////////
_createWindowOpts() { };
// These can't be used with child windows, or aren't needed
optType& menu(HMENU m) { mMenuOrId=m; return static_cast<optType&>(*this); }; // Gives the window a menu
optType& owner(HWND hwnd) { mParentOrOwner=hwnd; return static_cast<optType&>(*this); }; // Sets the optional parent/owner
};
class createWindowOpts: public _createWindowOpts<createWindowOpts> {
public: ///////////////////////////////////////////////////////////////
createWindowOpts() { };
};
```
It works, but as you can see, it requires a noticeable amount of extra work: a type-cast on the return type for each function, extra template classes, etcetera.
My question is, is there an easier way to implement the Named Parameter Idiom in this case, one that doesn't require all the extra stuff?
|
Maybe not what you want to hear, but I for one think it's ok to have lots of ugly type-casts and template parameters in library-code that's (more or less) hidden from the client *as long as* it is safe *and* makes the life of the client a lot easier. The beauty in library code is not in the code itself, but in the code it enables the clients to write. Take STL for example.
I've also developed a small GUI-library as a personal project with basically the same aspirations as you and some of the code gets pretty ugly in it, but in the end it allows me to write beautiful client code (at least in my (possibly perverted) eyes) and that's what counts IMHO.
|
How about...?
```
template <class T>
class _sharedWindowOpts: public detail::_baseCreateWindowOpts {
protected: // (protected so the inheriting classes may also use it)
T & me() { return static_cast<T&>(*this); } // !
public:
// No required parameters in this case.
_sharedWindowOpts() { };
typedef T optType;
// Commonly used options
optType& at(int x, int y) { mX=x; mY=y; return me(); }; // !
// ...
};
```
|
Better Way To Use C++ Named Parameter Idiom?
|
[
"",
"c++",
"named-parameters",
""
] |
That's it. It's a dumb dumb (embarrassing!) question, but I've never used C# before, only C++ and I can't seem to figure out how to access a Label on my main form from a secondary form and change the text. If anybody can let me know real quick what to do I'd be so grateful!
BTW, I should really clarify. Sorry: I've got two separate .cs files that each look about like below. I was using the [Designer] in VS2008 to add in the label in Form1. When I type something like Form1.label1 it doesn't understand. The dropdown shows a list of methods and properties for Form1, but there's only about 7, like ControlCollection, Equals, MouseButtons, and a couple others... I can publicly define a variable in Form1 and that shows, but I don't know how to access the label...
```
namespace AnotherProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
```
|
You'll need a reference to the instance of Form1 - for example, if it's Form1 which is constructing Form2, you might pass `this` in as a constructor parameter.
Then you'll need to either expose the label of Form1 via a property (or - ick! - a non-private field) or write a method/property which will set the text of the label. For example:
```
public class Form1 : Form
{
private Label label;
// Construction etc as normal
public string LabelText
{
get { return label.Text; }
set { label.Text = value; }
}
public Form2 CreateForm2()
{
return new Form2(this);
}
}
public class Form2 : Form
{
private Form1 form1;
public Form2(Form1 form1)
{
this.form1 = form1;
// Normal construction
}
public void SayHello()
{
form1.LabelText = "Hello";
}
}
```
|
You have to have a reference to Form1 from Form2. Then you need either a method or a property on Form 1 visible to Form2 that changes the label text to "Hello".
|
How can I make a label on Form1 say "Hello" from form2?
|
[
"",
"c#",
""
] |
Usually, I need to retrieve data from a table in some range; for example, a separate page for each search result. In MySQL I use LIMIT keyword but in DB2 I don't know. Now I use this query for retrieve range of data.
```
SELECT *
FROM(
SELECT
SMALLINT(RANK() OVER(ORDER BY NAME DESC)) AS RUNNING_NO
, DATA_KEY_VALUE
, SHOW_PRIORITY
FROM
EMPLOYEE
WHERE
NAME LIKE 'DEL%'
ORDER BY
NAME DESC
FETCH FIRST 20 ROWS ONLY
) AS TMP
ORDER BY
TMP.RUNNING_NO ASC
FETCH FIRST 10 ROWS ONLY
```
but I know it's bad style. So, how to query for highest performance?
|
My requirement have been added into DB2 9.7.2 already.
DB2 9.7.2 adds new syntax for limit query result as illustrate below:
```
SELECT * FROM TABLE LIMIT 5 OFFSET 20
```
the database will retrieve result from row no. 21 - 25
|
It's very difficult, it is depends which database do you have.
for example:
```
SELECT * FROM (
SELECT
ROW_NUMBER() OVER (ORDER BY ID_USER ASC) AS ROWNUM,
ID_EMPLOYEE, FIRSTNAME, LASTNAME
FROM EMPLOYEE
WHERE FIRSTNAME LIKE 'DEL%'
) AS A WHERE A.rownum
BETWEEN 1 AND 25
```
|
How to query range of data in DB2 with highest performance?
|
[
"",
"sql",
"database",
"pagination",
"db2",
""
] |
There is another recent Project Euler question but I think this is a bit more specific (I'm only really interested in PHP based solutions) so I'm asking anyway.
[Question #5](http://projecteuler.net/index.php?section=problems&id=5) tasks you with: "What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?"
Now, I have solved it twice. Once very inefficiently and once much more efficiently but I am still far away from an especially sophisticated answer (and I am not especially solid in math hence my brute force solution). I can see a couple of areas where I could improve this but I am wondering if any of you could demonstrate a more efficient solution to this problem.
\*spoiler: Here is my less than optimal (7 seconds to run) but still tolerable solution (not sure what to do about the double $... just pretend you only see 1...
```
function euler5(){
$x = 20;
for ($y = 1; $y < 20; $y++) {
if (!($x%$y)) {
} else {
$x+=20;
$y = 1;
}
}echo $x;
};
```
|
in php it will look like this:
```
<?php
function gcd($a,$b) {
while($a>0 && $b>0) {
if($a>$b) $a=$a-$b; else $b=$b-$a;
}
if($a==0) return $b;
return $a;
}
function euler5($i=20) {
$euler=$x=1;
while($x++<$i) {
$euler*=$x/gcd($euler,$x);
}
return $euler;
}
?>
```
Its at least twice as fast than what you posted.
|
Collect prime factors for all numbers between 1 and 20. Counting the maximal exponents of each prime factor, we have `16 = 2**4`, `9 = 3**2`, as well as 5, 7, 11, 13, 17, 19 (each appearing only once). Multiply the lot, and you have your answer.
|
A Project Euler Puzzler (specifically in PHP)
|
[
"",
"php",
"math",
"puzzle",
""
] |
I've got a little c# windows service that periodically pulls xml from a web service and stores the data in a database table.
Unfortunately it's failing because the web service has occasional bad data in it - strings instead of decimals. I don't have any control over the web service (unvalidated user input from software we can't change) but I would like to log the bad data so that it can be re-input.
It's simple data that looks something like this:
```
<ROWS>
<ROW>
<COL1>5405</COL1>
<COL2>102.24</COL1>
</ROW>
<ROW>
<COL1>5406</COL1>
<COL2>2.25</COL1>
</ROW>
</ROWS>
```
The table just has two columns, COL1 (NUMBER, 10), COL2 (NUMBER, 10,2).
I was using a validating XmlReader and this XSD:
```
<?xml version="1.0" encoding="utf-8"?>
<xs:schema id="ROWS" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="ROWS" msdata:IsDataSet="true" msdata:Locale="en-US">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="ROW">
<xs:complexType>
<xs:sequence>
<xs:element name="COL1" type="xs:decimal" minOccurs="0" />
<xs:element name="COL2" type="xs:decimal" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
```
then a dataset.ReadXml() and Update()ing the dataset.
Whenever it hits bad data I get the following exception:
> System.Xml.Schema.XmlSchemaValidationException
> was unhandled
>
> Message="The 'COL1'
> element is invalid - The value 'A40'
> is invalid according to its datatype
> '<http://www.w3.org/2001/XMLSchema:decimal>'
> - The string 'A40' is not a valid Decimal value."
I can think of several ways of ways of getting around the problem but they all feel like a bit of a kludge and I'd like to learn something more elegant, and improve my knowledge. Here's what I've come up with so far:
* Pre-process the XML provided by the web service before loading into the validating XML reader, removing any bad nodes entirely.
* Catch the XmlSchemaValidationExceptions and try to continue from them gracefully (not sure about that one)
* Don't use a validating XML reader, but instead catch exceptions when loading the unvalidated xml into the dataset. (again not sure about that)
* have string columns in the dataset, and ignore bad data until I update it, and catch anything the database rejects.
* go and stand over the users with a large mallet until they learn to get it right first time (too time consuming)
* something else?
**UPDATE:** The data can be bad because it comes from a application that doesn't validate the user input for COL1 - but the numbers in COL2 are calculated correctly, and COL1 should correspond with a different system. Any invalid entries should be recorded so they can be corrected. After the data is written to the database, another system verifies that COL1 is valid, and the users will soon spot if it doesn't show correctly in the other system - they used to load it by hand anyway :)
|
> Pre-process the XML provided by the
> web service before loading into the
> validating XML reader, removing any
> bad nodes entirely.
This is the option I would choose, it would allow you to grab the bad input before the exception and store it somewhere so it can be looked at later. Then you can find the offending user and use another of your methods
> go and stand over the users with a
> large mallet until they learn to get
> it right first time
|
The question for me is: What do you want to do with the erroneus data?
Do you want to ignore it, sanitize it (remove the 'A' from 'A40'), or collect it to one day finally show it to the users (speaking of a large mallet;-) ?
If you just want to leave out any rows with incorrect data, the strip out the ones with errors before doing anything else. You have to decide yourself if you still need to validate the remaining xml before entering it into the DB. If you do the stripping in a restrictive way, it should no longer be necessary.
|
right approach to handling bad xml data
|
[
"",
"c#",
"xml",
"xsd",
"xmlreader",
"xmlschemaset",
""
] |
I have this code
```
#include <iostream>
using namespace std;
int main(int argc,char **argv) {
unsigned long long num1 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999995LL;
unsigned long long num2 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999996LL;
unsigned long long num3 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999997LL;
unsigned long long num4 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999998LL;
unsigned long long num5 = 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999LL;
cout << (unsigned long long)(num1 * num2 * num3 * num4 * num5) << endl;
return 0;
}
```
As you can see the numbers are enormous, but when I do the math there I get this:
18446744073709551496
At compile time I get these warnings:
```
warning: integer constant is too large for its type|
In function `int main(int, char**)':|
warning: this decimal constant is unsigned only in ISO C90|
...
```
|
Your result is larger than the long long type - you need to look at a [BigInteger](http://mattmccutchen.net/bigint/) or arbitrary precision library, something like [gmp](http://gmplib.org/)
|
Those numbers won't fit into any C++ data types. If you just want to print them, store the numbers in a string. If you want to do math on it, find an arbitrary precision math library and use that.
|
How to print really big numbers in C++
|
[
"",
"c++",
"biginteger",
"limits",
""
] |
Given a string of keywords, such as "Python best practices", I would like to obtain the first 10 Stack Overflow questions that contain that keywords, sorted by relevance (?), say from a Python script. My goal is to end up with a list of tuples (title, URL).
How can I accomplish this? Would you consider querying Google instead? (How would you do it from Python?)
|
```
>>> from urllib import urlencode
>>> params = urlencode({'q': 'python best practices', 'sort': 'relevance'})
>>> params
'q=python+best+practices&sort=relevance'
>>> from urllib2 import urlopen
>>> html = urlopen("http://stackoverflow.com/search?%s" % params).read()
>>> import re
>>> links = re.findall(r'<h3><a href="([^"]*)" class="answer-title">([^<]*)</a></h3>', html)
>>> links
[('/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines “pythonian” or “pythonic”?'), ('/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]
>>> from urlparse import urljoin
>>> links = [(urljoin('http://stackoverflow.com/', url), title) for url,title in links]
>>> links
[('http://stackoverflow.com/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150', 'What are the best RSS feeds for programmers/developers?'), ('http://stackoverflow.com/questions/3088/best-ways-to-teach-a-beginner-to-program#13185', 'Best ways to teach a beginner to program?'), ('http://stackoverflow.com/questions/13678/textual-versus-graphical-programming-languages#13886', 'Textual versus Graphical Programming Languages'), ('http://stackoverflow.com/questions/58968/what-defines-pythonian-or-pythonic#59877', 'What defines “pythonian” or “pythonic”?'), ('http://stackoverflow.com/questions/592/cxoracle-how-do-i-access-oracle-from-python#62392', 'cx_Oracle - How do I access Oracle from Python? '), ('http://stackoverflow.com/questions/7170/recommendation-for-straight-forward-python-frameworks#83608', 'Recommendation for straight-forward python frameworks'), ('http://stackoverflow.com/questions/100732/why-is-if-not-someobj-better-than-if-someobj-none-in-python#100903', 'Why is if not someobj: better than if someobj == None: in Python?'), ('http://stackoverflow.com/questions/132734/presentations-on-switching-from-perl-to-python#134006', 'Presentations on switching from Perl to Python'), ('http://stackoverflow.com/questions/136977/after-c-python-or-java#138442', 'After C++ - Python or Java?')]
```
Converting this to a function should be trivial.
**EDIT**: Heck, I'll do it...
```
def get_stackoverflow(query):
import urllib, urllib2, re, urlparse
params = urllib.urlencode({'q': query, 'sort': 'relevance'})
html = urllib2.urlopen("http://stackoverflow.com/search?%s" % params).read()
links = re.findall(r'<h3><a href="([^"]*)" class="answer-title">([^<]*)</a></h3>', html)
links = [(urlparse.urljoin('http://stackoverflow.com/', url), title) for url,title in links]
return links
```
|
Since Stackoverflow already has this feature you just need to get the contents of the search results page and scrape the information you need. Here is the URL for a search by relevance:
> <https://stackoverflow.com/search?q=python+best+practices&sort=relevance>
If you View Source, you'll see that the information you need for each question is on a line like this:
```
<h3><a href="/questions/5119/what-are-the-best-rss-feeds-for-programmersdevelopers#5150" class="answer-title">What are the best RSS feeds for programmers/developers?</a></h3>
```
So you should be able to get the first ten by doing a regex search for a string of that form.
|
How can I search through Stack Overflow questions from a script?
|
[
"",
"python",
"search",
"scripting",
"stackexchange-api",
""
] |
I'm looking to create a Visual Studio 2008 template that will create a basic project and based on remove certain files/folders based on options the user enters.
Right now, I have followed some tutorials online which have let me create the form to query the user and pass the data into an IWizard class, but I don't know what to do from there.
The tutorials provide a sample to do some simple substitution:
code:
```
Form1 form = new Form1();
DialogResult dlg = form.ShowDialog();
if (dlg == DialogResult.OK)
{
foreach (KeyValuePair<string, string> pair in form.Parameters)
{
if (!replacementsDictionary.ContainsKey(pair.Key))
replacementsDictionary.Add(pair.Key, pair.Value);
else
replacementsDictionary[pair.Key] = pair.Value;
}
}
form.Close();
```
but I'm looking to selectively include files based on the user settings, and if possible, selectively include code sections in a file based on settings.
Is there a clever way to do this, or will I manually have to delete project files in the IWizard:ProjectFinishedGenerating()?
|
In my experience, `ShouldAddProjectItem` only gets called for *folders* in the template project. As such, it's pretty much useless.
Instead, you would need to put code in your `ProjectFinishedGenerating` implementation that uses the VS API to remove ProjectItems.
In there, you can remove items like this:
```
ProjectItem file = project.ProjectItems.Item("File.cs");
file.Remove();
```
|
You can selectively include parts of a file by using `$if$` with replacements. See, for example, this bit in the default C# Class Library template:
```
<ItemGroup>
<Reference Include="System"/>
$if$ ($targetframeworkversion$ >= 3.5)
<Reference Include="System.Core"/>
<Reference Include="System.Xml.Linq"/>
<Reference Include="System.Data.DataSetExtensions"/>
$endif$
```
...etc.
|
Creating Visual Studio Templates
|
[
"",
"c#",
"visual-studio",
"templates",
""
] |
I'm trying to read variables from a batch file for later use in the batch script, which is a Java launcher. I'd ideally like to have the same format for the settings file on all platforms (Unix, Windows), and also be a valid Java Properties file. That is, it should look like this:
```
setting1=Value1
setting2=Value2
...
```
Is it possible to read such values like you would in a Unix shell script? The could should look something like this:
```
READ settingsfile.xy
java -Dsetting1=%setting1% ...
```
I know that this is probably possible with `SET setting1=Value1`, but I'd really rather have the same file format for the settings on all platforms.
To clarify: I need to do this in the command line/batch environment as I also need to set parameters that cannot be altered from within the JVM, like -Xmx or -classpath.
|
You can do this in a batch file as follows:
```
setlocal
FOR /F "tokens=*" %%i in ('type Settings.txt') do SET %%i
java -Dsetting1=%setting1% ...
endlocal
```
This reads a text file containing strings like "SETTING1=VALUE1" and calls SET to set them as environment variables.
setlocal/endlocal are used to limit the scope of the environment variables to the execution of your batch file.
The CMD Command Processor is actually quite powerful, though with a rather byzantine syntax.
|
This one-liner also unquotes value before assigning it to a variable:
```
for /F "delims== tokens=1,* eol=#" %%i in (%filename%) do set %%i=%%~j
```
* `delims==` split lines by `=` character
* `tokens=1,*` put first token (name) into `%%i` and the rest (value) into `%%j`
* `eol=#` skip lines starting with `#` (comments)
* `%%~j` [remove surrounding quotes](https://ss64.com/nt/syntax-dequote.html) from value
|
Read environment variables from file in Windows Batch (cmd.exe)
|
[
"",
"java",
"windows",
"command-line",
"cmd",
"environment-variables",
""
] |
I'm getting a whole bunch of linker errors in Visual studios for methods I'm not even calling directly. I'm a java developer by day, but I have a project I need to do in C++, intended to run on windows machines. Hence, I'm stuck messing about with Visual Studio.
Bascally, I have an os project that I added an accessor method to. I compiled that project as a .lib file (compiles and links fine).
I then have my own project that uses that lib. I've included the library under Project->Properties -> Linker -> Input, and set the appropriate directory in the General -> Additional Lib Directories. I've included the header in the appropriate file, and I'm simply calling the constructor of one of the classes...not even calling the method that I created yet.
The code compiles, but I get the following mountain of linker errors -- mostly LNK2019 and LNK2001 errors. I've tried recompiling under different settings (lib, exe, etc.), and the linker errors only seem to multiply. When I switch back to the previous settings, the number of errors remain at their peak. Any ideas how to fix this?
Build Log
> Build started: Project: SpamCapture, Configuration: Debug|Win32
Command Lines:
> Creating temporary file "c:\SpamCapture\SpamCapture\SpamCapture\Debug\RSP0000103081740.rsp" with contents
> [
> /VERBOSE:LIB /OUT:"C:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.exe" /INCREMENTAL /LIBPATH:"C:\SpamCapture\Config\Debug\" /MANIFEST /MANIFESTFILE:"Debug\SpamCapture.exe.intermediate.manifest" /NODEFAULTLIB:"libcmtd.lib" /NODEFAULTLIB:"nafxcwd.lib" /DEBUG /PDB:"c:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.pdb" /SUBSYSTEM:CONSOLE /MACHINE:X86 KeyCapture\_Config.lib kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib
>
> ".\Debug\Interaction.obj"
>
> ".\Debug\InteractionSet.obj"
>
> ".\Debug\LogReader.obj"
>
> ".\Debug\SpamCapture.obj"
>
> ".\Debug\stdafx.obj"
>
> ".\Debug\SpamCapture.res"
>
> ".\Debug\SpamCapture.exe.embed.manifest.res"
> ]
> Creating command line "link.exe @c:\SpamCapture\SpamCapture\SpamCapture\Debug\RSP0000103081740.rsp /NOLOGO /ERRORREPORT:PROMPT"
Output Window:
> Linking...
> LINK : warning LNK4067: ambiguous entry point; selected 'mainCRTStartup'
> Searching libraries
> Searching C:\SpamCapture\Config\Debug\KeyCapture\_Config.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\MSVCRTD.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\OLDNAMES.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfc80ud.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfcs80ud.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\msimg32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comctl32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shlwapi.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\atlsd.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\wininet.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ws2\_32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\mswsock.lib:
> Searching C:\SpamCapture\Config\Debug\KeyCapture\_Config.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\MSVCRTD.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\OLDNAMES.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfc80ud.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\mfcs80ud.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\msimg32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comctl32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shlwapi.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\atlmfc\lib\atlsd.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\wininet.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ws2\_32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\mswsock.lib:
> Searching C:\SpamCapture\Config\Debug\KeyCapture\_Config.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\kernel32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\user32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\gdi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\winspool.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\comdlg32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\advapi32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\shell32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\ole32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\oleaut32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\uuid.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbc32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\PlatformSDK\lib\odbccp32.lib:
> Searching C:\Program Files\Microsoft Visual Studio 8\VC\lib\msvcprtd.lib:
> Finished searching libraries
Linker Errors start here:
> KeyCapture\_Config.lib(KeyCapture\_ConfigDlg.obj) : error LNK2001: unresolved external
> symbol "public: virtual int \_\_thiscall CWnd::Create(char const \*,char const \*,unsigned
> long,struct tagRECT const &,class CWnd \*,unsigned int,struct CCreateContext \*)"
> (?Create@CWnd@@UAEHPBD0KABUtagRECT@@PAV1@IPAUCCreateContext@@@Z)
... a bunch more like this
> KeyCapture\_Config.lib(KeyCapture\_ConfigDlg.obj) : error LNK2019: unresolved external
> symbol "public: struct HICON\_\_ \* **thiscall CWinApp::LoadIconA(unsigned int)const "
> (?LoadIconA@CWinApp@@QBEPAUHICON**@@I@Z) referenced in function "public: \_\_thiscall
> CKeyCapture\_ConfigDlg::CKeyCapture\_ConfigDlg(class CWnd \*)"
> (??0CKeyCapture\_ConfigDlg@@QAE@PAVCWnd@@@Z)
...a bunch more like this
> (?DoDataExchange@SetupDialog@@MAEXPAVCDataExchange@@@Z)
> C:\SpamCapture\SpamCapture\SpamCapture\Debug\SpamCapture.exe : fatal error LNK1120: 34 unresolved externals
Results:
> Build log was saved at "file://c:\SpamCapture\SpamCapture\SpamCapture\Debug\BuildLog.htm"
> SpamCapture - 44 error(s), 1 warning(s)
|
The library `KeyCapture_Config.lib` is using MFC GUI classes (`CWnd`, `CWinApp`, etc), but the application you're linking it into is a console application (see the `/SUBSYSTEM:CONSOLE` option in your linker command line). This won't work. You should create a new MFC GUI application project and add the library to that project.
Edit: I've just checked the link in your comment: <http://dynamicnetservices.com/~will/academic/textinput/keycapture/> and it seems that KeyCapture\_Config is actually an MFC dialog application that uses the KeyCapture DLL. It may be possible to use KeyCapture in a console application by linking directly against `KeyCapture.lib`.
|
The link error seem to be complaining about the lack of a lot of MFC functions, and you link lines includes: /NODEFAULTLIB:"nafxcwd.lib" which would exclude MFC. Is the lib you are linking against built with MFC?
Other things to check are that you are compiling the app and the lib with the same character set (ie. both multibyte or both unicode).
When you are building a lib there is no link step, so an arbitrary collection of objects can be thrown into a lib without any regard for what else they might need.
|
Linker Errors C++ Visual Studio 2005
|
[
"",
"c++",
"visual-studio-2005",
"linker",
"visual-c++-2005",
""
] |
Basically I'm trying to change the `Canvas.Left` property of an Ellipse Silverlight control in C#. Here is how I'm accessing the control:
```
Ellipse c1 = this.FindName("Circle1") as Ellipse;
```
How would I then set the `Canvas.Left` property?
Thanks,
Jeff
|
The answer lies in Silverlights use of Dependancy Properties
c1.SetValue(Canvas.LeftProperty, value);
|
something like this...
```
double left=50;
c1.SetValue(Canvas.LeftProperty, left);
```
|
How do you access an attached property of a Silverlight object in C#?
|
[
"",
"c#",
"silverlight",
""
] |
I have the following
```
var id='123';
newDiv.innerHTML = "<a href=\"#\" onclick=\" TestFunction('"+id+"', false);\"></a>";
```
Which renders `<a href="#" onclick="return Testfunction('123',false);"></a>` in my HTML.
The problem I have is that I wish to take the call to the method TestFunction, and use as a string parameter in my function StepTwo(string, boolean), which would ideally end up in live HTML as shown...
```
<a href="#" onclick="StepTwo("TestFunction('123',false)",true)"></a>
```
notice how the TestFunction is a string here (it is executed within StepTwo using eval).
I have tried to format my JS as by :
```
newDiv.innerHTML = "<a href=\"#\" onclick=\"StepTwo(\"TestFunction('"+id+"', false);\",true)\"></a>";
```
but while this appears to me correct in my IDE, in the rendered HTML, it as garbelled beyond belief.
Would appreciate if anyone could point me in the right direction. Thanks!
|
Try using " instead of \"
newDiv.innerHTML = "<a href="#"...
|
One of the biggest capital failures on the internet is creating html in javascript by gluing strings together.
```
var mya = document.createElement("a");
mya.href="#";
mya.onclick = function(){
StepTwo(function(){
TestFunction('123', false );
}, true );
};
newDiv.innerHTML = "";
newDiv.appendChild(mya);
```
This Eliminates the need for any fancy escaping stuff.
( I probably should do 'onclick' differently, but this should work, I'm trying hard not to just use jQuery code to do everything )
Heres how I would do it in jQuery:
```
jQuery(function($){
var container = $("#container");
var link = document.createElement("a"); /* faster than $("<a></a>"); */
$(link).attr("href", "Something ( or # )" );
$(link).click( function(){
var doStepTwo = function()
{
TestFunction('123', true );
};
StepTwo( doStepTwo, false ); /* StepTwo -> doStepTwo -> TestFunction() */
});
container.append(link);
});
```
### There is no good excuse for gluing strings together in Javascript
All it does is **ADD** overhead of html parsing back into dom structures, and **ADD** potential for XSS based broken HTML. Even *beloved google* get this wrong in some of their advertising scripts and have caused *epic failures* in many cases I have seen ( and they don't want to know about it )
**I don't understand Javascript** is the only excuse, and it's **NOT** a good one.
|
Escaping dilemma in Javascript
|
[
"",
"javascript",
"eval",
"escaping",
""
] |
The question is if a database connection should be passed in by reference or by value?
For me I'm specifically questioning a PHP to MySQL connection, but I think it applies to all databases.
I have heard that in PHP when you pass a variable to a function or object, that it is copied in memory and therefore uses twice as much memory immediately. I have also heard that it's only copied once changes have been made to the value (such as a key being added/removed from an array).
In a database connection, I would think it's being changed within the function as the query could change things like the last insert id or num rows. (I guess this is another question: are things like num rows and insert id stored within the connection or an actual call is made back to the database?)
So, does it matter memory or speed wise if the connection is passed by reference or value? Does it make a difference PHP 4 vs 5?
```
// $connection is resource
function DoSomething1(&$connection) { ... }
function DoSomething2($connection) { ... }
```
|
A PHP resource is a special type that already is a reference in itself. Passing it by value or explicitly by reference won't make a difference (ie, it's still a reference). You can check this for yourself under PHP4:
```
function get_connection() {
$test = mysql_connect('localhost', 'user', 'password');
mysql_select_db('db');
return $test;
}
$conn1 = get_connection();
$conn2 = get_connection(); // "copied" resource under PHP4
$query = "INSERT INTO test_table (id, field) VALUES ('', 'test')";
mysql_query($query, $conn1);
print mysql_insert_id($conn1)."<br />"; // prints 1
mysql_query($query, $conn2);
print mysql_insert_id($conn2)."<br />"; // prints 2
print mysql_insert_id($conn1); // prints 2, would print 1 if this was not a reference
```
|
Call-time pass-by-reference is being depreciated,so I wouldn't use the method first described. Also, generally speaking, resources are passed by reference in PHP 5 by default. So having any references should not be required, and you should never open up more than one database connection unless you really need it.
Personally, I use a singleton-factory class for my database connections, and whenever I need a database reference I just call Factory::database(), that way I don't have to worry about multiple connections or passing/receiving references.
```
<?php
Class Factory
{
private static $local_db;
/**
* Open new local database connection
*
* @return MySql
*/
public static function localDatabase() {
if (!is_a(self::$local_db, "MySql")) {
self::$local_db = new MySql(false);
self::$local_db->connect(DB_HOST, DB_USER, DB_PASS, DB_DATABASE);
self::$local_db->debugging = DEBUG;
}
return self::$local_db;
}
}
?>
```
|
Passing database connection by reference in PHP
|
[
"",
"php",
"mysql",
"database",
""
] |
Is there a way to emulate mixins or traits in java? basically, I need a way to do multiple inheritance so I can add common business logic to several classes
|
I would encapsulate all of the business logic into a new class `BusinessLogic` and have each class that needs `BusinessLogic` make calls to the class. If you need a single rooted heirarchy for your classes that make calls to `BusinessLogic`, you'll have to create an interface as well (`BusinessLogicInterface`?)
In pseudo-code:
```
interface BusinessLogicInterace
{
void method1();
void method2();
}
class BusinessLogic implements BusinessLogicInterface
{
void method1() { ... }
void method2() { ... }
}
class User
extends OtherClass
implements BusinessLogicInterface
{
BusinessLogic logic = new BusinessLogic();
@Override
void method1() { logic.method1(); }
@Override
void method2() { logic.method2(); }
}
```
This isn't the prettiest implementation to work around a lack of multiple inheritance and it becomes quite cumbersome when the interface has a lot of methods. Most likely, you'll want to try and redesign your code to avoid needing mixins.
|
Not the way you want to do it. [Effective Java](https://rads.stackoverflow.com/amzn/click/com/0321356683) recommends that you "Favor composition over inheritance". Meaning you move the common logic to other classes and delegate. This is how you get around the lack of multiple inheritance in java.
|
java traits or mixins pattern?
|
[
"",
"java",
"mixins",
"traits",
""
] |
What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?
|
The primary key value will be in that property after the SubmitChanges().
```
MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
```
|
```
// Create a new Order object.
Order ord = new Order
{
OrderID = 12000,
ShipCity = "Seattle",
OrderDate = DateTime.Now
// …
};
// Add the new object to the Orders collection.
db.Orders.InsertOnSubmit(ord);
// Submit the change to the database.
try
{
db.SubmitChanges();
}
catch (Exception e)
{
Console.WriteLine(e);
// Make some adjustments.
// ...
// Try again.
db.SubmitChanges();
}
return ord.OrderID;
```
|
How to insert a record with LINQ and C# and return the Primary Key of that record
|
[
"",
"c#",
"linq",
""
] |
I need to present a wizard once, the first time my windows forms application is run after install. I could use a user setting like firstrun = false I suppose. But I also need handle the case where the program is uninstalled, then reinstalled. How will that user setting be reset? It's already present in the config file in ...\Users--user--\AppData\Roaming... for that user. I need the wizard to run after any reinstalls so I need to reset that setting. Do I need to do this with a custom installer action?
|
It's probably best to have your installer create the FirstRun key in the registry and set it to true (or 1 or whatever), and make sure your uninstaller deletes this key entirely. Then just have your application read this key when it starts, and set it to false (or 0 or whatever).
If the user uninstalls and then reinstalls your application, they'll see the wizard again the first time they run it.
|
The Windows registry seems like the appropriate place for this type of setting. An installer step could reset the key when the user reinstalls, or you could just clear out the registry key on uninstall if you don't want to keep any settings between installations.
|
c# winforms: determine first run of program
|
[
"",
"c#",
".net",
"windows",
"winforms",
""
] |
I have always initialized my strings to NULL, with the thinking that NULL means the absence of a value and "" or String.Empty is a valid value. I have seen more examples lately of code where String.Empty is considered the default value or represents no value. This strikes me as odd, with the newly added nullable types in c# it seems like we are taking strides backwards with strings by not using the NULL to represent 'No Value'.
**What do you use as the default initializer and why?**
*Edit: Based on the answers I futher my further thoughts*
1. **Avoiding error handling** If the value shouldn't be null, why did it get set to `NULL` in the first place? Perhaps it would be better to identify the error at the place where it occurs rather than cover it up through out the rest of your codebase?
2. **Avoiding null checks** If you are tired of doing null checks in code, wouldn't it be better to abstract the null checks? Perhaps wrap (or extend!) the string methods to make them `NULL` safe? What happens if you constantly use `String.Empty` and a null happens to work it's way into your system, do you start adding `NULL` checks anyways?
I can't help but return to the opinion that it is laziness. Any DBA would slap you nine ways to silly if you used '' instead of `null` in his\her database. I think the same principles apply in programming and there should be somebody to smack those upside the head who use `String.Empty` rather than `NULL` to represent no value.
> ### Related Questions
>
> * [In C#, should I use string.Empty or String.Empty or “” ?](https://stackoverflow.com/questions/263191/in-c-should-i-use-stringempty-or-stringempty-or)
> * [What is the difference between String.Empty and “”](https://stackoverflow.com/questions/151472/what-is-the-difference-between-stringempty-and)
> * [Null or empty string to represent no data in table column?](https://stackoverflow.com/questions/167952/null-or-empty-string-to-represent-no-data-in-table-column)
|
+1 for distinguishing between "empty" and NULL. I agree that "empty" should mean "valid, but blank" and "NULL" should mean "invalid."
So I'd answer your question like this:
**empty** when I want a valid default value that may or may not be changed, for example, a user's middle name.
**NULL** when it is an error if the ensuing code does not set the value explicitly.
|
According to [MSDN](http://msdn.microsoft.com/en-us/library/ms228362.aspx):
> By initializing strings with the `Empty` value instead of `null`, you can reduce the chances of a `NullReferenceException` occurring.
Always using `IsNullOrEmpty()` is good practice nevertheless.
|
Default string initialization: NULL or Empty?
|
[
"",
"c#",
""
] |
We are using LINQ very widely in our system. Particularly LINQ-to-objects. So in some places we end up having a LINQ query in memory build up from some huge expressions. The problem comes when there's some bug in the expressions. So we get NullReferenceException and the stack trace leads us nowhere (to [Lightweight Function]). The exception was thrown inside the dynamic method generated by LINQ.
Is there any easy way to debug such dynamic methods? Or do I have to sacrifice myself to learning WinDBG? :-)
|
If you are building your own expressions and compiling them, or using AsQueryable, then yes; the LINQ-generated methods will be a royal pain to debug.
You can save some pain by using small fragements of *actual* methods - at least something useful will show in the stack trace...
Another consideration is: rather than having one huge expression, if you can daisy-chain things a bit more you might have more idea (from the stack trace) where it is failing. The downside is performance - a Where(foo).Where(bar) is two delegate invokes, where-as Where(foo && bar) can be one.
One option might be to swap in a debug version of the extension methods; unfortunately it is a little inconvenient because `IQueryable<T>` and `Queryable` are in the same namespace... this works, though...
Output first:
```
>Where: x => ((x % 2) = 0)
<Where: x => ((x % 2) = 0)
>Count
'WindowsFormsApplication2.vshost.exe' (Managed): Loaded 'Anonymously Hosted DynamicMethods Assembly'
<Count
```
Code:
```
using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace Demo
{
using DebugLinq;
static class Program
{
static void Main()
{
var data = System.Linq.Queryable.AsQueryable(new[] { 1, 2, 3, 4, 5 });
data.Where(x => x % 2 == 0).Count();
}
}
}
namespace DebugLinq
{
public static class DebugQueryable
{
public static int Count<T>(this System.Linq.IQueryable<T> source)
{
return Wrap(() => System.Linq.Queryable.Count(source), "Count");
}
public static System.Linq.IQueryable<T> Where<T>(this System.Linq.IQueryable<T> source, Expression<Func<T, bool>> predicate)
{
return Wrap(() => System.Linq.Queryable.Where(source, predicate), "Where: " + predicate);
}
static TResult Wrap<TResult>(Func<TResult> func, string caption)
{
Debug.WriteLine(">" + caption);
try
{
TResult result = func();
Debug.WriteLine("<" + caption);
return result;
}
catch
{
Debug.WriteLine("!" + caption);
throw;
}
}
}
}
```
|
If you're using LINQ to Objects, I wouldn't expect to see dynamic methods being created. I'd expect them with LINQ to SQL etc. Could you give an example where you're seeing this?
I don't really have any good debugging tips when it comes to LINQ, but I'm pretty sure MS know about this as a pain point. Could I suggest you try the [VS2010 CTP](http://www.microsoft.com/downloads/details.aspx?FamilyId=922B4655-93D0-4476-BDA4-94CF5F8D4814&displaylang=en) and see if that's better? More for the sake of improving VS than for solving your immediate problem, admittedly.
|
Debugging .NET dynamic methods
|
[
"",
"c#",
".net",
"linq",
"debugging",
"dynamic-method",
""
] |
I've got this python dictionary "mydict", containing arrays, here's what it looks like :
```
mydict = dict(
one=['foo', 'bar', 'foobar', 'barfoo', 'example'],
two=['bar', 'example', 'foobar'],
three=['foo', 'example'])
```
i'd like to replace all the occurrences of "example" by "someotherword".
While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?
|
```
for arr in mydict.values():
for i, s in enumerate(arr):
if s == 'example':
arr[i] = 'someotherword'
```
|
If you want to leave the original untouched, and just return a new dictionary with the modifications applied, you can use:
```
replacements = {'example' : 'someotherword'}
newdict = dict((k, [replacements.get(x,x) for x in v])
for (k,v) in mydict.iteritems())
```
This also has the advantage that its easy to extend with new words just by adding them to the replacements dict. If you want to mutate an existing dict in place, you can use the same approach:
```
for l in mydict.values():
l[:]=[replacements.get(x,x) for x in l]
```
However it's probably going to be slower than [J.F Sebastian's](https://stackoverflow.com/questions/268891/replacing-multiple-occurrences-in-nested-arrays#269043) solution, as it rebuilds the whole list rather than just modifying the changed elements in place.
|
Replacing multiple occurrences in nested arrays
|
[
"",
"python",
"arrays",
"dictionary",
"replace",
""
] |
I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:
```
<a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a>
```
This works OK in internet explorer, but firefox always opens a new tab/window.
Any ideas?
|
The window.open() function in Javascript is specifically designed to open a new window, please see: [w3schools documentation](http://www.w3schools.com/HTMLDOM/met_win_open.asp). It actually sounds like IE is handling things in a non-standard way (which is hardly surprising).
If you want to relocate the existing location to a new page using Javascript, you should look at the [location.replace()](http://www.w3schools.com/HTMLDOM/met_loc_replace.asp) function.
Generally speaking I would recommend that you develop for Firefox and then fix for IE. Not only does Firefox offer better development tools but its implementation of W3C standards tends to be more correct.
|
Actually, the W3Schools documentation linked to by [gabriel1836](https://stackoverflow.com/questions/268902/javascript-windowopen-strange-behavior-in-firefox#268951) is only a very very brief summary of functions.
And Oddly, mozilla's own developer reference *CONTRADITCS* this logic.
[MDC / DOM / Window.open](https://developer.mozilla.org/En/DOM/Window.open)
> ```
> var WindowObjectReference = window.open(strUrl,
> strWindowName [, strWindowFeatures]);
> ```
>
> If a window with the name
> **strWindowName** already exists, then,
> instead of opening a new window,
> **strUrl** is loaded into the existing
> window. In this case the return value
> of the method is the existing window
> and **strWindowFeatures** is ignored.
> Providing an empty string for **strUrl**
> is a way to get a reference to an open
> window by its name without changing
> the window's location. If you want to
> open a new window on every call of
> **window.open()**, you should use the
> special value **\_blank** for
> **strWindowName**.
However, the page also states that there are many extensions that can be installed that change this behaviour.
So either the documentation mozilla provides for people targeting their own browser is **wrong** or something is odd with your test system :)
Also, your current A-Href notation is bad for the web, and will infuriate users.
```
<a href="http://google.com"
onclick="window.open( this.href, 'windowName' ); return false" >
Text
</a>
```
Is a SUBSTANTIALLY better way to do it.
Many people will instinctively 'middle click' links they want to manually open in a new tab, and having your only href as "#" infuriates them to depravity.
The "#" trick is a redundant and somewhat bad trick to stop the page going somewhere unintended, but this is only because of the lack of understanding of how to use `onclick`
If you return `FALSE` from an on-click event, it will cancel the links default action ( the default action being navigating the **current** page away )
Even better than this notation would be to use unintrusive javascript like so:
```
<a href="google.com" rel="external" >Text</a>
```
and later
```
<script type="text/javascript">
jQuery(function($){
$("a[rel*=external]").click(function(){
window.open(this.href, 'newWindowName' );
return false;
});
});
</script>
```
|
Javascript window.open strange behavior in Firefox
|
[
"",
"javascript",
"firefox",
""
] |
I'm looking for a library that can deal with RDF and OWL data.
So far I have found:
* [semweb](http://razor.occams.info/code/semweb/) (no owl support for all I know)
* [rowlex](http://rowlex.nc3a.nato.int/HowToUse.aspx) (more of a 'browser' application)
Your recommendations:
* [LinqToRdf](https://code.google.com/p/linqtordf/) (very interesting, thanks mark!)
|
[ROWLEX](http://rowlex.nc3a.nato.int) is actually very cool (uses [SemWeb](http://razor.occams.info/code/semweb/) internally). It is not just a browser app but rather an SDK written in C#. If you use ROWLEX, you do not directly interact with the tripples of RDF anymore (though you can), but gives an object oriented look&feel. There are two main usage scenarios:
1. **Business class first:** You have your .NET business classes. You declaratively add attributes to your classes similarly as you do with XML serialization attributes. After this, ROWLEX can extract the ontology corresponding your business classes and/or can serialize your business objects into RDF.
2. **Ontology first:** You have your ontology(s) and [ROWLEX](http://rowlex.nc3a.nato.int) generates .NET classes for you that you can use to build/browse RDF documents. The great thing is that these autogenerated classes are far better then the typical results of codegenerators. They are comfortable to use and mimic the multiple inheritence feature of OWL by providing implicit and explicit cast operators to cover the entire inheritence graph.
The typical usage is the Ontology first approach. For example, let us say that your ontology describes the following multiple inheritence scenario:
> Car isSubClassOf Vehicle
>
> Car isSubClassOf CompanyAsset
Using ROWLEX, you will get .NET classes for Car, Vehicle, and CompanyAsset. The following C# code will compile without any problem:
```
RdfDocument rdfDoc = new RdfDocument();
Car car = new Car("myCarUri", rdfDoc);
Vehicle vehicle = car; // implicit casting
CompanyAsset companyAsset = car; // implicit casting
vehicle.WheelCount = 4;
companyAsset.MonetaryValue = 15000;
Console.WriteLine(rdfDoc.ToN3());
```
This would print:
```
myCarUri typeOf Car
myCarUri WheelCount 4
myCarUri MonetaryValue 15000
```
The "car" business object is represented inside the RdfDocument as triples. The autogenerated C#/VB classes behave as a views. You can have several C# views - each of a completely different type - on the same business object. When you interact with these views, you actually modifying the RdfDocument.
|
BrightstarDB is a native, .NET NoSQL RDF triple store, with SPARQL support, a .NET entity framework with LINQ and OData support. It is free for developers and open source projects and has a small runtime cost for commercial use.
BrightstarDB provide three levels of API.
1. SPARQL query and simple transaction API.
2. A generic object api that groups collections of triples into data objects
3. A Visual Studio integration that takes Interface definitions and generated a strongly typed .NET domain model that stores its data as RDF in a BrightstarDB instance. The .NET model has LINQ support and can also be exposed as an OData service.
All BrightstarDB documentation is online and the software is available for download with no registration at <http://www.brightstardb.com>
|
What is a good RDF library for .net?
|
[
"",
"c#",
".net",
"rdf",
"semantic-web",
"owl",
""
] |
From the MSDN documentation:
"Synchronized supports multiple writing threads, provided that no threads are reading the Hashtable. The synchronized wrapper does not provide thread-safe access in the case of one or more readers and one or more writers."
Source:
<http://msdn.microsoft.com/en-us/library/system.collections.hashtable.synchronized.aspx>
It sounds like I still have to use locks anyways, so my question is why would we use Hashtable.Synchronized at all?
|
For the same reason there are different levels of DB transaction. You may care that writes are guaranteed, but not mind reading stale/possibly bad data.
---
**EDIT** I note that their specific example is an Enumerator. They can't handle this case in their wrapper, because if you break from the enumeration early, the wrapper class would have no way to know that it can release its lock.
Think instead of the case of a counter. Multiple threads can increase a value in the table, and you want to display the value of the count. It doesn't matter if you display 1,200,453 and the count is actually 1,200,454 - you just need it close. However, you don't want the data to be corrupt. This is a case where thread-safety is important for writes, but not reads.
|
For the case where you can guarantee that no reader will access the data structure when writing to it (or when you don't care reading wrong data). For example, where the structure is not continually being modified, but a one time calculation that you'll later have to access, although huge enough to warrant many threads writing to it.
|
Why use Hashtable.Synchronized?
|
[
"",
"c#",
".net",
""
] |
I have stumbled into several methods of looping in JavaScript, what I like the most is:
```
for(var i = 0; i < a.length; i++){
var element = a[i];
}
```
But as tested here (<http://www.robertnyman.com/2008/04/11/javascript-loop-performance/>), it should probably be written so that the length is only calculated once.
In jQuery there is a .each that you can stick a function. I like this a little better, because I don't have to type the array twice, like in the above solution.
If JavaScript supported macros it would be a piece of cake to roll your own, but sadly it does not.
So what do you guys use?
|
I've started using iterators where relevant. Performance is reasonable, however more importantly it allows you to encapsulate the looping logic:
```
function createIterator(x) {
var i = 0;
return function(){
return x[i++];
};
}
```
Then to use:
```
var iterator=createIterator(['a','b','c','d','e','f','g']);
iterator();
```
returns "a";
```
iterator();
```
returns "b";
and so on.
To iterate the whole list and display each item:
```
var current;
while(current=iterator())
{
console.log(current);
}
```
Be aware that the above is only acceptable for iterating a list that contains "non-falsy" values. If this array contained any of:
* 0
* false
* ""
* null
* NaN
the previous loop would stop at that item, not always what you want/expect.
To avoid this use:
```
var current;
while((current=iterator())!==undefined)
{
console.log(current);
}
```
|
Small improvement to the original, to only calculate the array size once:
```
for(var i = 0, len = a.length; i < len; i++){ var element = a[i]; }
```
Also, I see a lot of for..in loops. Though keep in mind that it's not technically kosher, and will cause problems with Prototype specifically:
```
for (i in a) { var element = a[i]; }
```
|
What is the best way to do loops in JavaScript
|
[
"",
"javascript",
"jquery",
"loops",
"macros",
""
] |
What do you usually use to connect to a Web Service when you are developing a Java project?
There are different API-s that can do the job.
From different books and tutorials I have read about: JAX-WS, JAXB, JAXM, JAXR, JAX-RPC, Axis ans so on.
I'm interested in what exactly are you using and how much? Take this as a survey if you wish :)
|
To answer your question, we first need to differentiate between the tools you listed.
JAX-WS, JAXB, JAXM, JAXR, JAX-RPC are XML and Web service related APIs while Axis 1 and 2 are implementations of zero, one, or more of these APIs depending on the version.
JAX-B 1 and 2 are XML to object binding APIs, JAX-WS is a WSDL and SOAP based Web service API and the predecessor of JAX-RPC, JAX-M is an older XML messaging API and JAX-R is an abstraction API for interacting with registries such as UDDI and ebXML.
From the Java.net JAX-RPC page:
> The JAX-RPC expert group has wide industry participation with Sun Microsystems as the EG lead. The initial specification (JAX-RPC 1.0) was JSR-101 and was released in June 2002. A maintenance release followed in October 2003 providing better integration with JAXB 1.0 as well as better support for doc/literal.
>
> The next version of the spec was renamed from JAX-RPC 2.0 to JAX-WS 2.0 and is being developed as JSR-224; this release will address a number of additional requirements in the area, and will increase the synergy between the JAXB and JAX-WS specifications. You can access the JAX-WS project page here.
Since SOAP stacks have come a long way since JAX-B 1.0 and JAX-RPC 1.0 I recommend staying far away from Axis 1.0 and XFire (which if I recall correctly doesn't even implement JAX-RPC 1). There are numerous SOAP stacks out there that implement the newer APIs (JAX-WS 2.x and JAX-B 2.x).
As others have mentioned, Axis 2, JAX-WS RI, and CXF are all valid choices. These SOAP stacks are far more mature and support many modern WS-\* specifications.
A word of caution about the comments regarding using your IDE to auto-generate client code. While I am a big proponent of generating XML data binding code and JAX-WS interfaces from XSDs and WSDLs, respectively, I caution using a built-in wizard in your IDE to perform the auto-generation. If you work on a team with more than one developer or plan to modify the generated code you should consider the maintainability of such an approach.
If you have more than one developer, there will come a time when one of them is using a different version of the auto-generation tool, a different IDE, or has a different configuration in their tool. Additionally, if you auto-generate from a wizard, it is up to the developers to remember how they generated the code in the event that you need to re-generate it in the future. If you change the XSD and don't remember your configuration from the last time you auto-generated, the generated code may not align with the existing code that is already used throughout your program.
If you plan to modify the generated code, make sure that you only ever need to do it once and that from then on you are comfortable maintaining the code by hand or merging the regenerated code with your modifications on a regular basis.
Both of these issues can be avoided by scripting the code generation in your build process. JAX-WS and JAX-B both come with Ant tasks and/or Maven 2 plug-ins that are easy to use in your builds. Take these warnings seriously as I have seen multiple projects suffer through these issues when they needed to modify code that was generated 5 years ago by an employee that had since left the firm.
My final words of caution are to be careful when allowing a tool to auto-generate your Web service interfaces from your WSDLs. The JAX-WS RI WSDL2Java tool likes to place hard-coded paths to the WSDL in the generated interfaces. It is my opinion that you should auto-generate the interfaces once and then remove the hard-coded URLs and QName references to make the interface applicable to all Web services that implement the WSDL Binding that the interface represents and not just the one endpoint that your WSDL describes.
|
<http://cxf.apache.org/> is nice.
|
Web Services in Java
|
[
"",
"java",
"xml",
"web-services",
"web-applications",
""
] |
I need to be able to send encrypted data between a Ruby client and a Python server (and vice versa) and have been having trouble with the [ruby-aes](http://rubyforge.org/projects/ruby-aes) gem/library. The library is very easy to use but we've been having trouble passing data between it and the pyCrypto AES library for Python. These libraries seem to be fine when they're the only one being used, but they don't seem to play well across language boundaries. Any ideas?
Edit: We're doing the communication over SOAP and have also tried converting the binary data to base64 to no avail. Also, it's more that the encryption/decryption is almost but not exactly the same between the two (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)
|
Turns out what happened was that ruby-aes automatically pads data to fill up 16 chars and sticks a null character on the end of the final string as a delimiter. PyCrypto requires you to do multiples of 16 chars so that was how we figured out what ruby-aes was doing.
|
> (e.g., the lengths differ by one or there is extra garbage characters on the end of the decrypted string)
I missed that bit. There's nothing wrong with your encryption/decryption. It sounds like a padding problem. AES always encodes data in blocks of 128 bits. If the length of your data isn't a multiple of 128 bits the data should be padded before encryption and the padding needs to be removed/ignored after encryption.
|
Which AES library to use in Ruby/Python?
|
[
"",
"python",
"ruby",
"encryption",
"aes",
""
] |
I have two Java classes: B, which extends another class A, as follows :
```
class A {
public void myMethod() { /* ... */ }
}
class B extends A {
public void myMethod() { /* Another code */ }
}
```
I would like to call the `A.myMethod()` from `B.myMethod()`. I am coming from the [C++ world](https://stackoverflow.com/questions/357307/how-to-call-a-parent-class-function-from-derived-class-function), and I don't know how to do this basic thing in Java.
|
The keyword you're looking for is `super`. See [this guide](http://java.sun.com/docs/books/tutorial/java/IandI/super.html), for instance.
|
Just call it using super.
```
public void myMethod()
{
// B stuff
super.myMethod();
// B stuff
}
```
|
In Java, how do I call a base class's method from the overriding method in a derived class?
|
[
"",
"java",
"inheritance",
"methods",
"polymorphism",
""
] |
I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.
The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.
Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.
Thanks,
Blake.
|
[RFC 2919](http://www.apps.ietf.org/rfc/rfc2919.html) has some info and more references on this.
|
What about <http://labs.freehackers.org/projects/colibri/wiki>
It seems to do what you want: a mailing list manager with a django frontend.
|
How can you emulate a mailing list in Django?
|
[
"",
"python",
"django",
"mailing-list",
""
] |
I have been trying to learn how to add testing to existing code -- currently reading reading [Working Effectively With Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052). I have been trying to apply some of the principles in JavaScript, and now I'm trying to extract an interface.
In searching for creating interfaces in JavaScript, I can't find a lot -- and what I find about inheritance seems like their are several different ways. (Some people create their own base classes to provide helpful methods to make it easier to do inheritance, some use functions, some use prototypes).
What's the right way? Got a simple example for extracting an interface in JavaScript?
|
There's no definitive **right way**, because so many people are doing so many different things.. There are many useful patterns.
**Crockford** suggests that you "go with the grain", or write javascript in a way that corresponds to javascript's prototypal nature.
Of course, he goes on to show that the original model that Netscape suggested is actually broken. He labels it "pseudoclassical", and points out a lot of the misdirection and unnecessary complexity that is involved in following that model.
He wrote the "object" function as a remedy (now known as Object.create() ). It allows for some very powerful prototypal patterns.
It's not always easy to do develop a clean interface when you have to work with legacy javascript, especially not when you're dealing with large systems, usually including multiple libraries, and each implementing a unique style and different inheritance pattern. In general, I'd say that the "right way" to do inheritance is the one which allows you to write a clean interface which behaves well in the context of your legacy code, but also allows you to refactor and eliminate old dependencies over time.
Considering the differences between the major library patterns, I've found that the most successful route to take in my own work is to keep my interfaces independent of the library interfaces entirely. I'll use a library or module if it's helpful, but won't be bound to it. This has allowed me to refactor a lot of code, phase out some libraries, and use libraries as scaffolding which can be optimized later.
Along these lines, I've written interfaces that were inspired by Crockford's parasitic inheritance pattern. It's really a win for simplicity.
On the other side of the coin, I'm sure you could argue for picking a library, enforcing it across your team, and conforming to both its inheritance patterns and its interface conventions.
|
There are no class in javascript, only objects.
But if you insist on emulating the class based object-oriented model you can use this:
```
function ChildClass() {
ParentClass.call(this);
// Write the rest of your constructor function after this point.
};
ChildClass.prototype = jQuery.extend({}, ParentClass.prototype, ChildClass.prototype);
```
jQuery.extend is a 'shallow copy' function from the jQuery library. You can replace it with any other object copying/cloning function.
|
Is there a "right" way to do inheritance in JavaScript? If so, what is it?
|
[
"",
"javascript",
"oop",
"refactoring",
"interface",
""
] |
Since I've started to use jQuery, I have been doing a lot more JavaScript development.
I have the need to parse different date formats and then to display them into another format.
Do you know of any good tool to do this?
Which one would you recommend?
|
2014 update: [Moment.js](http://momentjs.com/) is an excellent date manipulation library, which includes parsing functions. It doesn't include automatic date format detection, but you can [specify multiple parsing patterns](http://momentjs.com/docs/#/parsing/string-formats/).
Do you know the format of the dates before hand though, or are they user input?
---
[A deprecated library for parsing dates is Datejs](http://www.datejs.com/). It hasn't been updated since 2007.
|
If you already use jqueryUI on the page, than $.datepicker has parseDate() and formatDate() functions that enough in most cases. As for DateJS - profile yu code and you'll see how it baggy and how much time it spends in handling exception
|
Best JavaScript Date Parser & Formatter?
|
[
"",
"javascript",
"jquery",
"datetime",
"parsing",
"formatting",
""
] |
We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error\_log, I get a stack trace that culminates in:
```
PythonHandler trac.web.modpython_frontend:
ExtractionError: Can't extract file(s) to egg cache
The following error occurred while trying to extract file(s) to the Python egg
cache:
[Errno 13] Permission denied: '/.python-eggs'
The Python egg cache directory is currently set to:
/.python-eggs
Perhaps your account does not have write access to this directory? You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory
```
So I explicitly set PYTHON\_EGG\_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python\_eggs.")
How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?
|
That should be fixed in 0.11 according to their [bug tracking system](http://trac.edgewall.org/ticket/7320).
If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like
```
export PYTHON_EGG_CACHE=/tmp/python_eggs
```
to the script you use to start apache should work.
|
I ran into the same problem when upgrading from Trac 10.4 to 0.11 earlier this year. Something must have changed for this problem to have just suddenly appeared -- an updated Python or Apache installation?
I don't remember all of the permutations I tried to solve this, but I ended up having to use `SetEnv PYTHON_EGG_CACHE /.python-eggs` and create /.python-eggs with 777 permissions. This might not be the best solution, but it fixed the problem.
I never investigated what the root cause was. As [agnul](https://stackoverflow.com/questions/215267/how-do-you-fix-a-trac-installation-that-begins-giving-errors-relating-to-python#215298) says, this may have been fixed in a subsequent Trac release.
|
How do you fix a Trac installation that begins giving errors relating to PYTHON_EGG_CACHE?
|
[
"",
"python",
"configuration",
"trac",
"python-egg-cache",
""
] |
I installed Python 2.6 for one user on Windows Vista. Python works okay, but when I try: `import Tkinter`, it says the side-by-side configuration has errors. I've tried tinkering with the Visual Studio runtime, with no good results. Any ideas on how to resolve this?
|
Maybe you should downgrade to 2.5 version?
|
It seems this is a one of the many weird Vista problems and some random reinstalling, installing/upgrading of the visual studio runtime or some such seems sometimes to help, or disabling sxs in the system configuration or writing a manifest file etc.
Though I think you should downgrade to windows XP.
|
How do I use Tkinter with Python on Windows Vista?
|
[
"",
"python",
"windows",
"windows-vista",
"tkinter",
""
] |
I've got a **large** array of primitive types (double).
How do I sort the elements in **descending order**?
Unfortunately the Java API doesn't support sorting of **primitive** types with a Comparator.
The first approach that probably comes to mind is to convert it to a list of objects (boxing):
```
double[] array = new double[1048576];
Arrays.stream(array).boxed().sorted(Collections.reverseOrder())…
```
This solution is probably good enough for many (or even most) use cases but **boxing** each primitive in the array is **too slow and causes a lot of GC pressure** if the array is large!
Another approach would be to sort and then reverse:
```
double[] array = new double[1048576];
...
Arrays.sort(array);
// reverse the array
for (int i = 0; i < array.length / 2; i++) {
// swap the elements
double temp = array[i];
array[i] = array[array.length - (i + 1)];
array[array.length - (i + 1)] = temp;
}
```
**This approach can also be too slow** if the array is already sorted quite well.
What's a better alternative if the arrays are large and performance is the major optimization goal?
|
[Java Primitive](https://github.com/mintern-java/primitive#java-primitive) includes functionality for sorting primitive arrays based on a custom comparator. Using it, and Java 8, your sample could be written as:
```
double[] array = new double[1048576];
...
Primitive.sort(array, (d1, d2) -> Double.compare(d2, d1), false);
```
If you're using Maven, you can include it with:
```
<dependency>
<groupId>net.mintern</groupId>
<artifactId>primitive</artifactId>
<version>1.2.1</version>
</dependency>
```
When you pass `false` as the third argument to `sort`, it uses an unstable sort, a simple edit of Java's built-in [dual-pivot quicksort](https://en.wikipedia.org/wiki/Quicksort#Variants). This means that the speed should be close to that of built-in sorting.
Full disclosure: I wrote the Java Primitive library.
|
I think it would be best not to re-invent the wheel and use Arrays.sort().
Yes, I saw the "descending" part. The sorting is the hard part, and you want to benefit from the simplicity and speed of Java's library code. Once that's done, you simply reverse the array, which is a relatively cheap O(n) operation. [Here's some code](http://www.leepoint.net/data/arrays/arrays-ex-reverse.html) I found to do this in as little as 4 lines:
```
for (int left=0, right=b.length-1; left<right; left++, right--) {
// exchange the first and last
int temp = b[left]; b[left] = b[right]; b[right] = temp;
}
```
|
Sort large arrays of primitive types in descending order
|
[
"",
"java",
"sorting",
""
] |
I have a co-worker that swears by
```
//in a singleton "Constants" class
public static final String EMPTY_STRING = "";
```
in a constants class available throughout the project. That way, we can write something like
```
if (Constants.EMPTY_STRING.equals(otherString)) {
...
}
```
instead of
```
if ("".equals(otherString)) {
...
}
```
I say it's
1. not worth it--it doesn't save any space in the heap/stack/string pool,
2. ugly
3. abuse of a constants class.
Who is the idiot here?
|
String literals are interned by default, so no matter how many times you refer to **""** in code, there will only be one empty String object. I don't see any benefit in declaring EMPTY\_STRING. Otherwise, you might as well declare ONE, TWO, THREE, FOUR, etc. for integer literals.
Of course, if you want to change the value of EMPTY\_STRING later, it's handy to have it in one place ;)
|
Why on earth would you want a global variable in Java? James Gosling really tried to get rid of them; don't bring them back, please.
Either
```
0 == possiblyEmptyString.length()
```
or
```
possiblyEmptyString.isEmpty() // Java 6 only
```
are just as clear.
|
Is making an empty string constant worth it?
|
[
"",
"java",
"string",
""
] |
What would be the best way to check that a `std::vector` is sorted? Is there something faster than a loop checking that `v[i]<=v[i+1]`? Is it faster/cleaner with iterators? Or is it actually better to just call `sort` every time (though the "v is already sorted" case is quite common)?
We can safely assume the vector only contains PODs, usually `float`s and sometimes `double`s and `int`s.
The size of the vector is non-trivial (usually a few thousands items) but not extreme (not gigabyte-sized).
* in some instances we'll sort the vector immediately afterwards, however there are other instances where we don't (it's an error case of our algorithm).
* we already use a flag "IsSorted" whenever possible.
|
**Consider Multiple Cpu Cores**
It depends on your platform and number of items in the vector. You'd have to benchmark to find what's best.
It's not possible to answer: Is there something faster than a loop checking that v[i]<=v[i+1] ?
With: No.
Because... computers now a days have multiple cpus/cores/hyperthreading. So, it may well be a lot quicker to exploit the parallism in the computer by spliting the work of checking to a number of threads, so each cpu can be checking a small range in parallel.
It's probably best to do this via a library function rather than implementing it yourself. New versions of libraries will exploit parallism. So, if you go for a std::sort you'll probably find when you build against newer implementations of STL, they'll do the operation in parallel for you without you having to worry about it. I don't know if there are readily available versions of STL that do this already, but it's worth sticking to the library functions so that when you upgrade to a version that does, this optimization is there for you without you needing to make any changes.
|
> Is there something faster than a loop
> checking that v[i]<=v[i+1] ?
No.
If this is something you wish to check often, you might want to make a wrapper class that keeps a "sorted" flag which starts out False, is set to False whenever an item is added, and add a member function sort() that sets the flag to True after sorting.
|
Best algorithm to check whether a vector is sorted
|
[
"",
"c++",
"algorithm",
"optimization",
"vector",
""
] |
I'm trying to run a particular JUnit test by hand on a Windows XP command line, which has an unusually high number of elements in the class path. I've tried several variations, such as:
```
set CLASS_PATH=C:\path\a\b\c;C:\path\e\f\g;....
set CLASS_PATH=%CLASS_PATH%;C:\path2\a\b\c;C:\path2\e\f\g;....
...
C:\apps\jdk1.6.0_07\bin\java.exe -client oracle.jdevimpl.junit.runner.TestRunner com.myco.myClass.MyTest testMethod
```
(Other variations are setting the classpath all on one line, setting the classpath via -classpath as an argument to java"). It always comes down to the console throwing up it's hands with this error:
```
The input line is too long.
The syntax of the command is incorrect.
```
This is a JUnit test testing a rather large existing legacy project, so no suggestions about rearranging my directory structure to something more reasonable, those types of solutions are out for now. I was just trying to gen up a quick test against this project and run it on the command line, and the console is stonewalling me. Help!
|
The Windows command line is very limiting in this regard. A workaround is to create a "pathing jar". This is a jar containing only a `Manifest.mf` file, whose `Class-Path` specifies the disk paths of your long list of jars, etc. Now just add this *pathing jar* to your command line classpath. This is usually more convenient than packaging the actual resources together.
As I recall, the disk paths can be relative to the *pathing jar* itself. So the `Manifest.mf` might look something like this:
```
Class-Path: this.jar that.jar ../lib/other.jar
```
If your *pathing jar* contains mainly foundational resources, then it won't change too frequently, but you will probably still want to generate it somewhere in your build. For example:
```
<jar destfile="pathing.jar">
<manifest>
<attribute name="Class-Path" value="this.jar that.jar ../lib/other.jar"/>
</manifest>
</jar>
```
|
Since Java 6 you can use [classpath wildcards](https://docs.oracle.com/javase/6/docs/technotes/tools/windows/classpath.html#Understanding).
Example: `foo/*`, refers to all .jar files in the directory `foo`
* this will not match class files (only jar files). To match both use: `foo;foo/*` or `foo/*;foo`. The order determines what is loaded first.
* The search is NOT recursive
|
How to set a long Java classpath in Windows?
|
[
"",
"java",
"junit",
"classpath",
""
] |
Please help!
*Background info*
I have a WPF application which accesses a SQL Server 2005 database. The database is running locally on the machine the application is running on.
Everywhere I use the Linq DataContext I use a using { } statement, and pass in a result of a function which returns a SqlConnection object which has been opened and had an SqlCommand executed using it before returning to the DataContext constructor.. I.e.
```
// In the application code
using (DataContext db = new DataContext(GetConnection()))
{
... Code
}
```
where getConnection looks like this (I've stripped out the 'fluff' from the function to make it more readable, but there is no additional functionality that is missing).
```
// Function which gets an opened connection which is given back to the DataContext constructor
public static System.Data.SqlClient.SqlConnection GetConnection()
{
System.Data.SqlClient.SqlConnection Conn = new System.Data.SqlClient.SqlConnection(/* The connection string */);
if ( Conn != null )
{
try
{
Conn.Open();
}
catch (System.Data.SqlClient.SqlException SDSCSEx)
{
/* Error Handling */
}
using (System.Data.SqlClient.SqlCommand SetCmd = new System.Data.SqlClient.SqlCommand())
{
SetCmd.Connection = Conn;
SetCmd.CommandType = System.Data.CommandType.Text;
string CurrentUserID = System.String.Empty;
SetCmd.CommandText = "DECLARE @B VARBINARY(36); SET @B = CAST('" + CurrentUserID + "' AS VARBINARY(36)); SET CONTEXT_INFO @B";
try
{
SetCmd.ExecuteNonQuery();
}
catch (System.Exception)
{
/* Error Handling */
}
}
return Conn;
}
```
**I do not think that the application being a WPF one has any bearing on the issue I am having.**
*The issue I am having*
Despite the SqlConnection being disposed along with the DataContext in Sql Server Management studio I can still see loads of open connections with :
```
status : 'Sleeping'
command : 'AWAITING COMMAND'
last SQL Transact Command Batch : DECLARE @B VARBINARY(36); SET @B = CAST('GUID' AS VARBINARY(36)); SET CONTEXT_INFO @B
```
Eventually the connection pool gets used up and the application can't continue.
So I can only conclude that somehow running the SQLCommand to set the Context\_Info is meaning that the connection doesn't get disposed of when the DataContext gets disposed.
Can anyone spot anything obvious that would be stopping the connections from being closed and disposed of when the DataContext they are used by are disposed?
|
From [MSDN](http://msdn.microsoft.com/en-us/library/bb292288.aspx) (`DataContext Constructor (IDbConnection)`):
> If you provide an open connection, the
> DataContext will not close it.
> Therefore, do not instantiate a
> DataContext with an open connection
> unless you have a good reason to do
> this.
So basically, it looks like your connections are waiting for GC to finalize them before they will be released. If you have lots of code that does this, one approach might be to overide `Dispose()` in the data-context's partial class, and close the connection - just be sure to document that the data-context assumes ownership of the connection!
```
protected override void Dispose(bool disposing)
{
if(disposing && this.Connection != null && this.Connection.State == ConnectionState.Open)
{
this.Connection.Close();
this.Connection.Dispose();
}
base.Dispose(disposing);
}
```
Personally, I would happily give it (regular data-context, w/o the hack above) an open connection as long as I was "using" the connection (allowing me to perform multiple operations) - i.e.
```
using(var conn = GetConnection())
{
// snip: some stuff involving conn
using(var ctx = new FooContext(conn))
{
// snip: some stuff involving ctx
}
// snip: some more stuff involving conn
}
```
|
The `SqlProvider` used by the LINQ `DataContext` only closes the SQL connection (through `SqlConnectionManager.DisposeConnection`) if it was the one to open it. If you give an already-open `SqlConnection` object to the `DataContext` constructor, it will not close it for you. Thus, you should write:
```
using (SqlConnection conn = GetConnection())
using (DataContext db = new DataContext(conn))
{
... Code
}
```
|
.net SqlConnection not being closed even when within a using { }
|
[
"",
"c#",
".net",
"linq-to-sql",
"sqlconnection",
""
] |
This is one of those ajax "alternate flow" questions. Normally I expect my ajax request to return a part of the page. But sometimes it may return a full page with html, head and body tag.
At the time I return from my ajax-request I can detect if this is a full page, but is it possible to trigger a full page reload (with full event cycle) based on the string content I have ?
(And yes, I have tried replacing the body element, but that does not give me the events and does not allow me to change the content in the head block)
Any framework reference is ok
|
I don't think it's possible to do directly.
You'd be better off saving the HTML somewhere and sending back a URL where it can be retrieved, then using `location.href = ...`;
|
You can decide what to do with your [AJAX request](http://www.prototypejs.org/api/ajax/request) based on it's [HTTP status code](http://en.wikipedia.org/wiki/List_of_HTTP_status_codes).
If you get 301 ("moved permanently") you could do a redirect using `window.location`:
```
new Ajax.Request(url, {
method: 'get',
// status 200: yadaa
onSuccess: function(transport) {
// doSomething
},
// status 301: moved permanently
on301: function(transport){
window.location = transport.responseText;
}
});
```
|
Can I trigger a complete web page reload with content from a javascript string?
|
[
"",
"javascript",
"ajax",
""
] |
**ASPX Code**
```
<asp:RadioButtonList ID="rbServer" runat="server" >
<asp:ListItem Value=<%=ServerDeveloper%>> Developer </asp:ListItemv
<asp:ListItem Value="dev.ahsvendor.com"> dev.test.com</asp:ListItem>
<asp:ListItem Value="staging.ahsvendor.com"> staging.test.com</asp:ListItem>
</asp:RadioButtonList>
```
**ASPX.CS - Codebehind**
```
const string ServerDeveloper = "developer";
```
**ASPX Error**: Code blocks are not supported in this context.
**Question:** So what is the correct way to tie an dropdown/radio buttion/... ASPX value to a constant that is shared with the CodeBehind code?
I know that I could do rbServer.Add.Item("developer") [from the CodeBehind], but is there a way to achieve it from the Presentation side of things?
|
Would it be:
```
rbServer.Items.Add(ServerDeveloper)
```
Ok, so since you want to do it from presentation...It is possible, but horribly ugly:
```
<div>
<% rbServer.Items.Add(new ListItem("Dev", ServerDeveloper)); %>
<asp:RadioButtonList ID="rbServer" runat="server">
<asp:ListItem Value="Blah">Blah</asp:ListItem>
</asp:RadioButtonList>
</div>
```
Note that the code block has to be *above* the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.
|
In retrospect, the better solution would be to add it from the codebehind using rbServer.Items.Add()
|
C# (ASP.Net) Linking selection values to constants in Codebehind
|
[
"",
"c#",
"asp.net",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.