Prompt
stringlengths 10
31k
| Chosen
stringlengths 3
29.4k
| Rejected
stringlengths 3
51.1k
| Title
stringlengths 9
150
| Tags
listlengths 3
7
|
|---|---|---|---|---|
I haven't programmed games for about 10 years (My last experience was DJGPP + Allegro), but I thought I'd check out XNA over the weekend to see how it was shaping up.
I am fairly impressed, however as I continue to piece together a game engine, I have a (probably) basic question.
How much should you rely on C#'s Delegates and Events to drive the game? As an application programmer, I use delegates and events heavily, but I don't know if there is a significant overhead to doing so.
In my game engine, I have designed a "chase cam" of sorts, that can be attached to an object and then recalculates its position relative to the object. When the object moves, there are two ways to update the chase cam.
* Have an "UpdateCameras()" method in the main game loop.
* Use an event handler, and have the chase cam subscribe to object.OnMoved.
I'm using the latter, because it allows me to chain events together and nicely automate large parts of the engine. Suddenly, what would be huge and complex get dropped down to a handful of 3-5 line event handlers...Its a beauty.
However, if event handlers firing every nanosecond turn out to be a major slowdown, I'll remove it and go with the loop approach.
Ideas?
|
If you were to think of an event as a subscriber list, in your code all you are doing is registering a subscriber. The number of instructions needed to achieve that is likely to be minimal at the CLR level.
If you want your code to be generic or dynamic, then you're need to check if something is subscribed prior to calling an event. The event/delegate mechanism of C# and .NET provides this to you at very little cost (in terms of CPU).
If you're really concerned about every clock cycle, you'd never write generic/dynamic game logic. It's a trade off between maintainable/configurable code and outright speed.
Written well, I'd favour events/delegates until I could prove it is an issue.
The only way you'll truly know if it is an issue for you is by profiling your code -- which you should do anyway for any game development!
|
It's important to realize that events in C# are not queued asynchronous events (like, for example the Windows message queue). They are essentially a list of function pointers. So raising an event doesn't have worse performance implications than iterating through a list of function pointers and calling each one.
At the same time, realize that because of this, events are synchronous. If your event *listener* is slow, you'll slow down the class *raising* the events.
|
Game Programming and Event Handlers
|
[
"",
"c#",
"xna",
"camera",
""
] |
I frequently find myself writing code like this:
```
List<int> list = new List<int> { 1, 3, 5 };
foreach (int i in list) {
Console.Write("{0}\t", i.ToString()); }
Console.WriteLine();
```
Better would be something like this:
```
List<int> list = new List<int> { 1, 3, 5 };
Console.WriteLine("{0}\t", list);
```
I suspect there's some clever way of doing this, but I don't see it. Does anybody have a better solution than the first block?
|
Do this:
```
list.ForEach(i => Console.Write("{0}\t", i));
```
---
EDIT: To others that have responded - he wants them all on the same line, with tabs between them. :)
|
A different approach, just for kicks:
```
Console.WriteLine(string.Join("\t", list));
```
|
Console.WriteLine and generic List
|
[
"",
"c#",
"generics",
"console",
"list",
""
] |
Briefly: Does anyone know of a GUI for gdb that brings it on par or close to the feature set you get in the more recent version of Visual C++?
In detail: As someone who has spent a lot of time programming in Windows, one of the larger stumbling blocks I've found whenever I have to code C++ in Linux is that debugging anything using commandline gdb takes me several times longer than it does in Visual Studio, and it does not seem to be getting better with practice. Some things are just easier or faster to express graphically.
Specifically, I'm looking for a GUI that:
* Handles all the basics like stepping over & into code, watch variables and breakpoints
* Understands and can display the contents of complex & nested C++ data types
* Doesn't get confused by and preferably can intelligently step through templated code and data structures while displaying relevant information such as the parameter types
* Can handle threaded applications and switch between different threads to step through or view the state of
* Can handle attaching to an already-started process or reading a core dump, in addition to starting the program up in gdb
If such a program does not exist, then I'd like to hear about experiences people have had with programs that meet at least some of the bullet points.
Does anyone have any recommendations?
**Edit:**
Listing out the possibilities is great, and I'll take what I can get, but it would be even more helpful if you could include in your responses:
(a) Whether or not you've actually used this GUI and if so, what positive/negative feedback you have about it.
(b) If you know, which of the above-mentioned features are/aren't supported
Lists are easy to come by, sites like this are great because you can get an idea of people's personal experiences with applications.
|
You won't find *anything* overlaying GDB which can compete with the raw power of the Visual Studio debugger. It's just too powerful, and it's just too well integrated inside the IDE.
For a Linux alternative, try DDD if free software is your thing.
|
Eclipse CDT will provide an experience comparable to using Visual Studio. I use Eclipse CDT on a daily basis for writing code and debugging local and remote processes.
If you're not familiar with using an Eclipse based IDE, the GUI will take a little getting used to. However, once you get to understand the GUI ideas that are unique to Eclipse (e.g. a perspective), using the tool becomes a nice experience.
The CDT tooling provides a decent C/C++ indexer that allows you to quickly find references to methods in your code base. It also provides a nice macro expansion tool and limited refactoring support.
With regards to support for debugging, CDT is able to do everything in your list with the exception of reading a core dump (it may support this, but I have never tried to use this feature). Also, my experience with debugging code using templates is limited, so I'm not sure what kind of experience CDT will provide in this regard.
For more information about debugging using Eclipse CDT, you may want to check out these guides:
* [Interfacing with the CDT debugger, Part 2: Accessing gdb with the Eclipse CDT and MI](http://www.ibm.com/developerworks/library/os-eclipse-cdt-debug2/index.html)
* [CDT Debug Tutorial](http://download.eclipse.org/tools/cdt/docs/tutorials/debug_tutorial/cdt_w_debug.htm)
|
Is there a C++ gdb GUI for Linux?
|
[
"",
"c++",
"linux",
"gdb",
"debugging",
""
] |
In my application I have a DataGridView control that displays data for the selected object. When I select a different object (in a combobox above), I need to update the grid. Unfortunately different objects have completely different data, even different columns, so I need to clear all the existing data and columns, create new columns and add all the rows. When this is done, the whole control flickers horribly and it takes ages. Is there a generic way to get the control in an update state so it doesn't repaint itself, and then repaint it after I finish all the updates?
It is certainly possible with TreeViews:
```
myTreeView.BeginUpdate();
try
{
//do the updates
}
finally
{
myTreeView.EndUpdate();
}
```
Is there a generic way to do this with other controls, DataGridView in particular?
UPDATE: Sorry, I am not sure I was clear enough. I see the "flickering", because after single edit the control gets repainted on the screen, so you can see the scroll bar shrinking, etc.
|
Rather than adding the rows of the data grid one at a time, use the `DataGridView.Rows.AddRange` method to add all the rows at once. That should only update the display once. There's also a `DataGridView.Columns.AddRange` to do the same for the columns.
|
People seem to forget a simple fix for this:
```
Object.Visible = false;
//do update work
Object.Visible = true;
```
I know it seems weird, but that works. When the object is not visible, it won't redraw itself. You still, however, need to do the `begin` and `end` update.
|
Flickering during updates to Controls in WinForms (e.g. DataGridView)
|
[
"",
"c#",
".net",
"winforms",
""
] |
One of the things I'd like to do in my browser-based application is allow the user to select some text (not in a <textarea>, just plain ol' text!), and have my application pop up a small toolbar that then can interact with the next (in my case, add annotations).
I've found a lot of stuff on google that seems to be focused on writing WYSIWYG editors, **but that isn't what I want**, and most of it worked in IE but not in FF2 or 3. Ideally, I'd like some function that can return the currently selected text in the browser window that works in **IE7 (and 6 if possible), FireFox 2 & 3 and Safari 2**. If it works in Opera, that'd be a bonus, but it's not a requirement.
Anyone have a function that does this? Or an idea of where to start?
|
Have a look at [jQuery](http://jquery.com) and the [wrapSelection plugin](http://plugins.jquery.com/project/wrapSelection). It may be what you are looking for.
|
That jQuery plugin is cool but it accomplishes a very specific task: wrap the text you highlight with a tag. This may be just what you want. But if you don't want to (or are in a situation where you can't) add any extraneous markup to your page, you might try the following solution instead:
```
function getSelectedText() {
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
}
else if (document.getSelection) {
txt = document.getSelection();
}
else if (document.selection) {
txt = document.selection.createRange().text;
}
else return;
return txt;
}
```
This function returns an object representing the text selection. It works across browsers (though I suspect the objects it returns will be slightly different depending on the browser and only dependable for the actual text of the result rather than any of the additional properties).
Note: I originally discovered that code fragment here: <http://www.codetoad.com/javascript_get_selected_text.asp>
|
Getting selected text in a browser, cross-platform
|
[
"",
"javascript",
"browser",
""
] |
I need to read from Outlook .MSG file in .NET *without* using COM API for Outlook (cos it will not be installed on the machines that my app will run). Are there any free 3rd party libraries to do that? I want to extract From, To, CC and BCC fields. Sent/Receive date fields would be good if they are also stored in MSG files.
|
**Update:** I have found a 3rd party COM library called [Outlook Redemption](http://www.dimastr.com/redemption/) which is working fine for me at the moment. If you use it via COM-Interop in .NET, don't forget to release every COM object after you are done with it, otherwise your application crashes randomly.
|
There is code avaliable on CodeProject for reading .msg files without COM. See [here](http://www.codeproject.com/KB/office/reading_an_outlook_msg.aspx).
|
Read from .msg files
|
[
"",
"c#",
"outlook",
"email",
"message",
"msg",
""
] |
In my C++ program I want to parse a small piece of XML, insert some nodes, then extract the new XML (preferably as a `std::string`).
[RapidXml](http://rapidxml.sourceforge.net/) has been recommended to me, but I can't see how to retrieve the XML back as a text string.
(I could iterate over the nodes and attributes and build it myself, but surely there's a build in function that I am missing.)
Thank you.
|
Althoug the documentation is poor on this topic, I managed to get some working code by looking at the source. Although it is missing the xml header which normally contains important information. Here is a small example program that does what you are looking for using rapidxml:
```
#include <iostream>
#include <sstream>
#include "rapidxml/rapidxml.hpp"
#include "rapidxml/rapidxml_print.hpp"
int main(int argc, char* argv[]) {
char xml[] = "<?xml version=\"1.0\" encoding=\"latin-1\"?>"
"<book>"
"</book>";
//Parse the original document
rapidxml::xml_document<> doc;
doc.parse<0>(xml);
std::cout << "Name of my first node is: " << doc.first_node()->name() << "\n";
//Insert something
rapidxml::xml_node<> *node = doc.allocate_node(rapidxml::node_element, "author", "John Doe");
doc.first_node()->append_node(node);
std::stringstream ss;
ss <<*doc.first_node();
std::string result_xml = ss.str();
std::cout <<result_xml<<std::endl;
return 0;
}
```
|
Use `print` function (found in `rapidxml_print.hpp` utility header) to print the XML node contents to a `stringstream`.
|
C++: How to extract a string from RapidXml
|
[
"",
"c++",
"xml",
"rapidxml",
""
] |
I'm working on an exceedingly large codebase, and recently upgraded to GCC 4.3, which now triggers this warning:
> warning: deprecated conversion from string constant to ‘char\*’
Obviously, the correct way to fix this is to find every declaration like
```
char *s = "constant string";
```
or function call like:
```
void foo(char *s);
foo("constant string");
```
and make them `const char` pointers. However, that would mean touching 564 files, minimum, which is not a task I wish to perform at this point in time. The problem right now is that I'm running with [-Werror](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Werror), so I need some way to stifle these warnings. How can I do that?
|
I believe passing [-Wno-write-strings](https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-Wno-write-strings) to GCC will suppress this warning.
|
Any functions into which you pass string literals `"I am a string literal"` should use `char const *` as the type instead of `char*`.
If you're going to fix something, fix it right.
**Explanation:**
You can not use string literals to initialise strings that will be modified, because they are of type `const char*`. Casting away the constness to later modify them is [undefined behaviour](https://stackoverflow.com/questions/3801557/can-we-change-the-value-of-an-object-defined-with-const-through-pointers), so you have to copy your `const char*` strings `char` by `char` into dynamically allocated `char*` strings in order to modify them.
**Example:**
```
#include <iostream>
void print(char* ch);
void print(const char* ch) {
std::cout<<ch;
}
int main() {
print("Hello");
return 0;
}
```
|
How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC
|
[
"",
"c++",
"string",
"gcc",
""
] |
How do I find the start of the week (both Sunday and Monday) knowing just the current time in C#?
Something like:
```
DateTime.Now.StartWeek(Monday);
```
|
Use an extension method:
```
public static class DateTimeExtensions
{
public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
{
int diff = (7 + (dt.DayOfWeek - startOfWeek)) % 7;
return dt.AddDays(-1 * diff).Date;
}
}
```
Which can be used as follows:
```
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
DateTime dt = DateTime.Now.StartOfWeek(DayOfWeek.Sunday);
```
|
The quickest way I can come up with is:
```
var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek);
```
If you would like any other day of the week to be your start date, all you need to do is add the DayOfWeek value to the end
```
var monday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Monday);
var tuesday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek + (int)DayOfWeek.Tuesday);
```
|
How can I get the DateTime for the start of the week?
|
[
"",
"c#",
"datetime",
""
] |
The only *nice* way I've found is:
```
import sys
import os
try:
os.kill(int(sys.argv[1]), 0)
print "Running"
except:
print "Not running"
```
([Source](http://www.unix.com/unix-advanced-expert-users/79267-trick-bash-scripters-check-if-process-running.html))
But is this reliable? Does it work with every process and every distribution?
|
Mark's answer is the way to go, after all, that's why the /proc file system is there. For something a little more copy/pasteable:
```
>>> import os.path
>>> os.path.exists("/proc/0")
False
>>> os.path.exists("/proc/12")
True
```
|
on linux, you can look in the directory /proc/$PID to get information about that process. In fact, if the directory exists, the process is running.
|
How to check if a process is still running using Python on Linux?
|
[
"",
"python",
"linux",
"unix",
"process",
""
] |
```
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class Problem {
@ManyToOne
private Person person;
}
@Entity
@DiscriminatorValue("UP")
public class UglyProblem extends Problem {}
@Entity
public class Person {
@OneToMany(mappedBy="person")
private List< UglyProblem > problems;
}
```
I think it is pretty clear what I am trying to do. I expect @ManyToOne person to be inherited by UglyProblem class. But there will be an exception saying something like: "There is no such property found in UglyProblem class (mappedBy="person")".
All I found is [this](http://opensource.atlassian.com/projects/hibernate/browse/ANN-558). I was not able to find the post by Emmanuel Bernard explaining reasons behind this.
---
> Unfortunately, according to the Hibernate documentation "Properties from superclasses not mapped as @MappedSuperclass are ignored."
Well I think this means that if I have these two classes:
```
public class A {
private int foo;
}
@Entity
public class B extens A {
}
```
then field `foo` will not be mapped for class B. Which makes sense. But if I have something like this:
```
@Entity
public class Problem {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
@Entity
public class UglyProblem extends Problem {
private int levelOfUgliness;
public int getLevelOfUgliness() {
return levelOfUgliness;
}
public void setLevelOfUgliness(int levelOfUgliness) {
this.levelOfUgliness = levelOfUgliness;
}
}
```
I expect the class UglyProblem to have fileds `id` and `name` and both classes to be mapped using same table. (In fact, this is exactly what happens, I have just checked again). I have got this table:
```
CREATE TABLE "problem" (
"DTYPE" varchar(31) NOT NULL,
"id" bigint(20) NOT NULL auto_increment,
"name" varchar(255) default NULL,
"levelOfUgliness" int(11) default NULL,
PRIMARY KEY ("id")
) AUTO_INCREMENT=2;
```
Going back to my question:
> I expect @ManyToOne person to be inherited by UglyProblem class.
I expect that because all other mapped fields are inherited and I do not see any reason to make this exception for ManyToOne relationships.
---
Yeah, I saw that. In fact, I used Read-Only solution for my case. But my question was "Why..." :). I know that there is an explanation given by a member of hibernate team. I was not able to find it and that is why I asked.
I want to find out the motivation of this design decision.
(if you interested how I have faced this problem: I inherited a project built using hibernate 3. It was Jboss 4.0.something + hibernate was already there (you'd download it all together). I was moving this project to Jboss 4.2.2 and I found out that there are inherited mappings of "@OneToMany mappedBy" and it worked fine on old setup...)
|
I think it's a wise decision made by the Hibernate team. They could be less arrogante and make it clear why it was implemented this way, but that's just how Emmanuel, Chris and Gavin works. :)
Let's try to understand the problem. I think your concepts are "lying". First you say that many **Problem**s are associated to **People**. But, then you say that one **Person** have many **UglyProblem**s (and does not relate to other **Problem**s). Something is wrong with that design.
Imagine how it's going to be mapped to the database. You have a single table inheritance, so:
```
_____________
|__PROBLEMS__| |__PEOPLE__|
|id <PK> | | |
|person <FK> | -------->| |
|problemType | |_________ |
--------------
```
How is hibernate going to enforce the database to make **Problem** only relate to **People** if its **problemType** is equal UP? That's a very difficult problem to solve. So, if you want this kind of relation, every subclass must be in it's own table. That's what `@MappedSuperclass` does.
PS.: Sorry for the ugly drawing :D
|
In my case I wanted to use the SINGLE\_TABLE inheritance type, so using @MappedSuperclass wasn't an option.
What works, although not very clean, is to add the Hibernate proprietary [@Where](http://docs.jboss.org/hibernate/orm/4.2/javadocs/org/hibernate/annotations/Where.html) clause to the @OneToMany association to force the type in queries:
```
@OneToMany(mappedBy="person")
@Where(clause="DTYPE='UP'")
private List< UglyProblem > problems;
```
|
Why @OneToMany does not work with inheritance in Hibernate
|
[
"",
"java",
"hibernate",
"inheritance",
"orm",
""
] |
In the project I am currently working on, we have the need to develop a web chat application, not a very complex chat, just a way to connect two people to talk about a very specific topic, we don't need any kind of authentication for one of the two users, we don't have to support emoticons, avatars, or stuff like that.
Some project members suggested that we could use XMPP through BOSH, I said that is like trying to catch a fish with a boat's net, and proposed a simpler method, like a simple Ajax/MySQL web chat, but we're worried about the performance hit in the server because of the constant polling of many chats open at the same time.
Has anyone done something like this before? What would you recommend?
|
You might also want to look into [Comet](http://en.wikipedia.org/wiki/Comet_(programming)).
It's used by GTalk, Meebo, and many [other chat applications](http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications). A few years ago when I was experimenting with it, there weren't very many libraries or details about server architecture to implement it, but it looks like there is a lot more stuff out now.
Have a look at the [cometd](http://cometdproject.dojotoolkit.org/) project for more technical information.
|
> What would you recommend?
XMPP through BOSH
There's no need to invent your own message format and transport protocol when somebody else has. If you try, it'll slowly grow to be just as complex as BOSH but without the benefit of third-party library support or standardization.
|
Chat application AJAX polling
|
[
"",
"php",
"ajax",
"chat",
""
] |
Is there any shorthand way of defining and using generic definitions without having to keep repeating a particular generic description such that if there is a change I don't have to change all definitions/usages though out the codebase for example is something like this possible:
```
Typedef myGenDef = < Object1, Object2 >;
HashMap< myGenDef > hm = new HashMap< myGenDef >();
for (Entry< myGenDef > ent : hm..entrySet())
{
.
.
.
}
```
|
There's the [pseudo-typedef antipattern](http://www.ibm.com/developerworks/java/library/j-jtp02216/index.html)...
```
class StringList extends ArrayList<String> { }
```
Good stuff, drink up! ;-)
As the article notes, this technique has some serious issues, primarily that this "typedef" is actually a separate class and thus cannot be used interchangeably with either the type it extends or other similarly defined types.
|
In a generic method, you can use a limited form of type inferrence to avoid some repetitions.
Example: if you have the function
```
<K, V> Map<K, V> getSomething() {
//...
}
```
you can use:
```
final Map<String, Object> something = getsomething();
```
instead of:
```
final Map<String, Object> something = this.<String, Object>getsomething();
```
|
Generics in Java
|
[
"",
"java",
"generics",
""
] |
If you create an Oracle dblink you cannot directly access LOB columns in the target tables.
For instance, you create a dblink with:
```
create database link TEST_LINK
connect to TARGETUSER IDENTIFIED BY password using 'DATABASESID';
```
After this you can do stuff like:
```
select column_a, column_b
from data_user.sample_table@TEST_LINK
```
Except if the column is a LOB, then you get the error:
```
ORA-22992: cannot use LOB locators selected from remote tables
```
This is [a documented restriction](http://docs.oracle.com/cd/B10501_01/appdev.920/a96591/adl04mng.htm#98328).
The same page suggests you fetch the values into a local table, but that is... kind of messy:
```
CREATE TABLE tmp_hello
AS SELECT column_a
from data_user.sample_table@TEST_LINK
```
Any other ideas?
|
Yeah, it is messy, I can't think of a way to avoid it though.
You could hide some of the messiness from the client by putting the temporary table creation in a stored procedure (and using "execute immediate" to create they table)
One thing you will need to watch out for is left over temporary tables (should something fail half way through a session, before you have had time to clean it up) - you could schedule an oracle job to periodically run and remove any left over tables.
|
The best solution by using a query as below, where column\_b is a BLOB:
```
SELECT (select column_b from sample_table@TEST_LINK) AS column_b FROM DUAL
```
|
Best way to handle LOBs in Oracle distributed databases
|
[
"",
"sql",
"oracle",
"distributed-transactions",
"dblink",
""
] |
I had an idea, if I add a python .py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process.
Does anyone know if such a custom generator for Visual Studio 2008 exists?
|
OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own [here](http://www.drewnoakes.com/snippets/WritingACustomCodeGeneratorToolForVisualStudio/).
Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.
|
I think [Cog](http://nedbatchelder.com/code/cog/) does what you want.
|
Python code generator for Visual Studio?
|
[
"",
"python",
"visual-studio-2008",
"code-generation",
""
] |
We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur.
We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the following features:
* portable to Linux
* some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code
* animation
* we need to be able to overlay video
* not resource intensive (these terminals don't have a lot of memory or CPU)
* we're currently using C++, so management would prefer that, but other languages would be considered
* We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.)
We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box.
Any suggestions for off-the-shelf stuff we could use?
|
Maybe the way to go is something like [Clutter](http://clutter-project.org/) or [Allegro](http://www.allegro.cc/). If you check in this [article](http://arstechnica.com/news.ars/post/20080604-hands-on-with-the-ubuntu-netbook-remix.html) at ArsTechnica what they are using Clutter for, you might get an idea how to use it. I don't know for sure if it works on Windows, but I'm pretty sure it does, considering it only depends on libraries that are supported under Windows.
|
"We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box."
You realize that Trolltech's QT has a style sheet language for widgets? Take a look at their white paper, specifically page 60
<http://trolltech.com/pdf/qt43-whitepaper-us.pdf>
Going over your other requirements:
* portable to Linux
Yes. Also supports Windows, Mac, and embedded environments.
* some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code
Qt's Designer is a very nice tool. I use it all the time.
* animation
Qt supports this.
* we need to be able to overlay video
Qt supports this.
* not resource intensive (these terminals don't have a lot of memory or CPU)
This might be the fly in the ointment. You could check out Qt's embedded option. I've never used that myself.
* we're currently using C++, so management would prefer that, but other languages would be considered
Qt is for C++ and works with all major compilers.
* We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.)
Qt has both open-source and closed source options.
|
Simple Frameworks for Displaying Bitmaps and Handling Button Presses
|
[
"",
"c++",
"user-interface",
"graphics",
"bitmap",
""
] |
Let's say that you want to create a dead simple BlogEditor and, one of your ideas, is to do what Live Writer does and ask only the URL of the persons Blog. How can you detect what type of blog is it?
Basic detection can be done with the URL itself, such as “<http://myblog.blogger.com>” etc. But what if it's self hosted?
I'm mostly interested on how to do this in Java, but this question could be also used as a reference for any other language.
|
Many (most?) blogs will have a meta tag for "generator" which will list the blog engine. For example a blogger blog will contain the following meta tag:
```
<meta name="generator" content="Blogger" />
```
My Subtext blog shows the following generator meta tag:
```
<meta name="Generator" content="Subtext Version 1.9.5.177" />
```
This meta tag would be the first place to look. For blogs that don't set this meta tag in the source, you'd have to resort to looking for patterns to determine the blog type.
|
Some blogs provide a Generator meta tag - e.g. Wordpress - you could find out if there's any exceptions to this.
You'll have to be careful how you detect it though, Google surprised me with this line:
```
<meta content='blogger' name='generator'/>
```
Single quotes are blasphemy.
|
How to detect which blog API
|
[
"",
"java",
"api",
"blogs",
""
] |
Does anyone know if the Infragistics UltraGrid control provides functionality similar to that of DataGridView.HitTestInfo?
|
Check [this](http://www.abstraction-systems.com/ttf/HTML/TTFactory_TaskBasedTutorials_UltraWinGrid.htm) out.
They don't convert the coordinates, but they use a special Infragistics grid event ([MouseEnterElement](http://help.infragistics.com/Help/NetAdvantage/NET/2008.2/CLR2.0/html/Infragistics2.Win.v8.2~Infragistics.Win.UltraComponentControlManagerBase~MouseEnterElement_EV.html)) to get the element, which the mouse currently hovers over.
Maybe it helps.
|
There's a `.MousePosition` property which returns `System.Drawing.Point` and "Gets the position of the mouse cursor in screen coordinates" but I'm using an older version of their UltraWinGrid (2003).
They have a [free trial download](http://www.infragistics.com/downloads/default.aspx), so you could see if they've added it to their latest and greatest :o)
|
DataGridView.HitTestInfo equivalent in Infragistics.Win.UltraWinGrid.UltraGrid?
|
[
"",
"c#",
".net",
"infragistics",
"ultrawingrid",
""
] |
Well behaved windows programs need to allow users to save their work when they are shutting the PC down.
How can I make my app detect the shutdown event? Any solution should allow the user to abort the shutdown if user selects, say "Cancel".
The normal Swing window closing hook doesn't work, nor does adding a shutdown hook.
On testing, the methods of WindowListener (windowClosing,windowClosed, etc) do not get called.
The answer I have accepted requires the use of platform specific code (JNI to register for WM\_QUERYENDSESSION ). Isn't this a bug on Swing?
See <http://forums.sun.com/thread.jspa?threadID=481807&messageID=2246870>
|
Write some JNI code to WM\_QUERYENDSESSION message. You can get details for this from the MSDN documentation or by googling it.
If you don't want to write too much C++ code to do this I can recommend the JNA library [click here](https://jna.dev.java.net/). Which gives you some nice Java abstractions for C code.
|
[how-do-i-get-my-java-application-to-shutdown-nicely-in-windows](https://stackoverflow.com/questions/61692/how-do-i-get-my-java-application-to-shutdown-nicely-in-windows)
That might be of help
|
How can I detect from a Swing app that the PC is being shut-down?
|
[
"",
"java",
"swing",
"operating-system",
""
] |
For various reasons calling `System.exit` is frowned upon when writing **Java Applications**, so how can I notify the calling process that not everything is going according to plan?
**Edit:** The 1 is a `standin` for any non-zero exit code.
|
The use of `System.exit` is frowned upon when the 'application' is really a sub-application (e.g. servlet, applet) of a larger Java application (server): in this case the `System.exit` could stop the JVM and hence also all other sub-applications. In this situation, throwing an appropriate exception, which could be caught and handled by the application framework/server is the best option.
If the java application is really meant to be run as a standalone application, there is nothing wrong with using `System.exit`. in this case, setting an exit value is probably the easiest (and also most used) way of communicating failure or success to the parent process.
|
I agree with the "*throw an Exception*" crowd. One reason is that calling System.exit makes your code difficult to use if you want other code to be able to use it. For example, if you find out that your class would be useful from a web app, or some kind of message consuming app, it would be nice to allow those containers the opportunity to deal with the failure somehow. A container may want to retry the operation, decide to log and ignore the problem, send an email to an administrator, etc.
An exception to this would be your `main()` method; this could trap the Exception, and call `System.exit()` with some value that can be recognized by the calling process or shell script.
|
Alternatives to System.exit(1)
|
[
"",
"java",
"process",
""
] |
I need to run a JavaScript function onLoad(), but only do it if the page loaded the first time (i.e. is not the result of a postback).
Basically, I need to check for IsPostBack in JavaScript.
Thank you.
|
Server-side, write:
```
if(IsPostBack)
{
// NOTE: the following uses an overload of RegisterClientScriptBlock()
// that will surround our string with the needed script tags
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
}
```
Then, in your script which runs for the onLoad, check for the existence of that variable:
```
if(isPostBack) {
// do your thing
}
```
---
You don't really need to set the variable otherwise, like Jonathan's solution. The client-side if statement will work fine because the "isPostBack" variable will be undefined, which evaluates as false in that if statement.
|
There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:
```
if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
```
or
```
if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}
```
|
How can I check for IsPostBack in JavaScript?
|
[
"",
"asp.net",
"javascript",
""
] |
If I have the following:
```
{"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"}
{"Make":"Toyota","Model":"Corolla","Year":"2008"}
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
}
```
And I have a "hdrs" name (i.e. "Make"), how can I reference the `data` array instances?
seems like `data["Make"][0]` should work...but unable to get the right reference
**EDIT**
Sorry for the ambiguity.. I can loop through `hdrs` to get each hdr name, but I need to use each instance value of `hdrs` to find all the data elements in `data` (not sure that is any better of an explanation). and I will have it in a variable `t` since it is JSON (appreciate the re-tagging) I would like to be able to reference with something like this: `t.data[hdrs[i]][j]`
|
I had to alter your code a little:
```
var x = {"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"},
{"Make":"Toyota","Model":"Corolla","Year":"2008"},
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
};
alert( x.data[0].Make );
```
EDIT: in response to your edit
```
var x = {"hdrs": ["Make","Model","Year"],
"data" : [
{"Make":"Honda","Model":"Accord","Year":"2008"},
{"Make":"Toyota","Model":"Corolla","Year":"2008"},
{"Make":"Honda","Model":"Pilot","Year":"2008"}]
};
var Header = 0; // Make
for( var i = 0; i <= x.data.length - 1; i++ )
{
alert( x.data[i][x.hdrs[Header]] );
}
```
|
First, you forgot your trailing commas in your **data** array items.
Try the following:
```
var obj_hash = {
"hdrs": ["Make", "Model", "Year"],
"data": [
{"Make": "Honda", "Model": "Accord", "Year": "2008"},
{"Make": "Toyota", "Model": "Corolla", "Year": "2008"},
{"Make": "Honda", "Model": "Pilot", "Year": "2008"},
]
};
var ref_data = obj_hash.data;
alert(ref_data[0].Make);
```
@Kent Fredric: note that the last comma is not strictly needed, but allows you to more easily move lines around (i.e., if you move or add after the last line, and it didn't have a comma, you'd have to specifically remember to add one). I think it's best to always have trailing commas.
|
Javascript array reference
|
[
"",
"javascript",
"json",
""
] |
I am writing a program that needs to send out an email every hour on the hour, but at a time local to the user.
Say I have 2 users in different time zones. John is in New York and Fred is in Los Angeles. The server is in Chicago. If I want to send an email at 6 PM local to each user, I'd have to send the email to John at 7 PM Server time and Fred at 4 PM Server time.
What's a good approach to this in .NET / Sql Server? I have found an xml file with all of the time zone information, so I am considering writing a script to import it into the database, then querying off of it.
**Edit:** I used “t4znet.dll” and did all comparisons on the .NET side.
|
You have two options:
* Store the adjusted time for the mail action into the database for each user. Then just compare server time with stored time. To avoid confusion and portability issues, I would store all times in UTC. So, send mail when SERVER\_UTC\_TIME() == storedUtcTime.
* Store the local time for each mail action into the database, then convert on-the-fly. Send mail when SERVER\_UTC\_TIME() == TO\_UTC\_TIME(storedLocalTime, userTimeZone).
You should decide what makes most sense for your application. For example if the mailing time is always the same for all users, it makes more sense to go with option (2). If the events times can change between users and even per user, it may make development and debugging easier if you choose option (1). Either way you will need to know the user's time zone.
\*These function calls are obviously pseudo, since I don't know their invocations in T-SQL, but they should exist.
|
You can complement your solution with this excellent article "[World Clock and the TimeZoneInformation class](http://www.codeproject.com/KB/dotnet/WorldClock.aspx)", I made a webservice that sent a file with information that included the local and receiver time, what I did was to modify this class so I could handle that issue and it worked perfect, exactly as I needed.
I think you could take this class and obtain from the table "Users" the time zone of them and "calculate" the appropiate time, my code went like this;
```
//Get correct destination time
DateTime thedate = DateTime.Now;
string destinationtimezone = null;
//Load the time zone where the file is going
TimeZoneInformation tzi = TimeZoneInformation.FromName(this.m_destinationtimezone);
//Calculate
destinationtimezone = tzi.FromUniversalTime(thedate.ToUniversalTime()).ToString();
```
This class has an issue in Windows Vista that crashes the "FromIndex(int index)" function but you can modify the code, instead of using the function:
```
public static TimeZoneInformation FromIndex(int index)
{
TimeZoneInformation[] zones = EnumZones();
for (int i = 0; i < zones.Length; ++i)
{
if (zones[i].Index == index)
return zones[i];
}
throw new ArgumentOutOfRangeException("index", index, "Unknown time zone index");
}
```
You can change it to;
```
public static TimeZoneInformation FromName(string name)
{
TimeZoneInformation[] zones = EnumZones();
foreach (TimeZoneInformation tzi in zones)
{
if (tzi.DisplayName.Equals(name))
return tzi;
}
throw new ArgumentOutOfRangeException("name", name, "Unknown time zone name");
}
```
|
How to send out email at a user's local time in .NET / Sql Server?
|
[
"",
"sql",
".net",
"sql-server",
"timezone",
""
] |
I've got a problem similar to,but subtly different from, that described [here](https://stackoverflow.com/questions/22012/loading-assemblies-and-its-dependencies) (Loading assemblies and their dependencies).
I have a C++ DLL for 3D rendering that is what we sell to customers. For .NET users we will have a CLR wrapper around it. The C++ DLL can be built in both 32 and 64bit versions, but I think this means we need to have two CLR wrappers since the CLR binds to a specific DLL?
Say now our customer has a .NET app that can be either 32 or 64bit, and that it being a pure .NET app it leaves the CLR to work it out from a single set of assemblies. The question is how can the app code dynamically choose between our 32 and 64bit CLR/DLL combinations at run-time?
Even more specifically, is the suggested answer to the aforementioned question applicable here too (i.e. create a ResolveEvent handler)?
|
I finally have an answer for this that appears to work.
Compile both 32 & 64 bit versions - both managed & unmanaged - into separate folders. Then have the .NET app choose at run time which directory to load the assemblies from.
The problem with using the ResolveEvent is that it only gets called if assemblies aren't found, so it is all to easy to accidentally end up with 32 bit versions. Instead use a second AppDomain object where we can change the ApplicationBase property to point at the right folder. So you end up with code like:
```
static void Main(String[] argv)
{
// Create a new AppDomain, but with the base directory set to either the 32-bit or 64-bit
// sub-directories.
AppDomainSetup objADS = new AppDomainSetup();
System.String assemblyDir = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
switch (System.IntPtr.Size)
{
case (4): assemblyDir += "\\win32\\";
break;
case (8): assemblyDir += "\\x64\\";
break;
}
objADS.ApplicationBase = assemblyDir;
// We set the PrivateBinPath to the application directory, so that we can still
// load the platform neutral assemblies from the app directory.
objADS.PrivateBinPath = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
AppDomain objAD = AppDomain.CreateDomain("", null, objADS);
if (argv.Length > 0)
objAD.ExecuteAssembly(argv[0]);
else
objAD.ExecuteAssembly("MyApplication.exe");
AppDomain.Unload(objAD);
}
```
You end up with 2 exes - your normal app and a second switching app that chooses which bits to load.
Note - I can't take credit for the details of this myself. One of my colleagues sussed that out given my initial pointer. If and when he signs up to StackOverflow I'll assign the answer to him
|
I was able to do this about a year ago, but I no longer remember all of the details. Basically, you can use IntPtr.Size to determine which DLL to load, then perform the actual LoadLibrary through p/Invoke. At that point, you've got the module in memory and you ought to be able to just p/Invoke functions from inside of it -- the same module name shouldn't get reloaded again.
I think, though, that in my application I actually had the C++ DLL register itself as a COM server and then accessed its functionality through a generated .NET wrapper -- so I don't know if I ever tested p/Invoking directly.
|
How to late bind 32bit/64 bit libs at runtime
|
[
"",
"c#",
".net",
"64-bit",
"clr",
"x86-64",
""
] |
I have been working with Struts for some time, but for a project I am finishing I was asked to separate Templates (velocity .vm files), configs (struts.xml, persistence.xml) from main WAR file.
I have all in default structure like:
```
application
|-- META-INF -- Some configs are here
|-- WEB-INF -- others here
| |-- classes
| | |-- META-INF
| | `-- mypackage
| | `-- class-files
| `-- lib
|-- css
`-- tpl -- Template dir to be relocated
```
And I apparently can't find documentation about how to setup (probably in struts.xml) where my templates go, and where config files will be.
I think I will have to use configurations on the application server too (I am using Jetty 5.1.14).
So, any lights on how to configure it ?
Thanks
---
Well, the whole thing about changing templates place is to put the templates in a designer accessible area, so any modification needed, the designer can load them to his/her computer, edit, and upload it again. I think this is a common scenario. So, probably I am missing something in my research. Maybe I am focusing in configuring it on the wrong place ... Any thoughts ?
|
If I understood your question about Struts config files right, they are specified in web.xml. Find the Struts servlet config param. The param-value can be a list of comma separated list of XML files to load. Eg:
```
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>
WEB-INF/config/struts-config.xml,
WEB-INF/config/struts-config-stuff.xml,
WEB-INF/config/struts-config-good.xml,
WEB-INF/config/struts-config-bad.xml,
WEB-INF/config/struts-config-ugly.xml
</param-value>
</init-param>
...
</servlet>
```
See this [Struts guide](http://struts.apache.org/1.x/userGuide/configuration.html) under 5.3.2. And yes, this applies to 2.x also.
|
For *persistence.xml*, specifically, you can put a persistence unit in a separate JAR, which you can deploy separately from your web application WAR, or both together in an EAR archive, depending on what your application server supports. For example, the JBoss manual describes this as [Deploy EAR with EJB3 JAR](http://www.jboss.org/file-access/default/members/jbossas/freezone/docs/Server_Configuration_Guide/beta422/html/ch01s04s02.html).
For *struts-config.xml* I expect that you are going to have to override the Struts code that loads it, if you want to use a non-standard location.
I don't know about the Velocity templates.
In general, web applications only load resources from within the WAR, for security reasons. There are other techniques you can use, but you may find it easier to try [weblets](https://weblets.dev.java.net/), which seems to be a framework designed to let you load resources from a separate JAR.
|
Changing default file structure in a Java Struts App
|
[
"",
"java",
"templates",
"struts",
"configuration-files",
""
] |
I'm looking for a way to get the size of an instance of a reference type. sizeof is only for value types. Is this possible?
|
If you don't mind it being a little less accurate than perfect, and for comparative purposes, you could serialize the object/s and measure that (in bytes for example)
*EDIT (I kept thinking after posting)*: Because it's a little more complicated than sizeof for valuetypes, for example: reference types can have references to other objects and so on... there's not an exact and easy way to do it that I know of...
|
You need [Marshal.SizeOf](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.sizeof.aspx)
**Edit:** This *is* for unsafe code, but then, so is sizeof().
|
sizeof() equivalent for reference types?
|
[
"",
"c#",
".net",
""
] |
I'm fairly new to the STL, so I was wondering whether there are any dynamically sortable containers? At the moment my current thinking is to use a vector in conjunction with the various sort algorithms, but I'm not sure whether there's a more appropriate selection given the (presumably) linear complexity of inserting entries into a sorted vector.
To clarify "dynamically", I am looking for a container that I can modify the sorting order at runtime - e.g. sort it in an ascending order, then later re-sort in a descending order.
|
If you know you're going to be sorting on a single value ascending and descending, then set is your friend. Use a reverse iterator when you want to "sort" in the opposite direction.
If your objects are complex and you're going to be sorting in many different ways based on the member fields within the objects, then you're probably better off with using a vector and sort. Try to do your inserts all at once, and then call sort once. If that isn't feasible, then deque may be a better option than the vector for large collections of objects.
I think that if you're interested in *that* level of optimization, you had better be profiling your code using actual data. (Which is probably the best advice anyone here can give: it may not matter that you call sort after each insert if you're only doing it once in a blue moon.)
|
You'll want to look at std::map
```
std::map<keyType, valueType>
```
The map is sorted based on the < operator provided for keyType.
Or
```
std::set<valueType>
```
Also sorted on the < operator of the template argument, but does not allow duplicate elements.
There's
```
std::multiset<valueType>
```
which does the same thing as std::set but allows identical elements.
I highly reccomend "The C++ Standard Library" by Josuttis for more information. It is the most comprehensive overview of the std library, very readable, and chock full of obscure and not-so-obscure information.
Also, as mentioned by 17 of 26, Effective Stl by Meyers is worth a read.
|
Dynamically sorted STL containers
|
[
"",
"c++",
"stl",
"containers",
""
] |
I find that the .NET event model is such that I'll often be raising an event on one thread and listening for it on another thread. I was wondering what the cleanest way to marshal an event from a background thread onto my UI thread is.
Based on the community suggestions, I've used this:
```
// earlier in the code
mCoolObject.CoolEvent+=
new CoolObjectEventHandler(mCoolObject_CoolEvent);
// then
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
if (InvokeRequired)
{
CoolObjectEventHandler cb =
new CoolObjectEventHandler(
mCoolObject_CoolEvent);
Invoke(cb, new object[] { sender, args });
return;
}
// do the dirty work of my method here
}
```
|
A couple of observations:
* Don't create simple delegates explicitly in code like that unless you're pre-2.0 so you could use:
```
BeginInvoke(new EventHandler<CoolObjectEventArgs>(mCoolObject_CoolEvent),
sender,
args);
```
* Also you don't need to create and populate the object array because the args parameter is a "params" type so you can just pass in the list.
* I would probably favor `Invoke` over `BeginInvoke` as the latter will result in the code being called asynchronously which may or may not be what you're after but would make handling subsequent exceptions difficult to propagate without a call to `EndInvoke`. What would happen is that your app will end up getting a `TargetInvocationException` instead.
|
I have [some code for this](https://github.com/domenic/extensions/blob/master/WindowsFormsInvokingExtensions.cs) online. It's much nicer than the other suggestions; definitely check it out.
Sample usage:
```
private void mCoolObject_CoolEvent(object sender, CoolObjectEventArgs args)
{
// You could use "() =>" in place of "delegate"; it's a style choice.
this.Invoke(delegate
{
// Do the dirty work of my method here.
});
}
```
|
Cleanest Way to Invoke Cross-Thread Events
|
[
"",
"c#",
"multithreading",
"events",
""
] |
I'm wondering how you can implement a program similar to `tail -f` in C/C++, a program that watches for and processes new lines added to a log file?
|
You can use fseek() to clear the eof condition on the stream. Essentially, read to the end of the file, sleep for a while, fseek() (without changing your position) to clear eof, the read to end of file again. wash, rinse, repeat. man fseek(3) for details.
Here's what it looks like in perl. perl's seek() is essentially a wrapper for fseek(3), so the logic is the same:
```
wembley 0 /home/jj33/swap >#> cat p
my $f = shift;
open(I, "<$f") || die "Couldn't open $f: $!\n";
while (1) {
seek(I, 0, 1);
while (defined(my $l = <I>)) {
print "Got: $l";
}
print "Hit EOF, sleeping\n";
sleep(10);
}
wembley 0 /home/jj33/swap >#> cat tfile
This is
some
text
in
a file
wembley 0 /home/jj33/swap >#> perl p tfile
Got: This is
Got: some
Got: text
Got: in
Got: a file
Hit EOF, sleeping
```
Then, in another session:
```
wembley 0 /home/jj33/swap > echo "another line of text" >> tfile
```
And back to the original program output:
```
Hit EOF, sleeping
Got: another line of text
Hit EOF, sleeping
```
|
[See here](https://stackoverflow.com/questions/18632/how-to-monitor-a-text-file-in-realtime#18635)
You could either call out to tail and retrieve the stream back into your app, or as it's open source, maybe try to pull it into your own code.
Also, it is possible in C++ iostream to open a file for viewing only and just read to the end, while buffering the last 10-20 lines, then output that.
|
Implementing a log watcher
|
[
"",
"c++",
"c",
"file",
"io",
""
] |
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time?
What are their typical usages?
Are they unique to Java? Is there a C++ equivalent?
|
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as [JUnit](http://www.junit.org/) and [Hibernate](http://www.hibernate.org/) use annotations to minimize the amount of code you need to write yourself to use the frameworks.
Oracle has [a good explanation of the concept and its meaning in Java](http://docs.oracle.com/javase/1.5.0/docs/guide/language/annotations.html) on their site.
|
> Also, are they unique to Java, is there a C++ equivalent?
No, but VB and C# have [attributes](http://www.codeproject.com/KB/cs/dotnetattributes.aspx) which are the same thing.
Their use is quite diverse. One typical Java example, `@Override` has no effect on the code but it can be used by the compiler to generate a warning (or error) if the decorated method doesn't actually override another method. Similarly, methods can be marked obsolete.
Then there's reflection. When you reflect a type of a class in your code, you can access the attributes and act according to the information found there. I don't know any examples in Java but in .NET this is used by the compiler to generate [(de)serialization](http://msdn.microsoft.com/en-us/library/system.serializableattribute.aspx) information for classes, determine the [memory layout](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.structlayoutattribute.aspx) of structures and [declare function imports](http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx) from legacy libraries (among others). They also control how the IDE form designer works.
/EDIT: Attributes on classes are comparable to tag interfaces (like [Serializable](http://docs.oracle.com/javase/1.4.2/docs/api/java/io/Serializable.html) in Java). However, the .NET coding guidelines say not to use tag interfaces. Also, they only work on class level, not on method level.
|
Java Annotations
|
[
"",
"java",
"annotations",
"glossary",
""
] |
I'm looking at the [PHP Manual](http://www.php.net/manual/en/), and I'm not seeing a section on data structures that most languages have, such as lists and sets. Am I just blind or does PHP not have anything like this built in?
|
The only native data structure in PHP is array. Fortunately, arrays are quite flexible and can be used as hash tables as well.
<http://www.php.net/array>
However, there is SPL which is sort of a clone of C++ STL.
<http://www.php.net/manual/en/book.spl.php>
|
PHP offers data structures through the Standard PHP Library (SPL) basic extension, which is available and compiled by default in PHP 5.0.0.
The data structures offered are available with PHP 5 >= 5.3.0, and includes:
### Doubly Linked Lists
A Doubly Linked List (DLL) is a list of nodes linked in both directions to each others. Iterator’s operations, access to both ends, addition or removal of nodes have a cost of O(1) when the underlying structure is a DLL. It hence provides a decent implementation for stacks and queues.
* [SplDoublyLinkedList class](http://www.php.net/manual/en/class.spldoublylinkedlist.php)
+ [SplStack class](http://www.php.net/manual/en/class.splstack.php)
+ [SplQueue class](http://www.php.net/manual/en/class.splqueue.php)
### Heaps
Heaps are tree-like structures that follow the heap-property: each node is greater than or equal to its children, when compared using the implemented compare method which is global to the heap.
* [SplHeap class](http://www.php.net/manual/en/class.splheap.php)
+ [SplMaxHeap class](http://www.php.net/manual/en/class.splmaxheap.php)
+ [SplMinHeap class](http://www.php.net/manual/en/class.splminheap.php)
* [SplPriorityQueue class](http://www.php.net/manual/en/class.splpriorityqueue.php)
### Arrays
Arrays are structures that store the data in a continuous way, accessible via indexes. Don’t confuse them with PHP arrays: PHP arrays are in fact implemented as ordered hashtables.
* [SplFixedArray class](http://www.php.net/manual/en/class.splfixedarray.php)
### Map
A map is a datastructure holding key-value pairs. PHP arrays can be seen as maps from integers/strings to values. SPL provides a map from objects to data. This map can also be used as an object set.
* [SplObjectStorage class](http://www.php.net/manual/en/class.splobjectstorage.php)
Source: <http://php.net/manual/en/spl.datastructures.php>
|
Does PHP have built-in data structures?
|
[
"",
"php",
"data-structures",
""
] |
I have a need to convert images from CMYK to RGB - not necessarily back again, but hey, if it can be done...
With the release of ColdFusion 8, we got the [CFImage](http://cfquickdocs.com/cf8/?getDoc=cfimage) tag, but it doesn't support this conversion; and nor does [Image.cfc](http://x.com), or [Alagad's Image Component](http://x.com).
However, it should be possible in Java; which we can leverage through CF. For example, here's how you might create a Java thread to sleep a process:
```
<cfset jthread = createObject("java", "java.lang.Thread")/>
<cfset jthread.sleep(5000)/>
```
I would guess a similar method could be used to leverage java to do this image conversion, but not being a Java developer, I don't have a clue where to start. Can anyone lend a hand here?
|
I use the Java ImageIO libraries (<https://jai-imageio.dev.java.net>). They aren't perfect, but can be simple and get the job done. As far as converting from CMYK to RGB, here is the best I have been able to come up with.
Download and install the ImageIO JARs and native libraries for your platform. The native libraries are essential. Without them the ImageIO JAR files will not be able to detect the CMYK images. Originally, I was under the impression that the native libraries would improve performance but was not required for any functionality. I was wrong.
The only other thing that I noticed is that the converted RGB images are sometimes much lighter than the CMYK images. If anyone knows how to solve that problem, I would be appreciative.
Below is some code to convert a CMYK image into an RGB image of any supported format.
Thank you,
Randy Stegbauer
```
package cmyk;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import org.apache.commons.lang.StringUtils;
public class Main
{
/**
* Creates new RGB images from all the CMYK images passed
* in on the command line.
* The new filename generated is, for example "GIF_original_filename.gif".
*
*/
public static void main(String[] args)
{
for (int ii = 0; ii < args.length; ii++)
{
String filename = args[ii];
boolean cmyk = isCMYK(filename);
System.out.println(cmyk + ": " + filename);
if (cmyk)
{
try
{
String rgbFile = cmyk2rgb(filename);
System.out.println(isCMYK(rgbFile) + ": " + rgbFile);
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
}
}
/**
* If 'filename' is a CMYK file, then convert the image into RGB,
* store it into a JPEG file, and return the new filename.
*
* @param filename
*/
private static String cmyk2rgb(String filename) throws IOException
{
// Change this format into any ImageIO supported format.
String format = "gif";
File imageFile = new File(filename);
String rgbFilename = filename;
BufferedImage image = ImageIO.read(imageFile);
if (image != null)
{
int colorSpaceType = image.getColorModel().getColorSpace().getType();
if (colorSpaceType == ColorSpace.TYPE_CMYK)
{
BufferedImage rgbImage =
new BufferedImage(
image.getWidth(), image.getHeight(), BufferedImage.TYPE_3BYTE_BGR);
ColorConvertOp op = new ColorConvertOp(null);
op.filter(image, rgbImage);
rgbFilename = changeExtension(imageFile.getName(), format);
rgbFilename = new File(imageFile.getParent(), format + "_" + rgbFilename).getPath();
ImageIO.write(rgbImage, format, new File(rgbFilename));
}
}
return rgbFilename;
}
/**
* Change the extension of 'filename' to 'newExtension'.
*
* @param filename
* @param newExtension
* @return filename with new extension
*/
private static String changeExtension(String filename, String newExtension)
{
String result = filename;
if (filename != null && newExtension != null && newExtension.length() != 0);
{
int dot = filename.lastIndexOf('.');
if (dot != -1)
{
result = filename.substring(0, dot) + '.' + newExtension;
}
}
return result;
}
private static boolean isCMYK(String filename)
{
boolean result = false;
BufferedImage img = null;
try
{
img = ImageIO.read(new File(filename));
}
catch (IOException e)
{
System.out.println(e.getMessage() + ": " + filename);
}
if (img != null)
{
int colorSpaceType = img.getColorModel().getColorSpace().getType();
result = colorSpaceType == ColorSpace.TYPE_CMYK;
}
return result;
}
}
```
|
A very simple formula for converting from CMYK to RGB ignoring all color profiles is:
```
R = ( (255-C)*(255-K) ) / 255;
G = ( (255-M)*(255-K) ) / 255;
B = ( (255-Y)*(255-K) ) / 255;
```
This code requires CMYK values to be in rage of 0-255. If you have 0 to 100 or 0.0 to 1.0 you'll have to convert the values.
Hope this will get you started.
As for the java and ColdFusion interfacing, I'm sorry, but I have no idea how to do that.
|
How do I convert images between CMYK and RGB in ColdFusion (Java)?
|
[
"",
"java",
"image",
"coldfusion",
""
] |
The primary class in the `subprocess` module is name `Popen`, and represents a subprocess. `Popen` sounds like someone was trying to force the name to follow some function naming format, rather than chosing a name that actually represents what the object is. Does anyone know why it was chosen over something simple like, say, `Subprocess`?
|
Now, I'm not saying that this is the greatest name in the world, but here was the idea as I understand it.
Originally, the popen family was in the os module and was an implementation of the venerable posix popen. The movement to the subprocess module would have been an opportune time to rename them, but I guess that keeping Popen makes it easier to find in the docs for those who have a long history with python or even to the venerable posix functions.
From its earliest posix incarnation, `Popen` has always been meant to open a Process and allow you to read and write from its stdio like a file. Thus the mnemonic for `Popen` is that it is short for `ProcessOpen` in an attempt to kind of, sorta, look like open.
|
`subprocess.Popen` replaces the group of `os.popenX` POSIX functions (which have a long history). I suppose that the name `Popen` makes it more likely for people used to the old functions to find and use the new ones.
The [PEP for subprocess (PEP 324)](http://www.python.org/dev/peps/pep-0324/) has a little bit of discussion on the name of the module but not of class `Popen`. The [list of PEPs](http://www.python.org/dev/peps/) (Python enhancement proposals) is in general an excellent place to start if you're looking for the rationale for features of Python.
|
Why is the subprocess.Popen class not named Subprocess?
|
[
"",
"python",
"subprocess",
""
] |
I have a web system which has a classical parent-children menu saved in a database, with fields id as the PK, and parent\_id to pointing to the owning menu. (Yes, I know this doesn't scale very well, but that's another topic).
So for these records (id-parent\_id pairs):
```
0-7 0-4 4-9 4-14 4-16 9-6
```
I have this tree:
```
0
├ 7
└ 4
├ 9
| └ 6
├ 14
└ 16
```
I'm needing to hide a top node, so I have to make a list of all the childrens of that certain node, i.e. for 4, they will be (9, 6, 14, 16). Order doesn't matters.
I'm confused... does this fits into the classical tree problems? or is it a graph one?
How can I compose this structure and solve this problem using php?
|
This is the perfect chance to use recursion!
Pseudo-code:
```
nodeList = {}
enumerateNodes(rootNode, nodeList);
function enumerateNodes(node, nodeList) {
nodeList += node;
foreach ( childnode in node.children ) {
enumerateNodes(childnode, nodeList);
}
}
```
Edit: Didn't notice that your tree is in the adjacent list format. I would probably just build that into an actual tree datastructure before I started working with it. Just loop through all pairs (creating nodes the first time you see them) and linking them. I *think* it should be easy...
|
Adjacent list models are very difficult to deal with. The company I am with now uses them for hierarchies and it causes great headaches. I have successfully used Celko's nested set models for prior employers and they work great for creating, maintaining and using hierarchies (trees).
I found this link which describes them: <http://www.intelligententerprise.com/001020/celko.jhtml>
But I would also recommend the book "SQL for Smarties: Advanced SQL Programming" written by Joe Celko and covers nested sets.
[Joe Celko's SQL for Smarties: Advanced SQL Programming](https://rads.stackoverflow.com/amzn/click/com/0123693799)
[Joe Celko's Trees and Hierarchies in SQL for Smarties](https://rads.stackoverflow.com/amzn/click/com/1558609202)
|
Retrieve all nodes in a tree that are children of another one
|
[
"",
"php",
"tree",
""
] |
While writing a custom IHttpHandler I came across a behavior that I didn't expect concerning the HttpCachePolicy object.
My handler calculates and sets an entity-tag (using the SetETag method on the HttpCachePolicy associated with the current response object). If I set the cache-control to public using the SetCacheability method everything works like a charm and the server sends along the e-tag header. If I set it to private the e-tag header will be suppressed.
Maybe I just haven't looked hard enough but I haven't seen anything in the HTTP/1.1 spec that would justify this behavior. Why wouldn't you want to send E-Tag to browsers while still prohibiting proxies from storing the data?
```
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext ctx) {
ctx.Response.Cache.SetCacheability(HttpCacheability.Private);
ctx.Response.Cache.SetETag("\"static\"");
ctx.Response.ContentType = "text/plain";
ctx.Response.Write("Hello World");
}
public bool IsReusable { get { return true; } }
}
```
Will return
```
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 11
```
But if we change it to public it'll return
```
Cache-Control: public
Content-Type: text/plain; charset=utf-8
Content-Length: 11
Etag: "static"
```
I've run this on the ASP.NET development server and IIS6 so far with the same results. Also I'm unable to explicitly set the ETag using
```
Response.AppendHeader("ETag", "static")
```
**Update**: It's possible to append the ETag header manually when running in IIS7, I suspect this is caused by the tight integration between ASP.NET and the IIS7 pipeline.
**Clarification**: It's a long question but the core question is this: **why does ASP.NET do this, how can I get around it and should I?**
**Update**: I'm going to accept [Tony's answer](https://stackoverflow.com/questions/32824/why-does-httpcacheabilityprivate-suppress-etags#34004) since it's essentially correct (go Tony!). I found that if you want to emulate the HttpCacheability.Private fully you can set the cacheability to ServerAndPrivate but you also have call cache.[SetOmitVaryStar](http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.setomitvarystar.aspx)(true) otherwise the cache will add the **Vary: \*** header to the output and you don't want that. I'll edit that into the answer when I get edit permissions (or if you see this Tony perhaps you could edit your answer to include that call?)
|
I think you need to use HttpCacheability.ServerAndPrivate
That should give you cache-control: private in the headers and let you set an ETag.
The documentation on that needs to be a bit better.
**Edit:** Markus found that you also have call cache.SetOmitVaryStar(true) otherwise the cache will add the Vary: \* header to the output and you don't want that.
|
Unfortunately if you look at `System.Web.HttpCachePolicy.UpdateCachedHeaders()` in .NET Reflector you see that there's an if statement specifically checking that the Cacheability is not Private before doing any ETag stuff. In any case, I've always found that `Last-Modified/If-Modified-Since` works well for our data and is a bit easier to monitor in Fiddler anyway.
|
Why does HttpCacheability.Private suppress ETags?
|
[
"",
"c#",
"asp.net",
"http",
"caching",
""
] |
Why wouldn't I choose abstract? What are the limitations to declaring a class member virtual? Can only methods be declared virtual?
|
An abstract method or property (both can be virtual or abstract) can only be declared in an abstract class and cannot have a body, i.e. you can't implement it in your abstract class.
A virtual method or property must have a body, i.e. you must provide an implementation (even if the body is empty).
If someone want to use your abstract class, he will have to implement a class that inherits from it and explicitly implement the abstract methods and properties but can chose to not override the virtual methods and properties.
Exemple :
```
using System;
using C=System.Console;
namespace Foo
{
public class Bar
{
public static void Main(string[] args)
{
myImplementationOfTest miot = new myImplementationOfTest();
miot.myVirtualMethod();
miot.myOtherVirtualMethod();
miot.myProperty = 42;
miot.myAbstractMethod();
}
}
public abstract class test
{
public abstract int myProperty
{
get;
set;
}
public abstract void myAbstractMethod();
public virtual void myVirtualMethod()
{
C.WriteLine("foo");
}
public virtual void myOtherVirtualMethod()
{
}
}
public class myImplementationOfTest : test
{
private int _foo;
public override int myProperty
{
get { return _foo; }
set { _foo = value; }
}
public override void myAbstractMethod()
{
C.WriteLine(myProperty);
}
public override void myOtherVirtualMethod()
{
C.WriteLine("bar");
}
}
}
```
|
You would use abstract if you do not want to define any implementation in the base class and want to force it to be defined in any derived classes. Define it as a virtual if you want to provide a default implementatio that can be overriden by derived classes.
Yes, only methods can be virtual.
|
When should a class member be declared virtual (C#)/Overridable (VB.NET)?
|
[
"",
"c#",
".net",
"vb.net",
""
] |
I am looking for a little bit of JQuery or JS that allows me to produce a horizontally scrolling "news ticker" list.
The produced HTML needs to be standards compliant as well.
I have tried [liScroll](http://www.gcmingati.net/wordpress/wp-content/lab/jquery/newsticker/jq-liscroll/scrollanimate.html) but this has a habit of breaking (some content ends up on a second line at the start of the scroll), especially with longer lists.
I have also tried [this News Ticker](http://www.mioplanet.com/rsc/newsticker_javascript.htm) but when a DOCTYPE is included the scrolling will jolt rather than cycle smoothly at the end of each cycle.
Any suggestions are appreciated.
**Edit**
So thanks to Matt Hinze's suggestion I realised I could do what I wanted to do with JQuery animate (I require continuous scrolling not discrete scrolling like the example). However, I quickly ran into similar problems to those I was having with liScroll and after all that realised a CSS issue (as always) was responsible.
Solution: liScroll - change the default 'var stripWidth = 0' to something like 100, to give a little space and avoid new line wrapping.
|
Smooth Div Scroll can also be used as a news ticker/stock ticker. It can pause on mouse over or mouse down and it can loop endlessly if you want it to.
Here's [the example](http://www.maaki.com/) with a running ticker.
|
<http://www.emrecamdere.com/news_scroller_jquery.html>
|
What's a good bit of JS or JQuery for horizontally scrolling news ticker
|
[
"",
"javascript",
"jquery",
"scroll",
"client-side",
""
] |
I'm getting some strange, intermittent, data aborts (< 5% of the time) in some of my code, when calling `memset()`. The problem is that is usually doesn't happen unless the code is running for a couple days, so it's hard to catch it in the act.
I'm using the following code:
```
char *msg = (char*)malloc(sizeof(char)*2048);
char *temp = (char*)malloc(sizeof(char)*1024);
memset(msg, 0, 2048);
memset(temp, 0, 1024);
char *tempstr = (char*)malloc(sizeof(char)*128);
sprintf(temp, "%s %s/%s %s%s", EZMPPOST, EZMPTAG, EZMPVER, TYPETXT, EOL);
strcat(msg, temp);
//Add Data
memset(tempstr, '\0', 128);
wcstombs(tempstr, gdevID, wcslen(gdevID));
sprintf(temp, "%s: %s%s", "DeviceID", tempstr, EOL);
strcat(msg, temp);
```
As you can see, I'm not trying to use memset with a size larger that what's originally allocated with `malloc()`
Anyone see what might be wrong with this?
|
`malloc` can return `NULL` if no memory is available. You're not checking for that.
|
There's a couple of things. You're using `sprintf` which is inherently unsafe; unless you're 100% positive that you're not going to exceed the size of the buffer, you should almost *always* prefer `snprintf`. The same applies to `strcat`; prefer the safer alternative `strncat`.
Obviously this may not fix anything, but it goes a *long* way in helping spot what might otherwise be very annoying to spot bugs.
|
memset() causing data abort
|
[
"",
"c++",
"c",
"memory",
"windows-mobile",
""
] |
What libraries/methods do you know of that can do some basic HTML representation in Swing? Can you comment on your experience?
|
Many of the Swing controls (like JLabel) can render basic HTML content. [JEditorPane](http://java.sun.com/javase/6/docs/api/javax/swing/JEditorPane.html) can be used to display HTML pages. However, these controls are limited to [HTML 3.2](http://www.w3.org/TR/REC-html32) support.
For a richer experience, I would use the [JDesktop Integration Components](https://java.net/projects/jdic/).
> JDIC provides Java applications with
> access to functionalities and
> facilities provided by the native
> desktop. It consists of a collection
> of Java packages and tools. JDIC
> supports a variety of features such as
> **embedding the native browser**,
> launching the desktop applications,
> creating tray icons on the desktop,
> registering file type associations,
> creating JNLP installer packages, etc.
|
A good pure Java solution is [JWebEngine](http://www.inetsoftware.de/other-products/jwebengine). It render HTML 4 very good.
|
Previewing HTML in Java
|
[
"",
"java",
"html",
""
] |
Is there any difference between:
```
if foo is None: pass
```
and
```
if foo == None: pass
```
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an instance (and the only instance, IIRC) of NoneType, so it shouldn't matter, right? Are there any circumstances in which it might?
|
`is` always returns `True` if it compares the same object instance, whereas `==` is ultimately determined by the `__eq__()` method.
i.e.
```
>>> class Foo:
def __eq__(self, other):
return True
>>> f = Foo()
>>> f == None
True
>>> f is None
False
```
|
You may want to read this: [object identity and equivalence](http://mail.python.org/pipermail/python-list/2001-November/094920.html).
The statement `is` is used for object identity, it checks if objects refer to the same instance (same address in memory).
And the `==` statement refers to equality (same value).
|
Is there any difference between "foo is None" and "foo == None"?
|
[
"",
"python",
""
] |
We've got a page with a ton of jQuery (approximately 2000 lines) that we want to trim down b/c it is a maintenance nightmare, and it might be easier to maintain on the server. We've thought about using UpdatePanel for this. However, we don't like the fact that the UpdatePanel is sending the whole page back to the server.
|
Don't move to UpdatePanels. After coming from jQuery, [the drop in performance](http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/) would be untenable. Especially on a page as complex as yours sounds.
If you have 2,000 lines of JavaScript code, the solution is to refactor that code. If you put 2,000 lines of C# code in one file, it would be difficult to maintain too. That would be difficult to manage effectively with **any** language or tool.
If you're using 3.5 SP1, you can use the ScriptManager's new script combining to separate your JavaScript into multiple files with no penalty. That way, you can logically partition your code just as you would with server side code.
|
Please don't put your self in that world of pain. Instead use [UFRAME](http://msmvps.com/blogs/omar/archive/2008/05/24/uframe-goodness-of-updatepanel-and-iframe-combined.aspx) which is a lot faster and is implemented in jQuery.
Now, to manage those 2000 lines of Javascript code I recommend splitting the code in different files and set up your build process to join them using JSMin or Yahoo Compressor into chunks.
|
jQuery AJAX vs. UpdatePanel
|
[
"",
"javascript",
"jquery",
"asp.net",
"ajax",
"updatepanel",
""
] |
How do I select all records that contain "LCS" within the title column in sql.
|
```
SELECT * FROM TABLE WHERE TABLE.TITLE LIKE '%LCS%';
```
% is the wild card matcher.
|
Look into the LIKE clause
|
How do I display records containing specific information in SQl
|
[
"",
"sql",
"sql-server",
""
] |
The following bit of code catches the EOS Exception
```
using (var reader = new BinaryReader(httpRequestBodyStream)) {
try {
while (true) {
bodyByteList.Add(reader.ReadByte());
}
} catch (EndOfStreamException) { }
}
```
So why do I still receive first-chance exceptions in my console?
> A first chance exception of type 'System.IO.EndOfStreamException' occurred in mscorlib.dll
Is there a way to hide these first chance exception messages?
|
The point of "first-chance" exceptions is that you're seeing them pre-handler so that you can stop on them during debugging at the point of throwing. A "second-chance" exception is one that has no appropriate handler. Sometimes you want to catch "first-chance" exceptions because it's important to see what's happening when it's being thrown, even if someone is catching it.
There's nothing to be concerned with. This is normal behavior.
|
To avoid seeing the messages, right-click on the output window and uncheck "Exception Messages".
However, seeing them happen might be nice, if you're interested in knowing when exceptions are thrown without setting breakpoints and reconfiguring the debugger.
|
Avoiding first chance exception messages when the exception is safely handled
|
[
"",
"c#",
".net",
"exception",
""
] |
I am trying to automate functional testing of a server using a realistic frequency distribution of requests. (sort of load testing, sort of simulation)
I've chosen the [Weibull](http://en.wikipedia.org/wiki/Weibull_distribution) distribution as it "sort of" matches the distribution I've observed (ramps up quickly, drops off quickly but not instantly)
I use this distribution to generate the number of requests that should be sent each day between a given start and end date
I've hacked together an algorithm in Python that sort of works but it feels kludgy:
```
how_many_days = (end_date - start_date).days
freqs = defaultdict(int)
for x in xrange(how_many_responses):
freqs[int(how_many_days * weibullvariate(0.5, 2))] += 1
timeline = []
day = start_date
for i,freq in sorted(freqs.iteritems()):
timeline.append((day, freq))
day += timedelta(days=1)
return timeline
```
What better ways are there to do this?
|
This is quick and probably not that accurate, but if you calculate the PDF yourself, then at least you make it easier to lay several smaller/larger ones on a single timeline. `dev` is the std deviation in the Guassian noise, which controls the roughness. Note that this is *not* the 'right' way to generate what you want, but it's easy.
```
import math
from datetime import datetime, timedelta, date
from random import gauss
how_many_responses = 1000
start_date = date(2008, 5, 1)
end_date = date(2008, 6, 1)
num_days = (end_date - start_date).days + 1
timeline = [start_date + timedelta(i) for i in xrange(num_days)]
def weibull(x, k, l):
return (k / l) * (x / l)**(k-1) * math.e**(-(x/l)**k)
dev = 0.1
samples = [i * 1.25/(num_days-1) for i in range(num_days)]
probs = [weibull(i, 2, 0.5) for i in samples]
noise = [gauss(0, dev) for i in samples]
simdata = [max(0., e + n) for (e, n) in zip(probs, noise)]
events = [int(p * (how_many_responses / sum(probs))) for p in simdata]
histogram = zip(timeline, events)
print '\n'.join((d.strftime('%Y-%m-%d ') + "*" * c) for d,c in histogram)
```
|
Why don't you try [The Grinder 3](http://grinder.sourceforge.net) to load test your server, it comes with all this and more prebuilt, and it supports python as a scripting language
|
How do i generate a histogram for a given probability distribution (for functional testing a server)?
|
[
"",
"python",
"statistics",
"simulation",
"stress-testing",
""
] |
Speaking as a non-C# savvy programmer, I'm curious as to the evaluation semantics of LINQ queries like the following:
```
var people = from p in Person
where p.age < 18
select p
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
```
Assuming that `Person` is an ADO entity which defines the `age` and `firstName` fields, what would this do from a database standpoint? Specifically, would the `people` query be run to produce an in-memory structure, which would then be queried by the `otherPeople` query? Or would the construction of `otherPeople` merely pull the data regarding the query from `people` and then produce a new database-peered query? So, if I iterated over both of these queries, how many SQL statements would be executed?
|
They are composable. This is possible because LINQ queries are actually expressions (code as data), which LINQ providers like LINQ-to-SQL can evaluate and generate corresponding SQL.
Because LINQ queries are lazily evaluated (e.g. won't get executed until you iterate over the elements), the code you showed won't actually touch the database. Not until you iterate over otherPeople or people will SQL get generated and executed.
|
```
var people = from p in Person
where p.age < 18
select p
```
Translates to:
```
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[Age] < @p0
```
where @p0 gets sent through as 18
```
var otherPeople = from p in people
where p.firstName equals "Daniel"
select p
```
Translates to:
```
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0]
WHERE [t0].[FirstName] = @p0
```
where @p0 gets sent through as "Daniel"
```
var morePeople = from p1 in people
from p2 in otherPeople
where p1.PersonId == p2.PersonId
select p1;
```
Translates to:
```
SELECT [t0].[PersonId], [t0].[Age], [t0].[FirstName]
FROM [dbo].[Person] AS [t0], [dbo].[Person] AS [t1]
WHERE ([t0].[PersonId] = [t1].[PersonId]) AND ([t0].[Age] < @p0) AND ([t1].[FirstName] = @p1)
```
where @p0 is 18, @p1 is "Daniel"
When in doubt, call the ToString() on your IQueryable or give a TextWriter to the DataContext's Log property.
|
Does LINQ-to-SQL Support Composable Queries?
|
[
"",
"sql",
"linq",
"linq-to-sql",
"code-reuse",
""
] |
Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?
|
Kevin,
it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example, [Snoop](https://web.archive.org/web/20081228210203/http://blois.us/Snoop/) uses this method.
|
Mike Stall has [this sample](http://blogs.msdn.com/jmstall/archive/2006/09/28/managed-create-remote-thread.aspx), that uses CreateRemoteThread. It has the advantage of not requiring any C++.
|
Code Injection With C#
|
[
"",
"c#",
"code-injection",
""
] |
I would like a panel in GWT to fill the page without actually having to set the size. Is there a way to do this? Currently I have the following:
```
public class Main implements EntryPoint
{
public void onModuleLoad()
{
HorizontalSplitPanel split = new HorizontalSplitPanel();
//split.setSize("250px", "500px");
split.setSplitPosition("30%");
DecoratorPanel dp = new DecoratorPanel();
dp.setWidget(split);
RootPanel.get().add(dp);
}
}
```
With the previous code snippet, nothing shows up. Is there a method call I am missing?
Thanks.
---
**UPDATE Sep 17 '08 at 20:15**
I put some buttons (explicitly set their size) on each side and that still doesn't work. I'm really surprised there isn't like a FillLayout class or a setFillLayout method or setDockStyle(DockStyle.Fill) or something like that. Maybe it's not possible? But for as popular as GWT is, I would think it would be possible.
**UPDATE Sep 18 '08 at 14:38**
I have tried setting the RootPanel width and height to 100% and that still didn't work. Thanks for the suggestion though, that seemed like it maybe was going to work. Any other suggestions??
|
Google has answered the main part of your question in one of their FAQs:
<http://code.google.com/webtoolkit/doc/1.6/FAQ_UI.html#How_do_I_create_an_app_that_fills_the_page_vertically_when_the_b>
The primary point is that you can't set height to 100%, you must do something like this:
```
final VerticalPanel vp = new VerticalPanel();
vp.add(mainPanel);
vp.setWidth("100%");
vp.setHeight(Window.getClientHeight() + "px");
Window.addResizeHandler(new ResizeHandler() {
public void onResize(ResizeEvent event) {
int height = event.getHeight();
vp.setHeight(height + "px");
}
});
RootPanel.get().add(vp);
```
|
Ben's answer is very good, but is also out of date. A resize handler was necessary in GWT 1.6, but we are at 2.4 now. You can use a [DockLayoutPanel](http://google-web-toolkit.googlecode.com/svn/javadoc/2.0/com/google/gwt/user/client/ui/DockLayoutPanel.html) to have your content fill the page vertically. See the [sample mail app](http://gwt.google.com/samples/Mail/Mail.html), which uses this panel.
|
Creating a fluid panel in GWT to fill the page?
|
[
"",
"java",
"gwt",
""
] |
What is the difference in C# between `Convert.ToDecimal(string)` and `Decimal.Parse(string)`?
In what scenarios would you use one over the other?
What impact does it have on performance?
What other factors should I be taking into consideration when choosing between the two?
|
From [bytes.com](http://bytes.com/forum/thread266344.html):
> The Convert class is designed to
> convert a wide range of Types, so you
> can convert more types to Decimal than
> you can with Decimal.Parse, which can
> only deal with String. On the other
> hand Decimal.Parse allows you to
> specify a NumberStyle.
>
> Decimal and decimal are aliases and
> are equal.
>
> For Convert.ToDecimal(string),
> Decimal.Parse is called internally.
>
> Morten Wennevik [C# MVP]
Since Decimal.Parse is called internally by Convert.ToDecimal, if you have ***extreme*** performance requirements you might want to stick to Decimal.Parse, it will save a stack frame.
|
There is one important difference to keep in mind:
`Convert.ToDecimal` will return `0` if it is given a `null` string.
`decimal.Parse` will throw an `ArgumentNullException` if the string you want to parse is `null`.
|
Difference between Convert.ToDecimal(string) & Decimal.Parse(string)
|
[
"",
"c#",
".net",
""
] |
I have a console program written in C# that I am using to send faxes. When I step through the program in Visual Studio it works fine. When I double click on the program in Windows Explorer it works fine. When I setup a Windows scheduled task to run the program it fails with this in the event log.
```
EventType clr20r3, P1 consolefaxtest.exe, P2 1.0.0.0,
P3 48bb146b, P4 consolefaxtest, P5 1.0.0.0, P6 48bb146b,
P7 1, P8 80, P9 system.io.filenotfoundexception,
P10 NIL.
```
I wrote a batch file to run the fax program and it fails with this message.
```
Unhandled Exception: System.IO.FileNotFoundException: Operation failed.
at FAXCOMEXLib.FaxDocumentClass.ConnectedSubmit(FaxServer pFaxServer)
```
Can anyone explain this behavior to me?
|
I can't explain it - but I have a few ideas.
Most of the times, when a program works fine testing it, and doesn't when scheduling it - security is the case. In the context of which user is your program scheduled? Maybe that user isn't granted enough access.
Is the resource your programm is trying to access a network drive, that the user running the scheduled task simply haven't got?
|
I agree with MartinNH.
Many of these problems root from the fact that you develop while logged in as an administrator in Visual Studio (so the program has all the permissions for execution set properly) but you deploy as a user with lesser privileges.
Try setting the priveleges of the task scheduler user higher.
|
C# console program can't send fax when run as a scheduled task
|
[
"",
"c#",
"console",
"fax",
""
] |
I would like to read the text and binary attachments in a saved Outlook message (.msg file) from a Java application, without resorting to native code (JNI, Java Native Interface).
[Apache POI-HSMF](http://poi.apache.org/hsmf/index.html) seems to be in the right direction, but it's in very early stages of development...
|
* You could use Apache POIFS, which
seems to be a little more mature,
but that would appear to duplicate the efforts of POI-HSMF.
* You could use POI-HSMF and contribute changes to get the
features you need working. That's
often how FOSS projects like that expand.
* You
could use com4j, j-Interop, or some
other COM-level interop feature and
interact directly with the COM
interfaces that provide access to
the structured document. That would
be much easier than trying to hit it
directly through JNI.
|
[msgparser](http://auxilii.com/msgparser/) is a small open source Java library that parses Outlook .msg files and provides their content using Java objects. msgparser uses the [Apache POI - POIFS](http://poi.apache.org/poifs/) library to parse the message files which use the OLE 2 Compound Document format.
|
What's the best library for reading Outlook .msg files in Java?
|
[
"",
"java",
"outlook",
"msg",
""
] |
I'm currently working on a JavaScript tool that, during the course of its execution, will ultimately traverse each node in the DOM. Because this has potential to be a very expensive task, I'd like to benchmark the performance of this script.
What's the best, free tool for benchmarking a script such as this across the major browsers? Ideally, I'd like the tool (or set of tools, even):
* \*\*To generate some form of report based on the results of the test.\*\* It can be as simple as a table showing execution times, or as complex as generating some form of a chart. Either way is fine.
* \*\*To be free.\*\* it's not that I don't believe in paying for software, it's just that I don't have a major need for a tool like this in my typical day-to-day tasks.
If possible, I'd also like the tool to generate varying levels of complex pages so that I can stress test a set of DOMs. This isn't a necessity - if I need to do so, I can write one myself; however, I'd figure I'd poll the community first to see if something already exists.
|
**[Firebug](http://getfirebug.com)** does include JS profiling, and it is probably the best out there. While I've had problems with Firebug's debugger, its profiler is currently top-of-the-line. **[Venkman](http://www.mozilla.org/projects/venkman/)** is also an older JS debugger/profiler for Firefox, just in case you run into Firebug issues.
Using these tools should get you just about all the profiling you need across all browsers even though you'll only be monitoring Firefox. If you truly need to get down to dirty details of IE profiling and the like, there are a number of tools online that inject profiling calls into your javascript to help monitor all profiler-lacking browsers....but even to a JS performance nazi like me, this seems unnecessary.
***Note:*** A new, very promising IE8 JS profiler has recently been announced: <http://blogs.msdn.com/ie/archive/2008/09/11/introducing-the-ie8-developer-tools-jscript-profiler.aspx>.
|
In FireBug and FireBug Lite you can call the console.time() and console.timeEnd() methods in your code to start and end a timer around a particular piece of code. The Profiler tool in FireBug will measure how long each function takes. I've used it a lot to narrow down which lines of a particularly slow function are causing the slowdown
|
What is the best tool to benchmark my JavaScript?
|
[
"",
"javascript",
"dom",
""
] |
How do I call an external command within Python as if I had typed it in a shell or command prompt?
|
Use [`subprocess.run`](https://docs.python.org/library/subprocess.html#subprocess.run):
```
import subprocess
subprocess.run(["ls", "-l"])
```
Another common way is [`os.system`](https://docs.python.org/library/os.html#os.system) but you shouldn't use it because it is unsafe if any parts of the command come from outside your program or can contain spaces or other special characters, also `subprocess.run` is generally more flexible (you can get the [`stdout`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stdout), [`stderr`](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.stderr), the ["real" status code](https://docs.python.org/library/subprocess.html#subprocess.CompletedProcess.returncode), better [error handling](https://docs.python.org/library/subprocess.html#subprocess.CalledProcessError), etc.). Even the [documentation for `os.system`](https://docs.python.org/library/os.html#os.system) recommends using `subprocess` instead.
On Python 3.4 and earlier, use `subprocess.call` instead of `.run`:
```
subprocess.call(["ls", "-l"])
```
|
Here is a summary of ways to call external programs, including their advantages and disadvantages:
1. [`os.system`](https://docs.python.org/3/library/os.html#os.system) passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:
```
os.system("some_command < input_file | another_command > output_file")
```
However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, et cetera. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs.
2. [`os.popen`](https://docs.python.org/3/library/os.html#os.popen) will do the same thing as `os.system` except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. Example:
```
print(os.popen("ls -l").read())
```
3. [`subprocess.Popen`](https://docs.python.org/3/library/subprocess.html#subprocess.Popen). This is intended as a replacement for `os.popen`, but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:
```
print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
```
instead of
```
print os.popen("echo Hello World").read()
```
but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See [the documentation](https://docs.python.org/3/library/subprocess.html#popen-constructor).
4. [`subprocess.call`](https://docs.python.org/3/library/subprocess.html#subprocess.call). This is basically just like the `Popen` class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:
```
return_code = subprocess.call("echo Hello World", shell=True)
```
5. [`subprocess.run`](https://docs.python.org/3/library/subprocess.html#subprocess.run). Python 3.5+ only. Similar to the above but even more flexible and returns a [`CompletedProcess`](https://docs.python.org/3/library/subprocess.html#subprocess.CompletedProcess) object when the command finishes executing.
6. `os.fork`, `os.exec`, `os.spawn` are similar to their C language counterparts, but I don't recommend using them directly.
The `subprocess` module should probably be what you use.
Finally, please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. **There are serious security implications** if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:
```
print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()
```
and imagine that the user enters something "`my mama didnt love me && rm -rf /`" which could erase the whole filesystem.
|
How do I execute a program or call a system command?
|
[
"",
"python",
"shell",
"terminal",
"subprocess",
"command",
""
] |
Suppose a large composite application built on several foundation components packaged in their own assemblies: (database reading, protocol handlers, etc.). For some deployments, this can include over 20 assemblies. Each of these assemblies has settings or configuration information. Our team tends to like the VS settings editor (and the easy-to-use code it generates!), and the application vs. user distinction meets most of our needs.
BUT....
It is very tedious to copy & paste the many configuration sections into our application's .xml. Furthermore, for shared components that tend to have similar configurations across applications, this means we need to maintain duplicate settings in multiple .config files.
Microsoft's EntLib solves this problem with an external tool to generate the monster .config file, but this feels klunky as well.
What techniques do you use to manage large .NET .config files with sections from multiple shared assemblies? Some kind of include mechanism? Custom configuration readers?
FOLLOWUP:
Will's [answer](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) was exactly what I was getting at, and looks elegant for flat key/value pair sections. Is there a way to combine this approach with [custom configuration sections](https://stackoverflow.com/questions/89245/how-do-you-manage-net-appconfig-files-for-large-applications#89618) ?
Thanks also for the suggestions about managing different .configs for different build targets. That's also quite useful.
Dave
|
You use one master config file that points to other config files. [Here's an example of how to do this.](http://blog.andreloker.de/post/2008/06/Keep-your-config-clean-with-external-config-files.aspx)
---
In case the link rots, what you do is specify the [configSource](http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.configsource.aspx) for a particular configuration section. This allows you to define that particular section within a separate file.
```
<pages configSource="pages.config"/>
```
which implies that there is a file called "pages.config" within the same directory that contains the entire `<pages />` node tree.
|
My preferred method is to use MSBuild, if you right click on a project and click 'unload' a new menu option will pop up that says 'edit '. Select that and it'll open up the project file so you can edit it, scroll down until you find a commented out section that is called "AfterBuild".
You can then add something like:
```
<Target Name="AfterBuild">
<Delete Files="$(TargetDir)$(TargetFileName).config" />
<Copy SourceFiles="$(ProjectDir)$(Configuration).config" DestinationFiles="$(TargetDir)$(TargetFileName).config" />
</Target>
```
This will replace the application config with one named [Release|Debug]app.exe.config. So you can maintain separate configurations depending on how the project is built.
But a quick and dirty option (if you don't want to play with msbuild) is to just maintain separate config files and then define which one you want to include, like this:
```
<appSettings configSource="Config\appSettingsDebug.config"/>
<roleManager configSource="Config\roleManagerDebug.config"/>
```
And if you are doing an asp.net application, microsoft provides a great utility called "Web Deployment Projects" that will allow you to manage all of this easily, [click here](http://www.microsoft.com/downloads/details.aspx?familyid=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&displaylang=en)
|
How do you manage .NET app.config files for large applications?
|
[
"",
"c#",
".net",
"configuration",
""
] |
While creating a file synchronization program in C# I tried to make a method `copy` in `LocalFileItem` class that uses `System.IO.File.Copy(destination.Path, Path, true)` method where `Path` is a `string`.
After executing this code with destination. `Path = "C:\\Test2"` and `this.Path = "C:\\Test\\F1.txt"` I get an exception saying that I do not have the required file permissions to do this operation on **C:\Test**, but **C:\Test** is owned by myself *(the current user)*.
Does anybody knows what is going on, or how to get around this?
Here is the original code complete.
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Diones.Util.IO
{
/// <summary>
/// An object representation of a file or directory.
/// </summary>
public abstract class FileItem : IComparable
{
protected String path;
public String Path
{
set { this.path = value; }
get { return this.path; }
}
protected bool isDirectory;
public bool IsDirectory
{
set { this.isDirectory = value; }
get { return this.isDirectory; }
}
/// <summary>
/// Delete this fileItem.
/// </summary>
public abstract void delete();
/// <summary>
/// Delete this directory and all of its elements.
/// </summary>
protected abstract void deleteRecursive();
/// <summary>
/// Copy this fileItem to the destination directory.
/// </summary>
public abstract void copy(FileItem fileD);
/// <summary>
/// Copy this directory and all of its elements
/// to the destination directory.
/// </summary>
protected abstract void copyRecursive(FileItem fileD);
/// <summary>
/// Creates a FileItem from a string path.
/// </summary>
/// <param name="path"></param>
public FileItem(String path)
{
Path = path;
if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true;
else IsDirectory = false;
}
/// <summary>
/// Creates a FileItem from a FileSource directory.
/// </summary>
/// <param name="directory"></param>
public FileItem(FileSource directory)
{
Path = directory.Path;
}
public override String ToString()
{
return Path;
}
public abstract int CompareTo(object b);
}
/// <summary>
/// A file or directory on the hard disk
/// </summary>
public class LocalFileItem : FileItem
{
public override void delete()
{
if (!IsDirectory) File.Delete(this.Path);
else deleteRecursive();
}
protected override void deleteRecursive()
{
Directory.Delete(Path, true);
}
public override void copy(FileItem destination)
{
if (!IsDirectory) File.Copy(destination.Path, Path, true);
else copyRecursive(destination);
}
protected override void copyRecursive(FileItem destination)
{
Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(
Path, destination.Path, true);
}
/// <summary>
/// Create's a LocalFileItem from a string path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(String path)
: base(path)
{
}
/// <summary>
/// Creates a LocalFileItem from a FileSource path
/// </summary>
/// <param name="path"></param>
public LocalFileItem(FileSource path)
: base(path)
{
}
public override int CompareTo(object obj)
{
if (obj is FileItem)
{
FileItem fi = (FileItem)obj;
if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) > 0) return 1;
else if (File.GetCreationTime(this.Path).CompareTo
(File.GetCreationTime(fi.Path)) < 0) return -1;
else
{
if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) < 0) return -1;
else if (File.GetLastWriteTime(this.Path).CompareTo
(File.GetLastWriteTime(fi.Path)) > 0) return 1;
else return 0;
}
}
else
throw new ArgumentException("obj isn't a FileItem");
}
}
}
```
|
It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination).
Also is "C:\Test2" a directory? You can't copy file to a directory.
Use something like that instead:
```
File.Copy(
sourceFile,
Path.Combine(destinationDir,Path.GetFileName(sourceFile))
)
```
;
|
I was able to solve the problem, Michal pointed me to the right direction.
The problem was that I tried to use File.Copy to copy a file from one location to another, while the Copy method does only copy all the contents from one file to another(creating the destination file if it does not already exists). The solution was to append the file name to the destination directory.
Thanks for all the help!
|
About File permissions in C#
|
[
"",
"c#",
"file",
"copy",
""
] |
I thought jQuery Intellisense was supposed to be improved with SP1. I even downloaded an annotated version of jQuery 1.2.6, but intellisense will not work in a separate jscript file. I have the jQuery library referenced first on my web page in the <head> tag. Am I doing anything wrong?
|
At the top of your external JavaScript file, add the following:
```
/// <reference path="jQuery.js"/>
```
Make sure the path is correct, relative to the file's position in the folder structure, etc.
Also, any references need to be at the top of the file, before *any* other text, including comments - literally, the very first thing in the file. Hopefully future version of Visual Studio will work regardless of where it is in the file, or maybe they will do something altogether different...
Once you have done that and *saved the file*, hit `Ctrl` + `Shift` + `J` to force Visual Studio to update Intellisense.
|
There is an officially supported jQuery documentation JavaScript file for Visual Studio 2008. This file is only an interim fix until Microsoft releases a hotfix that will more adequately address the issue.
Embedded in ASPX:
```
<% if (false) { %>
<script src="jquery-1.2.6-vsdoc.js" type="text/javascript"></script>
<% } %>
```
Embedded in JavaScript:
```
/// <reference path="jquery-1.2.6-vsdoc.js" />
```
Pick it up here: [jquery-1.2.6-vsdoc.js](http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.2.6-vsdoc.js)
**References**:
* [Rich Intellisense for jQuery](http://blogs.msdn.com/webdevtools/archive/2008/10/28/rich-intellisense-for-jquery.aspx)
* [Scott Hanselman - ASP.NET and jQuery](http://www.hanselman.com/blog/ASPNETAndJQuery.aspx)
|
How do you get JavaScript/jQuery Intellisense Working in Visual Studio 2008?
|
[
"",
"asp.net",
"javascript",
"jquery",
"visual-studio",
"intellisense",
""
] |
Kind of a special case problem:
* I start a process with `System.Diagnostics.Process.Start(..)`
* The process opens a splash screen -- this splash screen becomes the main window.
* The splash screen closes and the 'real' UI is shown. The main window (splash screen) is now invalid.
* I still have the Process object, and I can query its handle, module, etc. But the main window handle is now invalid.
I need to get the process's UI (or UI handle) at this point. Assume I cannot change the behavior of the process to make this any easier (or saner).
I have looked around online but I'll admit I didn't look for more than an hour. Seemed like it should be somewhat trivial :-(
|
If you don't mind using the Windows API, you could use [`EnumWindowsProc`](http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633498.aspx), and check each of the handles that that turns up using [`GetWindowThreadProcessId`](http://msdn.microsoft.com/en-gb/library/windows/desktop/ms633522.aspx) (to see that it's in your process), and then maybe `IsWindowVisible`, `GetWindowCaption` and `GetWindowTextLength` to determine which `hWnd` in your process is the one you want.
Though if you haven't used those functions before that approach will be a real pain, so hopefully there's a simpler way.
|
@ageektrapped is on the right track, however `FindWindow` will not search child windows.
For that you will need to use [`FindWindowEx`](http://pinvoke.net/default.aspx/user32/FindWindowEx.html)
|
.NET (C#): Getting child windows when you only have a process handle or PID?
|
[
"",
"c#",
".net",
"windows",
"user-interface",
""
] |
The documentation for the [round()](http://docs.python.org/lib/built-in-funcs.html) function states that you pass it a number, and the positions past the decimal to round. Thus it *should* do this:
```
n = 5.59
round(n, 1) # 5.6
```
But, in actuality, good old floating point weirdness creeps in and you get:
```
5.5999999999999996
```
For the purposes of UI, I need to display `5.6`. I poked around the Internet and found some [documentation](http://mail.python.org/pipermail/python-list/2005-September/340383.html) that this is dependent on my implementation of Python. Unfortunately, this occurs on both my Windows dev machine and each Linux server I've tried. [See here also](http://www.python.org/doc/2.5.1/tut/node16.html).
Short of creating my own round library, is there any way around this?
|
I can't help the way it's stored, but at least formatting works correctly:
```
'%.1f' % round(n, 1) # Gives you '5.6'
```
|
Formatting works correctly even without having to round:
```
"%.1f" % n
```
|
round() doesn't seem to be rounding properly
|
[
"",
"python",
"floating-point",
"rounding",
""
] |
What is the best C++ IDE or editor for using on Windows? I use Notepad++, but am missing IntelliSense from Visual Studio.
|
I've found the latest release of NetBeans, which includes C/C++ support, to be excellent.
<http://www.netbeans.org/features/cpp/index.html>
|
Um, that's because Visual Studio is the best IDE. Come back to the darkside.
|
Best C++ IDE or Editor for Windows
|
[
"",
"c++",
"windows",
""
] |
Is there a way to embed a browser in Java? more specifically, is there a library that can emulate a browser?
|
Since JavaFX 2.0 you can use now [webview](http://docs.oracle.com/javafx/2.0/webview/jfxpub-webview.htm)

|
I believe JWebPane is going to be the official way to embed a browser into a java app. Its based on the open sourced engine - WebKit, which is used in Apples Safari and Googles Chrome browsers.See [this blog](http://weblogs.java.net/blog/ixmal/archive/2008/05/introducing_jwe.html) for details.
|
Is there a way to embed a browser in Java?
|
[
"",
"java",
"browser",
"cross-platform",
""
] |
I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this?
I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly.
What I would like is something like py2exe that does it in the script itself.
|
Check out [phc: the PHP compiler](https://github.com/pbiggar/phc)
If you just want to run it like a script, you may not need to compile it per se, but just run it via the command line. [Read running PHP via the command line.](http://www.php.net/features.commandline)
|
There is this: <http://www.bambalam.se/bamcompile/> but that compiles to Windows bytecode. There are a few others, but all I have seen will compile for windows only.
Few More:
<http://www.nusphere.com/products/phpdock.htm>
Edit: I almost forgot if your looking to make it work on linux without regard for windows you can just add
```
#!/usr/bin/php
```
to the top of the script and you should be able to run it from the command line. Don't forget to chmod +x the file first.
|
Compile a PHP script in Linux
|
[
"",
"php",
"linux",
""
] |
I'm building a function to extend the `Enum.Parse` concept that
* Allows a default value to be parsed in case that an Enum value is not found
* Is case insensitive
So I wrote the following:
```
public static T GetEnumFromString<T>(string value, T defaultValue) where T : Enum
{
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
```
I am getting a Error Constraint cannot be special class `System.Enum`.
Fair enough, but is there a workaround to allow a Generic Enum, or am I going to have to mimic the `Parse` function and pass a type as an attribute, which forces the ugly boxing requirement to your code.
**EDIT** All suggestions below have been greatly appreciated, thanks.
Have settled on (I've left the loop to maintain case insensitivity - I am using this when parsing XML)
```
public static class EnumUtils
{
public static T ParseEnum<T>(string value, T defaultValue) where T : struct, IConvertible
{
if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");
if (string.IsNullOrEmpty(value)) return defaultValue;
foreach (T item in Enum.GetValues(typeof(T)))
{
if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
}
return defaultValue;
}
}
```
**EDIT:** (16th Feb 2015) Christopher Currens has posted [a compiler enforced type-safe generic solution in MSIL or F#](https://stackoverflow.com/a/8086788) below, which is well worth a look, and an upvote. I will remove this edit if the solution bubbles further up the page.
**EDIT 2:** (13th Apr 2021) As this has now been addressed, and supported, since C# 7.3, I have changed the accepted answer, though full perusal of the top answers is worth it for academic, and historical, interest :)
|
## This feature is finally supported in C# 7.3!
The following snippet (from [the dotnet samples](https://github.com/dotnet/samples/blob/3ee82879284e3f4755251fd33c3b3e533f7b3485/snippets/csharp/keywords/GenericWhereConstraints.cs#L180-L190)) demonstrates how:
```
public static Dictionary<int, string> EnumNamedValues<T>() where T : System.Enum
{
var result = new Dictionary<int, string>();
var values = Enum.GetValues(typeof(T));
foreach (int item in values)
result.Add(item, Enum.GetName(typeof(T), item));
return result;
}
```
Be sure to set your language version in your C# project to version 7.3.
---
Original Answer below:
I'm late to the game, but I took it as a challenge to see how it could be done. It's not possible in C# (or VB.NET, but scroll down for F#), but *is possible* in MSIL. I wrote this little....thing
```
// license: http://www.apache.org/licenses/LICENSE-2.0.html
.assembly MyThing{}
.class public abstract sealed MyThing.Thing
extends [mscorlib]System.Object
{
.method public static !!T GetEnumFromString<valuetype .ctor ([mscorlib]System.Enum) T>(string strValue,
!!T defaultValue) cil managed
{
.maxstack 2
.locals init ([0] !!T temp,
[1] !!T return_value,
[2] class [mscorlib]System.Collections.IEnumerator enumerator,
[3] class [mscorlib]System.IDisposable disposer)
// if(string.IsNullOrEmpty(strValue)) return defaultValue;
ldarg strValue
call bool [mscorlib]System.String::IsNullOrEmpty(string)
brfalse.s HASVALUE
br RETURNDEF // return default it empty
// foreach (T item in Enum.GetValues(typeof(T)))
HASVALUE:
// Enum.GetValues.GetEnumerator()
ldtoken !!T
call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle)
call class [mscorlib]System.Array [mscorlib]System.Enum::GetValues(class [mscorlib]System.Type)
callvirt instance class [mscorlib]System.Collections.IEnumerator [mscorlib]System.Array::GetEnumerator()
stloc enumerator
.try
{
CONDITION:
ldloc enumerator
callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
brfalse.s LEAVE
STATEMENTS:
// T item = (T)Enumerator.Current
ldloc enumerator
callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
unbox.any !!T
stloc temp
ldloca.s temp
constrained. !!T
// if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item;
callvirt instance string [mscorlib]System.Object::ToString()
callvirt instance string [mscorlib]System.String::ToLower()
ldarg strValue
callvirt instance string [mscorlib]System.String::Trim()
callvirt instance string [mscorlib]System.String::ToLower()
callvirt instance bool [mscorlib]System.String::Equals(string)
brfalse.s CONDITION
ldloc temp
stloc return_value
leave.s RETURNVAL
LEAVE:
leave.s RETURNDEF
}
finally
{
// ArrayList's Enumerator may or may not inherit from IDisposable
ldloc enumerator
isinst [mscorlib]System.IDisposable
stloc.s disposer
ldloc.s disposer
ldnull
ceq
brtrue.s LEAVEFINALLY
ldloc.s disposer
callvirt instance void [mscorlib]System.IDisposable::Dispose()
LEAVEFINALLY:
endfinally
}
RETURNDEF:
ldarg defaultValue
stloc return_value
RETURNVAL:
ldloc return_value
ret
}
}
```
Which generates a function that **would** look like this, if it were valid C#:
```
T GetEnumFromString<T>(string valueString, T defaultValue) where T : Enum
```
Then with the following C# code:
```
using MyThing;
// stuff...
private enum MyEnum { Yes, No, Okay }
static void Main(string[] args)
{
Thing.GetEnumFromString("No", MyEnum.Yes); // returns MyEnum.No
Thing.GetEnumFromString("Invalid", MyEnum.Okay); // returns MyEnum.Okay
Thing.GetEnumFromString("AnotherInvalid", 0); // compiler error, not an Enum
}
```
Unfortunately, this means having this part of your code written in MSIL instead of C#, with the only added benefit being that you're able to constrain this method by `System.Enum`. It's also kind of a bummer, because it gets compiled into a separate assembly. However, it doesn't mean you have to deploy it that way.
By removing the line `.assembly MyThing{}` and invoking ilasm as follows:
```
ilasm.exe /DLL /OUTPUT=MyThing.netmodule
```
you get a netmodule instead of an assembly.
Unfortunately, VS2010 (and earlier, obviously) does not support adding netmodule references, which means you'd have to leave it in 2 separate assemblies when you're debugging. The only way you can add them as part of your assembly would be to run csc.exe yourself using the `/addmodule:{files}` command line argument. It wouldn't be *too* painful in an MSBuild script. Of course, if you're brave or stupid, you can run csc yourself manually each time. And it certainly gets more complicated as multiple assemblies need access to it.
So, it CAN be done in .Net. Is it worth the extra effort? Um, well, I guess I'll let you decide on that one.
---
### F# Solution as alternative
Extra Credit: It turns out that a generic restriction on `enum` is possible in at least one other .NET language besides MSIL: F#.
```
type MyThing =
static member GetEnumFromString<'T when 'T :> Enum> str defaultValue: 'T =
/// protect for null (only required in interop with C#)
let str = if isNull str then String.Empty else str
Enum.GetValues(typedefof<'T>)
|> Seq.cast<_>
|> Seq.tryFind(fun v -> String.Compare(v.ToString(), str.Trim(), true) = 0)
|> function Some x -> x | None -> defaultValue
```
This one is easier to maintain since it's a well-known language with full Visual Studio IDE support, but you still need a separate project in your solution for it. However, it naturally produces considerably different IL (the code *is* very different) and it relies on the `FSharp.Core` library, which, just like any other external library, needs to become part of your distribution.
Here's how you can use it (basically the same as the MSIL solution), and to show that it correctly fails on otherwise synonymous structs:
```
// works, result is inferred to have type StringComparison
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", StringComparison.Ordinal);
// type restriction is recognized by C#, this fails at compile time
var result = MyThing.GetEnumFromString("OrdinalIgnoreCase", 42);
```
|
Since `Enum` Type implements `IConvertible` interface, a better implementation should be something like this:
```
public T GetEnumFromString<T>(string value) where T : struct, IConvertible
{
if (!typeof(T).IsEnum)
{
throw new ArgumentException("T must be an enumerated type");
}
//...
}
```
This will still permit passing of value types implementing `IConvertible`. The chances are rare though.
|
Create Generic method constraining T to an Enum
|
[
"",
"c#",
"generics",
"enums",
"generic-constraints",
""
] |
I have a swf with loads text into a Sprite that resizes based on the content put into - I'd like though for the ones that are longer than the page to have the browser use its native scroll bars rather than handle it in actionscript (very much like <http://www.nike.com/nikeskateboarding/v3/>...)
I did have a look at the stuff nike did but just wasn't able to pull it off. Any idea's?
|
I've never done it that way around but I think [swffit](http://swffit.millermedeiros.com/) might be able to pull it off.
|
The trick is to use some simple JavaScript to resize the Flash DOM node:
```
function resizeFlash( h ) {
// "flash-node-id" is the ID of the embedded Flash movie
document.getElementById("flash-node-id").style.height = h + "px";
}
```
Which you call from within the Flash movie like this:
```
ExternalInterface.call("resizeFlash", 400);
```
You don't actually need to have the JavaScript code externally, you can do it all from Flash if you want to:
```
ExternalInterface.call(
"function( id, h ) { document.getElementById(id).style.height = h + 'px'; }",
ExternalInterface.objectID,
400
);
```
The anonymous function is just to be able to pass in the ID and height as parameters instead of concatenating them into the JavaScript string.
I think that the JavaScript is fairly cross-platform. If you want to see a live example look at this site: [talkoftheweather.com](http://www.talkoftheweather.com/). It may not look as though it does anything, but it automatically resizes the Flash movie size to accommodate all the news items (it does this just after loading the news, which is done so quickly that you don't notice it happening). The resize forces the browser to show a vertical scroll bar.
|
How can I resize a swf during runtime to have the browser create html scrollbars?
|
[
"",
"javascript",
"apache-flex",
"actionscript-3",
"flash",
""
] |
I'm looking for a builder for [HQL](http://www.hibernate.org/hib_docs/reference/en/html/queryhql.html) in Java. I want to get rid of things like:
```
StringBuilder builder = new StringBuilder()
.append("select stock from ")
.append( Stock.class.getName() )
.append( " as stock where stock.id = ")
.append( id );
```
I'd rather have something like:
```
HqlBuilder builder = new HqlBuilder()
.select( "stock" )
.from( Stock.class.getName() ).as( "stock" )
.where( "stock.id" ).equals( id );
```
I googled a bit, and I couldn't find one.
I wrote a quick & dumb `HqlBuilder` that suits my needs for now, but I'd love to find one that has more users and tests than me alone.
Note: I'd like to be able to do things like this and more, which I failed to do with the Criteria API:
```
select stock
from com.something.Stock as stock, com.something.Bonus as bonus
where stock.someValue = bonus.id
```
ie. select all stocks whose property `someValue` points to *any* bonus from the Bonus table.
Thanks!
|
@[Sébastien Rocca-Serra](https://stackoverflow.com/questions/56843/looking-for-an-hql-builder-hibernate-query-language#57001)
Now we're getting somewhere concrete. The sort of join you're trying to do isn't really possible through the Criteria API, but a sub-query should accomplish the same thing. First you create a `DetachedCriteria` for the bonus table, then use the `IN` operator for `someValue`.
```
DetachedCriteria bonuses = DetachedCriteria.forClass(Bonus.class);
List stocks = session.createCriteria(Stock.class)
.add(Property.forName("someValue").in(bonuses)).list();
```
This is equivalent to
```
select stock
from com.something.Stock as stock
where stock.someValue in (select bonus.id from com.something.Bonus as bonus)
```
The only downside would be if you have references to different tables in `someValue` and your ID's are not unique across all tables. But your query would suffer from the same flaw.
|
For a type-safe approach to your problem, consider [Querydsl](http://www.querydsl.com).
The example query becomes
```
HQLQuery query = new HibernateQuery(session);
List<Stock> s = query.from(stock, bonus)
.where(stock.someValue.eq(bonus.id))
.list(stock);
```
Querydsl uses APT for code generation like JPA2 and supports JPA/Hibernate, JDO, SQL and Java collections.
I am the maintainer of Querydsl, so this answer is biased.
|
Looking for an HQL builder (Hibernate Query Language)
|
[
"",
"java",
"hibernate",
"hql",
""
] |
How can I have SQL repeat some set-based operation an arbitrary number of times without looping? How can I have SQL perform an operation against a range of numbers? I'm basically looking for a way to do a set-based for loop.
I know I can just create a small table with integers in it, say from 1 to 1000 and then use it for range operations that are within that range.
For example, if I had that table I could make a select to find the sum of numbers 100-200 like this:
```
select sum(n) from numbers where n between 100 and 200
```
Any ideas? I'm kinda looking for something that works for T-SQL but any platform would be okay.
[Edit] I have my own solution for this using SQL CLR which works great for MS SQL 2005 or 2008. [See below.](https://stackoverflow.com/questions/58429/sql-set-based-range#59657)
|
I think the very short answer to your question is to use WITH clauses to generate your own.
Unfortunately, the big names in databases don't have built-in queryable number-range pseudo-tables. Or, more generally, easy pure-SQL data generation features. Personally, I think this is a **huge** failing, because if they did it would be possible to move a lot of code that is currently locked up in procedural scripts (T-SQL, PL/SQL, etc.) into pure-SQL, which has a number of benefits to performance and code complexity.
So anyway, it sounds like what you need in a general sense is the ability to generate data on the fly.
Oracle and T-SQL both support a WITH clause that can be used to do this. They work a little differently in the different DBMS's, and MS calls them "common table expressions", but they are very similar in form. Using these with recursion, you can generate a sequence of numbers or text values fairly easily. Here is what it might look like...
In Oracle SQL:
```
WITH
digits AS -- Limit recursion by just using it for digits.
(SELECT
LEVEL - 1 AS num
FROM
DUAL
WHERE
LEVEL < 10
CONNECT BY
num = (PRIOR num) + 1),
numrange AS
(SELECT
ones.num
+ (tens.num * 10)
+ (hundreds.num * 100)
AS num
FROM
digits ones
CROSS JOIN
digits tens
CROSS JOIN
digits hundreds
WHERE
hundreds.num in (1, 2)) -- Use the WHERE clause to restrict each digit as needed.
SELECT
-- Some columns and operations
FROM
numrange
-- Join to other data if needed
```
This is admittedly quite verbose. Oracle's recursion functionality is limited. The syntax is clunky, it's not performant, and it is limited to 500 (I think) nested levels. This is why I chose to use recursion only for the first 10 digits, and then cross (cartesian) joins to combine them into actual numbers.
I haven't used SQL Server's Common Table Expressions myself, but since they allow self-reference, recursion is MUCH simpler than it is in Oracle. Whether performance is comparable, and what the nesting limits are, I don't know.
At any rate, recursion and the WITH clause are very useful tools in creating queries that require on-the-fly generated data sets. Then by querying this data set, doing operations on the values, you can get all sorts of different types of generated data. Aggregations, duplications, combinations, permutations, and so on. You can even use such generated data to aid in rolling up or drilling down into other data.
**UPDATE:** I just want to add that, once you start working with data in this way, it opens your mind to new ways of thinking about SQL. It's not just a scripting language. It's a fairly robust data-driven [declarative language](http://en.wikipedia.org/wiki/Declarative_programming_language). Sometimes it's a pain to use because for years it has suffered a dearth of enhancements to aid in reducing the redundancy needed for complex operations. But nonetheless it is very powerful, and a fairly intuitive way to work with data sets as both the target and the driver of your algorithms.
|
I created a SQL CLR table valued function that works great for this purpose.
```
SELECT n FROM dbo.Range(1, 11, 2) -- returns odd integers 1 to 11
SELECT n FROM dbo.RangeF(3.1, 3.5, 0.1) -- returns 3.1, 3.2, 3.3 and 3.4, but not 3.5 because of float inprecision. !fault(this)
```
Here's the code:
```
using System;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Collections;
[assembly: CLSCompliant(true)]
namespace Range {
public static partial class UserDefinedFunctions {
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRow", TableDefinition = "n bigint")]
public static IEnumerable Range(SqlInt64 start, SqlInt64 end, SqlInt64 incr) {
return new Ranger(start.Value, end.Value, incr.Value);
}
[Microsoft.SqlServer.Server.SqlFunction(DataAccess = DataAccessKind.None, IsDeterministic = true, SystemDataAccess = SystemDataAccessKind.None, IsPrecise = true, FillRowMethodName = "FillRowF", TableDefinition = "n float")]
public static IEnumerable RangeF(SqlDouble start, SqlDouble end, SqlDouble incr) {
return new RangerF(start.Value, end.Value, incr.Value);
}
public static void FillRow(object row, out SqlInt64 n) {
n = new SqlInt64((long)row);
}
public static void FillRowF(object row, out SqlDouble n) {
n = new SqlDouble((double)row);
}
}
internal class Ranger : IEnumerable {
Int64 _start, _end, _incr;
public Ranger(Int64 start, Int64 end, Int64 incr) {
_start = start; _end = end; _incr = incr;
}
public IEnumerator GetEnumerator() {
return new RangerEnum(_start, _end, _incr);
}
}
internal class RangerF : IEnumerable {
double _start, _end, _incr;
public RangerF(double start, double end, double incr) {
_start = start; _end = end; _incr = incr;
}
public IEnumerator GetEnumerator() {
return new RangerFEnum(_start, _end, _incr);
}
}
internal class RangerEnum : IEnumerator {
Int64 _cur, _start, _end, _incr;
bool hasFetched = false;
public RangerEnum(Int64 start, Int64 end, Int64 incr) {
_start = _cur = start; _end = end; _incr = incr;
if ((_start < _end ^ _incr > 0) || _incr == 0)
throw new ArgumentException("Will never reach end!");
}
public long Current {
get { hasFetched = true; return _cur; }
}
object IEnumerator.Current {
get { hasFetched = true; return _cur; }
}
public bool MoveNext() {
if (hasFetched) _cur += _incr;
return (_cur > _end ^ _incr > 0);
}
public void Reset() {
_cur = _start; hasFetched = false;
}
}
internal class RangerFEnum : IEnumerator {
double _cur, _start, _end, _incr;
bool hasFetched = false;
public RangerFEnum(double start, double end, double incr) {
_start = _cur = start; _end = end; _incr = incr;
if ((_start < _end ^ _incr > 0) || _incr == 0)
throw new ArgumentException("Will never reach end!");
}
public double Current {
get { hasFetched = true; return _cur; }
}
object IEnumerator.Current {
get { hasFetched = true; return _cur; }
}
public bool MoveNext() {
if (hasFetched) _cur += _incr;
return (_cur > _end ^ _incr > 0);
}
public void Reset() {
_cur = _start; hasFetched = false;
}
}
}
```
and I deployed it like this:
```
create assembly Range from 'Range.dll' with permission_set=safe -- mod path to point to actual dll location on disk.
go
create function dbo.Range(@start bigint, @end bigint, @incr bigint)
returns table(n bigint)
as external name [Range].[Range.UserDefinedFunctions].[Range]
go
create function dbo.RangeF(@start float, @end float, @incr float)
returns table(n float)
as external name [Range].[Range.UserDefinedFunctions].[RangeF]
go
```
|
SQL set-based range
|
[
"",
"sql",
"sql-server",
""
] |
As a general rule, I prefer using value rather than pointer semantics in C++ (ie using `vector<Class>` instead of `vector<Class*>`). Usually the slight loss in performance is more than made up for by not having to remember to delete dynamically allocated objects.
Unfortunately, value collections don't work when you want to store a variety of object types that all derive from a common base. See the example below.
```
#include <iostream>
using namespace std;
class Parent
{
public:
Parent() : parent_mem(1) {}
virtual void write() { cout << "Parent: " << parent_mem << endl; }
int parent_mem;
};
class Child : public Parent
{
public:
Child() : child_mem(2) { parent_mem = 2; }
void write() { cout << "Child: " << parent_mem << ", " << child_mem << endl; }
int child_mem;
};
int main(int, char**)
{
// I can have a polymorphic container with pointer semantics
vector<Parent*> pointerVec;
pointerVec.push_back(new Parent());
pointerVec.push_back(new Child());
pointerVec[0]->write();
pointerVec[1]->write();
// Output:
//
// Parent: 1
// Child: 2, 2
// But I can't do it with value semantics
vector<Parent> valueVec;
valueVec.push_back(Parent());
valueVec.push_back(Child()); // gets turned into a Parent object :(
valueVec[0].write();
valueVec[1].write();
// Output:
//
// Parent: 1
// Parent: 2
}
```
My question is: Can I have have my cake (value semantics) and eat it too (polymorphic containers)? Or do I have to use pointers?
|
Since the objects of different classes will have different sizes, you would end up running into the slicing problem if you store them as values.
One reasonable solution is to store container safe smart pointers. I normally use boost::shared\_ptr which is safe to store in a container. Note that std::auto\_ptr is not.
```
vector<shared_ptr<Parent>> vec;
vec.push_back(shared_ptr<Parent>(new Child()));
```
shared\_ptr uses reference counting so it will not delete the underlying instance until all references are removed.
|
I just wanted to point out that vector<Foo> is usually more efficient than vector<Foo\*>. In a vector<Foo>, all the Foos will be adjacent to each other in memory. Assuming a cold TLB and cache, the first read will add the page to the TLB and pull a chunk of the vector into the L# caches; subsequent reads will use the warm cache and loaded TLB, with occasional cache misses and less frequent TLB faults.
Contrast this with a vector<Foo\*>: As you fill the vector, you obtain Foo\*'s from your memory allocator. Assuming your allocator is not extremely smart, (tcmalloc?) or you fill the vector slowly over time, the location of each Foo is likely to be far apart from the other Foos: maybe just by hundreds of bytes, maybe megabytes apart.
In the worst case, as you scan through a vector<Foo\*> and dereferencing each pointer you will incur a TLB fault and cache miss -- this will end up being a *lot* slower than if you had a vector<Foo>. (Well, in the really worst case, each Foo has been paged out to disk, and every read incurs a disk seek() and read() to move the page back into RAM.)
So, keep on using vector<Foo> whenever appropriate. :-)
|
Can I have polymorphic containers with value semantics in C++?
|
[
"",
"c++",
"stl",
""
] |
How to serve users a dynamically generated ZIP archive in Django?
I'm making a site, where users can choose any combination of available books and download them as ZIP archive. I'm worried that generating such archives for each request would slow my server down to a crawl. I have also heard that Django doesn't currently have a good solution for serving dynamically generated files.
|
The solution is as follows.
Use Python module [zipfile](https://docs.python.org/3/library/zipfile.html) to create zip archive, but as the file specify [StringIO](https://docs.python.org/3/library/io.html#io.StringIO) object (ZipFile constructor requires file-like object). Add files you want to compress. Then in your Django application return the content of StringIO object in `HttpResponse` with mimetype set to `application/x-zip-compressed` (or at least `application/octet-stream`). If you want, you can set `content-disposition` header, but this should not be really required.
But beware, creating zip archives on each request is bad idea and this may kill your server (not counting timeouts if the archives are large). Performance-wise approach is to cache generated output somewhere in filesystem and regenerate it only if source files have changed. Even better idea is to prepare archives in advance (eg. by cron job) and have your web server serving them as usual statics.
|
Here's a Django view to do this:
```
import os
import zipfile
import StringIO
from django.http import HttpResponse
def getfiles(request):
# Files (local path) to put in the .zip
# FIXME: Change this (get paths from DB etc)
filenames = ["/tmp/file1.txt", "/tmp/file2.txt"]
# Folder name in ZIP archive which contains the above files
# E.g [thearchive.zip]/somefiles/file2.txt
# FIXME: Set this to something better
zip_subdir = "somefiles"
zip_filename = "%s.zip" % zip_subdir
# Open StringIO to grab in-memory ZIP contents
s = StringIO.StringIO()
# The zip compressor
zf = zipfile.ZipFile(s, "w")
for fpath in filenames:
# Calculate path for file in zip
fdir, fname = os.path.split(fpath)
zip_path = os.path.join(zip_subdir, fname)
# Add file, at correct path
zf.write(fpath, zip_path)
# Must close zip for all contents to be written
zf.close()
# Grab ZIP file from in-memory, make response with correct MIME-type
resp = HttpResponse(s.getvalue(), mimetype = "application/x-zip-compressed")
# ..and correct content-disposition
resp['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
return resp
```
|
Serving dynamically generated ZIP archives in Django
|
[
"",
"python",
"django",
""
] |
When interviewing college coops/interns or recent graduates it helps to have a Java programming question that they can do on a white board in 15 minutes. Does anyone have examples of good questions like this? A C++ question I was once asked in an interview was to write a string to integer function which is along the lines of the level of question I am looking for examples of.
|
Some stuff that has showed up on SO:
* IsPalindrome(string s)
* ReverseWordsInString(string s): "I know java" --> "java know I"
Other stuff that springs to mind:
* multiply a Vector with a Matrix (can this be done OO-Style?)
* `echo` (yes, a simple clone of the unix tool)
* `cat` (15 min should be enough, should weed out the clueless)
* a simple container for `int`s. Like `ArrayList`. **Bonus question**: Generic?
|
Is there any reason why it has to be on a whiteboard? Personally, I'd rather sit them in front of a keyboard and have them write some code. Our test used to be a simple 100 (IIRC) line Swing text editor. We then broke it a few simple ways, some making the code not compile and some a little more subtle, and gave the candidates half and hour and a list of problems to fix.
Even if you can't have them do anything hands on make sure that you do give them some explicitly technical questions. In another round of interviews there were a surprising number of recent graduates who were just buzzword-spouting IDE-jockeys, so they could look OKish waving their hands around in front of a whiteboard talking about Enterprise-this and SOA-that, but when given a simple Java fundamentals multiple choice exam asking things about what `final` and `protected` meant did horrifyingly badly.
|
Good 15 minute Java question to ask recent college graduate
|
[
"",
"java",
""
] |
Do you normally set your compiler to optimize for maximum speed or smallest code size? or do you manually configure individual optimization settings? Why?
I notice most of the time people tend to just leave compiler optimization settings to their default state, which with visual c++ means max speed.
I've always felt that the default settings had more to do with looking good on benchmarks, which tend to be small programs that will fit entirely within the L2 cache than what's best for overall performance, so I normally set it optimize for smallest size.
|
As a Gentoo user I have tried quite a few optimizations on the complete OS and there have been endless discussions on the [Gentoo forums](http://forums.gentoo.org/) about it. Some good flags for GCC can be found in the [wiki](http://gentoo-wiki.com/Safe_Cflags).
In short, optimizing for size worked best on an old Pentium3 laptop with limited ram, but on my main desktop machine with a Core2Duo, -O2 gave better results over all.
There's also a [small script](http://www.pixelbeat.org/scripts/gcccpuopt) if you are interested in the x86 (32 bit) specific flags that are the most optimized.
If you use gcc and really want to optimize a specific application, try [ACOVEA](http://www.coyotegulch.com/products/acovea/). It runs a set of benchmarks, then recompile them with all possible combinations of compile flags. There's an example using Huffman encoding on the site (lower is better):
```
A relative graph of fitnesses:
Acovea Best-of-the-Best: ************************************** (2.55366)
Acovea Common Options: ******************************************* (2.86788)
-O1: ********************************************** (3.0752)
-O2: *********************************************** (3.12343)
-O3: *********************************************** (3.1277)
-O3 -ffast-math: ************************************************** (3.31539)
-Os: ************************************************* (3.30573)
```
(Note that it found -Os to be the slowest on this Opteron system.)
|
I prefer to use minimal size. Memory may be cheap, **cache is not**.
|
How do you normally set up your compiler's optimization settings?
|
[
"",
"c++",
"c",
"optimization",
"compiler-optimization",
""
] |
I want to parse some HTML in order to find the values of some attributes/tags etc.
What HTML parsers do you recommend? Any pros and cons?
|
[NekoHTML](http://sourceforge.net/projects/nekohtml/), [TagSoup](http://home.ccil.org/~cowan/XML/tagsoup/), and [JTidy](http://sourceforge.net/projects/jtidy/) will allow you to parse HTML and then process with XML tools, like XPath.
|
I have tried [HTML Parser](http://htmlparser.sourceforge.net/) which is dead simple.
|
What HTML parsing libraries do you recommend in Java
|
[
"",
"java",
"html",
"parsing",
"html-content-extraction",
""
] |
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "\*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.
```
/*
... some Java code ...
... "... */ ..." ...
... more Java code ...
*/
```
Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.
|
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See [JLS §3.7](http://java.sun.com/docs/books/jls/second_edition/html/lexical.doc.html#48125).
|
In Eclipse you can highlight the part of the source code you want to comment out and use the Ctrl+/ to single-line comment every line in the highlighted section - puts a "//" at the beginning of the lines.
Or if you really want to block-comment the selection use the Ctrl+Shift+/ combination. It will detect the block comments in your selection. However undoing this is harder than single-line comments.
|
Do Java multi-line comments account for strings?
|
[
"",
"java",
"eclipse",
"comments",
""
] |
I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequence(unittest.TestCase):
def testsample(self):
for name, a,b in l:
print "test", name
self.assertEqual(a,b)
if __name__ == '__main__':
unittest.main()
```
The downside of this is that it handles all data in one test. I would like to generate one test for each item on the fly. Any suggestions?
|
This is called "parametrization".
There are several tools that support this approach. E.g.:
* [pytest's decorator](https://docs.pytest.org/en/latest/parametrize.html)
* [parameterized](https://github.com/wolever/parameterized)
The resulting code looks like this:
```
from parameterized import parameterized
class TestSequence(unittest.TestCase):
@parameterized.expand([
["foo", "a", "a",],
["bar", "a", "b"],
["lee", "b", "b"],
])
def test_sequence(self, name, a, b):
self.assertEqual(a,b)
```
Which will generate the tests:
```
test_sequence_0_foo (__main__.TestSequence) ... ok
test_sequence_1_bar (__main__.TestSequence) ... FAIL
test_sequence_2_lee (__main__.TestSequence) ... ok
======================================================================
FAIL: test_sequence_1_bar (__main__.TestSequence)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/parameterized/parameterized.py", line 233, in <lambda>
standalone_func = lambda *a: func(*(a + p.args), **p.kwargs)
File "x.py", line 12, in test_sequence
self.assertEqual(a,b)
AssertionError: 'a' != 'b'
```
For historical reasons I'll leave the original answer circa 2008):
I use something like this:
```
import unittest
l = [["foo", "a", "a",], ["bar", "a", "b"], ["lee", "b", "b"]]
class TestSequense(unittest.TestCase):
pass
def test_generator(a, b):
def test(self):
self.assertEqual(a,b)
return test
if __name__ == '__main__':
for t in l:
test_name = 'test_%s' % t[0]
test = test_generator(t[1], t[2])
setattr(TestSequense, test_name, test)
unittest.main()
```
|
**Using [unittest](https://docs.python.org/3/library/unittest.html) (since 3.4)**
Since Python 3.4, the standard library `unittest` package has the `subTest` context manager.
See the documentation:
* [26.4.7. Distinguishing test iterations using subtests](https://docs.python.org/3/library/unittest.html#distinguishing-test-iterations-using-subtests)
* [subTest](https://docs.python.org/3/library/unittest.html#unittest.TestCase.subTest)
Example:
```
from unittest import TestCase
param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]
class TestDemonstrateSubtest(TestCase):
def test_works_as_expected(self):
for p1, p2 in param_list:
with self.subTest(p1, p2):
self.assertEqual(p1, p2)
```
You can also specify a custom message and parameter values to `subTest()`:
```
with self.subTest(msg="Checking if p1 equals p2", p1=p1, p2=p2):
```
**Using [nose](https://pypi.org/project/nose/)**
The [nose](https://nose.readthedocs.org/en/latest/) testing framework [supports this](https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators).
Example (the code below is the entire contents of the file containing the test):
```
param_list = [('a', 'a'), ('a', 'b'), ('b', 'b')]
def test_generator():
for params in param_list:
yield check_em, params[0], params[1]
def check_em(a, b):
assert a == b
```
The output of the nosetests command:
```
> nosetests -v
testgen.test_generator('a', 'a') ... ok
testgen.test_generator('a', 'b') ... FAIL
testgen.test_generator('b', 'b') ... ok
======================================================================
FAIL: testgen.test_generator('a', 'b')
----------------------------------------------------------------------
Traceback (most recent call last):
File "/usr/lib/python2.5/site-packages/nose-0.10.1-py2.5.egg/nose/case.py", line 203, in runTest
self.test(*self.arg)
File "testgen.py", line 7, in check_em
assert a == b
AssertionError
----------------------------------------------------------------------
Ran 3 tests in 0.006s
FAILED (failures=1)
```
|
How do you generate dynamic (parameterized) unit tests in Python?
|
[
"",
"python",
"unit-testing",
"parameterized-unit-test",
""
] |
For a situation like capturing text incrementally, for example if you were receiving all of the output.write calls when a page was rendering, and those were being appended into a textwriter over a stringbuilder.
Is there a more efficient way to do this? Something that exists in dotnet already preferably? Especially if there's a total size over a hundred k. Maybe something more like an array of pages rather than contiguous memory?
|
I think StringBuilder is the most efficient way to append text in .net. To be more efficient you can specify the initial size of the StringBuilder when you create it.
|
It depends on what you're doing with that text.
If the concern is tracing or logging, I'd say your best bet is to use ETW (Event Tracing for Windows). It's a kernel-level tracing facility that's been built into Windows since Windows 2000 and it's much, much faster than doing file I/O.
If you're not using .NET 2.0, you have to do a little win32 API work to use it, and you have to create a provider class that you register on the system. It's a little complicated but worth the effort.
If you're using .NET 3.5, the managed Etw classes can be found in System.Diagnostics.Eventing.
|
Is there a more efficient text spooler than TextWriter/StringBuilder
|
[
"",
"c#",
".net",
"performance",
"string",
"data-structures",
""
] |
I'm teaching myself Python and my most recent lesson was that [Python is not Java](http://dirtsimple.org/2004/12/python-is-not-java.html), and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with `static` methods in Java, but now I'm not sure when I would use them. All the advice I can find about Python Class methods is along the lines of newbies like me should steer clear of them, and the standard documentation is at its most opaque when discussing them.
Does anyone have a good example of using a Class method in Python or at least can someone tell me when Class methods can be sensibly used?
|
Class methods are for when you need to have methods that aren't specific to any particular instance, but still involve the class in some way. The most interesting thing about them is that they can be overridden by subclasses, something that's simply not possible in Java's static methods or Python's module-level functions.
If you have a class `MyClass`, and a module-level function that operates on MyClass (factory, dependency injection stub, etc), make it a `classmethod`. Then it'll be available to subclasses.
|
Factory methods (alternative constructors) are indeed a classic example of class methods.
Basically, class methods are suitable anytime you would like to have a method which naturally fits into the namespace of the class, but is not associated with a particular instance of the class.
As an example, in the excellent [unipath](http://pypi.python.org/pypi/Unipath/0.2.1) module:
## Current directory
* `Path.cwd()`
+ Return the actual current directory; e.g., `Path("/tmp/my_temp_dir")`. This is a class method.
* `.chdir()`
+ Make self the current directory.
As the current directory is process wide, the `cwd` method has no particular instance with which it should be associated. However, changing the `cwd` to the directory of a given `Path` instance should indeed be an instance method.
Hmmm... as `Path.cwd()` does indeed return a `Path` instance, I guess it could be considered to be a factory method...
|
What is the purpose of class methods?
|
[
"",
"python",
"class-method",
""
] |
A simple question, but could someone provide sample code as to how would someone call a web service from within the JBoss Seam framework, and process the results?
I need to be able to integrate with a search platform being provided by a private vendor who is exposing his functionality as a web service. So, I'm just looking for some guidance as to what the code for calling a given web service would look like.
(Any sample web service can be chosen as an example.)
|
There's roughly a gajillion HTTP client libraries (Restlet is quite a bit more than that, but I already had that code snippet for something else), but they should all provide support for sending GET requests. Here's a rather less featureful snippet that uses [HttpClient](http://hc.apache.org/httpclient-3.x/tutorial.html) from Apache Commons:
```
HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=restbook&query=HttpClient");
client.executeMethod(method);
```
|
```
import org.restlet.Client;
import org.restlet.data.Protocol;
import org.restlet.data.Reference;
import org.restlet.data.Response;
import org.restlet.resource.DomRepresentation;
import org.w3c.dom.Node;
/**
* Uses YAHOO!'s RESTful web service with XML.
*/
public class YahooSearch {
private static final String BASE_URI = "http://api.search.yahoo.com/WebSearchService/V1/webSearch";
public static void main(final String[] args) {
if (1 != args.length) {
System.err.println("You need to pass a search term!");
} else {
final String term = Reference.encode(args[0]);
final String uri = BASE_URI + "?appid=restbook&query=" + term;
final Response response = new Client(Protocol.HTTP).get(uri);
final DomRepresentation document = response.getEntityAsDom();
document.setNamespaceAware(true);
document.putNamespace("y", "urn:yahoo:srch");
final String expr = "/y:ResultSet/y:Result/y:Title/text()";
for (final Node node : document.getNodes(expr)) {
System.out.println(node.getTextContent());
}
}
}
}
```
This code uses [Restlet](http://www.restlet.org/) to make a request to Yahoo's RESTful search service. Obviously, the details of the web service you are using will dictate what your client for it looks like.
|
Calling a Web Service from Seam
|
[
"",
"java",
"seam",
""
] |
What's a simple way to combine **feed** and **feed2**? I want the items from **feed2** to be added to **feed**. Also I want to avoid duplicates as **feed** might already have items when a question is tagged with both WPF and Silverlight.
```
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri);
SyndicationFeed feed = SyndicationFeed.Load(reader);
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri);
SyndicationFeed feed2 = SyndicationFeed.Load(reader2);
```
|
You can use LINQ to simplify the code to join two lists (don't forget to put System.Linq in your usings and if necessary reference System.Core in your project) Here's a Main that does the union and prints them to console (with proper cleanup of the Reader).
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.ServiceModel.Syndication;
namespace FeedUnion
{
class Program
{
static void Main(string[] args)
{
Uri feedUri = new Uri("http://stackoverflow.com/feeds/tag/silverlight");
SyndicationFeed feed;
SyndicationFeed feed2;
using(XmlReader reader = XmlReader.Create(feedUri.AbsoluteUri))
{
feed= SyndicationFeed.Load(reader);
}
Uri feed2Uri = new Uri("http://stackoverflow.com/feeds/tag/wpf");
using (XmlReader reader2 = XmlReader.Create(feed2Uri.AbsoluteUri))
{
feed2 = SyndicationFeed.Load(reader2);
}
SyndicationFeed feed3 = new SyndicationFeed(feed.Items.Union(feed2.Items));
StringBuilder builder = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(builder))
{
feed3.SaveAsRss20(writer);
System.Console.Write(builder.ToString());
System.Console.Read();
}
}
}
}
```
|
Well, one possibility is to create a new syndication feed that is a clone of the first feed, and then simply iterate through each post on the second one, check the first for its existence, and add it if it doesn't exist.
Something along the lines of:
```
SyndicationFeed newFeed = feed.clone;
foreach(SyndicationItem item in feed2.items)
{
if (!newFeed.contains(item))
newFeed.items.Add(item);
}
```
might be able to do it. It looks like 'items' is a simple enumberable list of syndication items, so theres not reason you can't simply add them.
|
Combining two SyndicationFeeds
|
[
"",
"c#",
"linq",
".net-3.5",
""
] |
I have a `XmlDocument` in java, created with the `Weblogic XmlDocument` parser.
I want to replace the content of a tag in this `XMLDocument` with my own data, or insert the tag if it isn't there.
```
<customdata>
<tag1 />
<tag2>mfkdslmlfkm</tag2>
<location />
<tag3 />
</customdata>
```
For example I want to insert a URL in the location tag:
```
<location>http://something</location>
```
but otherwise leave the XML as is.
Currently I use a `XMLCursor`:
```
XmlObject xmlobj = XmlObject.Factory.parse(a.getCustomData(), options);
XmlCursor xmlcur = xmlobj.newCursor();
while (xmlcur.hasNextToken()) {
boolean found = false;
if (xmlcur.isStart() && "schema-location".equals(xmlcur.getName().toString())) {
xmlcur.setTextValue("http://replaced");
System.out.println("replaced");
found = true;
} else if (xmlcur.isStart() && "customdata".equals(xmlcur.getName().toString())) {
xmlcur.push();
} else if (xmlcur.isEnddoc()) {
if (!found) {
xmlcur.pop();
xmlcur.toEndToken();
xmlcur.insertElementWithText("schema-location", "http://inserted");
System.out.println("inserted");
}
}
xmlcur.toNextToken();
}
```
I tried to find a "quick" `xquery` way to do this since the `XmlDocument` has an `execQuery` method, but didn't find it very easy.
Do anyone have a better way than this? It seems a bit elaborate.
|
How about an XPath based approach? I like this approach as the logic is super-easy to understand. The code is pretty much self-documenting.
If your xml document is available to you as an org.w3c.dom.Document object (as most parsers return), then you could do something like the following:
```
// get the list of customdata nodes
NodeList customDataNodeSet = findNodes(document, "//customdata" );
for (int i=0 ; i < customDataNodeSet.getLength() ; i++) {
Node customDataNode = customDataNodeSet.item( i );
// get the location nodes (if any) within this one customdata node
NodeList locationNodeSet = findNodes(customDataNode, "location" );
if (locationNodeSet.getLength() > 0) {
// replace
locationNodeSet.item( 0 ).setTextContent( "http://stackoverflow.com/" );
}
else {
// insert
Element newLocationNode = document.createElement( "location" );
newLocationNode.setTextContent("http://stackoverflow.com/" );
customDataNode.appendChild( newLocationNode );
}
}
```
And here's the helper method findNodes that does the XPath search.
```
private NodeList findNodes( Object obj, String xPathString )
throws XPathExpressionException {
XPath xPath = XPathFactory.newInstance().newXPath();
XPathExpression expression = xPath.compile( xPathString );
return (NodeList) expression.evaluate( obj, XPathConstants.NODESET );
}
```
|
How about an object oriented approach? You could deserialise the XML to an object, set the location value on the object, then serialise back to XML.
[XStream](http://xstream.codehaus.org/tutorial.html) makes this really easy.
For example, you would define the main object, which in your case is CustomData (I'm using public fields to keep the example simple):
```
public class CustomData {
public String tag1;
public String tag2;
public String location;
public String tag3;
}
```
Then you initialize XStream:
```
XStream xstream = new XStream();
// if you need to output the main tag in lowercase, use the following line
xstream.alias("customdata", CustomData.class);
```
Now you can construct an object from XML, set the location field on the object and regenerate the XML:
```
CustomData d = (CustomData)xstream.fromXML(xml);
d.location = "http://stackoverflow.com";
xml = xstream.toXML(d);
```
How does that sound?
|
How to insert/replace XML tag in XmlDocument?
|
[
"",
"java",
"xml",
"xquery",
""
] |
How do you generate and analyze a thread dump from a running JBoss instance?
|
There is a JBoss-specific method that is slightly more user-friendly:
<http://community.jboss.org/wiki/GenerateAThreadDumpWithTheJMXConsole>
This is especially useful when you don't have direct access to the host machine (which "kill" would require).
|
<http://java.sun.com/developer/technicalArticles/Programming/Stacktrace/>
...
"On UNIX platforms you can send a signal to a program by using the kill command. This is the quit signal, which is handled by the JVM. For example, on Solaris you can use the command kill -QUIT process\_id, where process\_id is the process number of your Java program.
Alternatively you can enter the key sequence <ctrl>\ in the window where the Java program was started. Sending this signal instructs a signal handler in the JVM, to recursively print out all the information on the threads and monitors inside the JVM."
...
"Determining the Thread States
You will see many different threads in many different states in a snapshot from a JVM stack trace. The key used is:
R Running or runnable thread
S Suspended thread
CW Thread waiting on a condition variable
MW Thread waiting on a monitor lock
MS Thread suspended waiting on a monitor lock"
|
How do you generate and analyze a thread dump from a running JBoss instance?
|
[
"",
"java",
"multithreading",
"dump",
""
] |
I am attempting to use the .Net System.Security.SslStream class to process the server side of a SSL/TLS stream with client authentication.
To perform the handshake, I am using this code:
```
SslStream sslStream = new SslStream(innerStream, false, RemoteCertificateValidation, LocalCertificateSelectionCallback);
sslStream.AuthenticateAsServer(serverCertificate, true, SslProtocols.Default, false);
```
Unfortunately, this results in the SslStream transmitting a CertificateRequest containing the subjectnames of all certificates in my CryptoAPI Trusted Root Store.
I would like to be able to override this. It is not an option for me to require the user to install or remove certificates from the Trusted Root Store.
It looks like the SslStream uses SSPI/SecureChannel underneath, so if anyone knows how to do the equivalent with that API, that would be helpful, too.
Any ideas?
|
It does not look like this is currently possible using the .NET libraries.
I solved it by using the Mono class library implementation of System.Security.SslStream, which gives better access to overriding the servers behavior during the handshake.
|
What the certificate validation is doing is validating all certificates in the chain. In order to truely do that it just contact the root store of each of those cerficates.
If that's not something you want to happen you can deploy your own root store locally.
|
How to specify accepted certificates for Client Authentication in .NET SslStream
|
[
"",
"c#",
".net",
"ssl",
"sspi",
""
] |
I am working on a project that requires the manipulation of enormous matrices, specifically pyramidal summation for a copula calculation.
In short, I need to keep track of a relatively small number of values (usually a value of 1, and in rare cases more than 1) in a sea of zeros in the matrix (multidimensional array).
A sparse array allows the user to store a small number of values, and assume all undefined records to be a preset value. Since it is not physically possible to store all values in memory, I need to store only a few non-zero elements. This could be several million entries.
Speed is a huge priority, and I would also like to dynamically choose the number of variables in the class at runtime.
I currently work on a system that uses a binary search tree (b-tree) to store entries. Does anyone know of a better system?
|
For C++, a map works well. Several million objects won't be a problem. 10 million items took about 4.4 seconds and about 57 meg on my computer.
My test application is as follows:
```
#include <stdio.h>
#include <stdlib.h>
#include <map>
class triple {
public:
int x;
int y;
int z;
bool operator<(const triple &other) const {
if (x < other.x) return true;
if (other.x < x) return false;
if (y < other.y) return true;
if (other.y < y) return false;
return z < other.z;
}
};
int main(int, char**)
{
std::map<triple,int> data;
triple point;
int i;
for (i = 0; i < 10000000; ++i) {
point.x = rand();
point.y = rand();
point.z = rand();
//printf("%d %d %d %d\n", i, point.x, point.y, point.z);
data[point] = i;
}
return 0;
}
```
Now to dynamically choose the number of variables, the easiest solution is to represent **index as a string**, and then use string as a key for the map. For instance, an item located at [23][55] can be represented via "23,55" string. We can also extend this solution for higher dimensions; such as for three dimensions an arbitrary index will look like "34,45,56". A simple implementation of this technique is as follows:
```
std::map data<string,int> data;
char ix[100];
sprintf(ix, "%d,%d", x, y); // 2 vars
data[ix] = i;
sprintf(ix, "%d,%d,%d", x, y, z); // 3 vars
data[ix] = i;
```
|
The accepted answer recommends using strings to represent multi-dimensional indices.
However, constructing strings is needlessly wasteful for this. If the size isn’t known at compile time (and thus `std::tuple` doesn’t work), `std::vector` works well as an index, both with hash maps and ordered trees. For `std::map`, this is almost trivial:
```
#include <vector>
#include <map>
using index_type = std::vector<int>;
template <typename T>
using sparse_array = std::map<index_type, T>;
```
For `std::unordered_map` (or similar hash table-based dictionaries) it’s slightly more work, since `std::vector` does not specialise `std::hash`:
```
#include <vector>
#include <unordered_map>
#include <numeric>
using index_type = std::vector<int>;
struct index_hash {
std::size_t operator()(index_type const& i) const noexcept {
// Like boost::hash_combine; there might be some caveats, see
// <https://stackoverflow.com/a/50978188/1968>
auto const hash_combine = [](auto seed, auto x) {
return std::hash<int>()(x) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
};
return std::accumulate(i.begin() + 1, i.end(), i[0], hash_combine);
}
};
template <typename T>
using sparse_array = std::unordered_map<index_type, T, index_hash>;
```
Either way, the usage is the same:
```
int main() {
using i = index_type;
auto x = sparse_array<int>();
x[i{1, 2, 3}] = 42;
x[i{4, 3, 2}] = 23;
std::cout << x[i{1, 2, 3}] + x[i{4, 3, 2}] << '\n'; // 65
}
```
|
What is the best way to create a sparse array in C++?
|
[
"",
"c++",
"oop",
"data-structures",
"hash",
"maps",
""
] |
I am looking for a tool that can serialize and/or transform SQL Result Sets into XML. Getting dumbed down XML generation from SQL result sets is simple and trivial, but that's not what I need.
The solution has to be database neutral, and accepts only regular SQL query results (no db xml support used). A particular challenge of this tool is to provide nested XML matching any schema from row based results. Intermediate steps are too slow and wasteful - this needs to happen in one single step; no RS->object->XML, preferably no RS->XML->XSLT->XML. It must support streaming due to large result sets, big XML.
Anything out there for this?
|
With SQL Server you really should consider using the *FOR XML* construct in the query.
If you're using .Net, just use a DataAdapter to fill a dataset. Once it's in a dataset, just use its .WriteXML() method. That breaks your DB->object->XML rule, but it's really how things are done. You might be able to work something out with a datareader, but I doubt it.
|
Not that I know of. I would just roll my own. It's not that hard to do, maybe something like this:
```
#!/usr/bin/env jruby
import java.sql.DriverManager
# TODO some magic to load the driver
conn = DriverManager.getConnection(ARGV[0], ARGV[1], ARGV[2])
res = conn.executeQuery ARGV[3]
puts "<result>"
meta = res.meta_data
while res.next
puts "<row>"
for n in 1..meta.column_count
column = meta.getColumnName n
puts "<#{column}>#{res.getString(n)}</#{column}"
end
puts "</row>"
end
puts "</result>"
```
**Disclaimer:** I just made all of that up, I'm not even bothering to pretend that it works. :-)
|
Converting SQL Result Sets to XML
|
[
"",
"sql",
"xml",
""
] |
In C# documentation tags allow you to produce output similar to MSDN. What are a list of allowable tags for use inside the /// (triple slash) comment area above classes, methods, and properties?
|
Check out [Great documentation on the various C# XML documentation tags.](http://web.archive.org/web/20100118163744/http://thoughtpad.net/alan-dean/cs-xml-documentation.html) (Go to the bottom to see the tags)
|
If you type this just above a method or class, intellisense should prompt you with a list of available tags:
```
/// <
```
|
What are the C# documentation tags?
|
[
"",
"c#",
"xml",
"documentation",
""
] |
I was asked this question in a job interview. The interviewer and I disagreed on what the correct answer was. I'm wondering if anyone has any data on this.
Update: I should have mentioned that the use of shuffle() was strictly forbidden... sorry.
|
You could use the [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Knuth_shuffle).
|
```
shuffle($arr);
```
:)
edit: I should clarify... my definition of best involves not just algorithm efficiency but code readability and maintainability as well. Using standard library functions means maintaining less code and reading much less too. Beyond that, you can get into year-long debates with PhD professors about the best "true random" function, so somebody will always disagree with you on randomization questions.
|
What is the best way to randomize an array's order in PHP without using the shuffle() function?
|
[
"",
"php",
"arrays",
"random",
""
] |
one of the most frequent requests I get is to create XY report for YZ App. These apps are normally built on PHP, so far I have manually created most of this reports, and while I enjoy the freedom of building it as I want, it usually becomes pretty tedious to calculate subtotals, averages, exporting to different formats etc.
What solutions are out there (free/OSS preferred) that help me get this repetitive tasks cranking?
edits:
* I'm talking about reports/summaries from SQL data. Many times from DBs not designed for reporting use.
* while I'm aware of "business-intelligence" we're not ready to implement a full scaled "intelligence" structure, looking more for a helper of sorts...
|
The problem you're facing is solved by so-called Business Intelligence software. This software tends to be bloated and expensive, but if you know your way around them you will be able to crank out such reports in no time at all.
I'm only familiar with one particular proprietary solution, which isn't too great either. But a quick search turns up the following page, which lists a number of free/open source alternatives:
<http://en.wikipedia.org/wiki/Business_intelligence_tools>
|
It depends on what kind of reports you're talking about. For example... site stats... you could install google analytics and the client could export whatever format they wanted.
|
report generation on php?
|
[
"",
"php",
"reporting",
""
] |
How would you go about proving that two queries are functionally equivalent, eg they will always both return the same result set.
---
As I had a specific query in mind when I was doing this, I ended up doing as @dougman suggested, over about 10% of rows the tables concerned and comparing the results, ensuring there was no out of place results.
|
The best you can do is compare the 2 query outputs based on a given set of inputs looking for any differences. To say that they will always return the same results for all inputs really depends on the data.
For Oracle one of the better if not best approaches (very efficient) is here (`Ctrl`+`F` Comparing the Contents of Two Tables):
[<http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html>](http://www.oracle.com/technetwork/issue-archive/2005/05-jan/o15asktom-084959.html)
Which boils down to:
```
select c1,c2,c3,
count(src1) CNT1,
count(src2) CNT2
from (select a.*,
1 src1,
to_number(null) src2
from a
union all
select b.*,
to_number(null) src1,
2 src2
from b
)
group by c1,c2,c3
having count(src1) <> count(src2);
```
|
**1) Real equivalency proof with Cosette:**
Cosette checks (with a proof) if 2 SQL query's are equivalent and counter examples when not equivalent. It's the only way to be absolutely sure, well almost ;) You can even throw in 2 query's on their website and check (formal) equivalence right away.
Link to Cosette:
<https://cosette.cs.washington.edu/>
Link to article that gives a good explanation of how Cosette works: <https://medium.com/@uwdb/introducing-cosette-527898504bd6>
**2) Or if you're just looking for a quick practical fix:**
Try this stackoverflow answer: [[sql - check if two select's are equal]](https://stackoverflow.com/questions/5727882/check-if-two-selects-are-equivalent)
Which comes down to:
```
(select * from query1 MINUS select * from query2)
UNION ALL
(select * from query2 MINUS select * from query1)
```
This query gives you all rows that are returned by only one of the queries.
|
Proving SQL query equivalency
|
[
"",
"sql",
"oracle",
""
] |
Maybe this is a dumb question, but is there any way to convert a boolean value to a string such that 1 turns to "true" and 0 turns to "false"? I could just use an if statement, but it would be nice to know if there is a way to do that with the language or standard libraries. Plus, I'm a pedant. :)
|
How about using the C++ language itself?
```
bool t = true;
bool f = false;
std::cout << std::noboolalpha << t << " == " << std::boolalpha << t << std::endl;
std::cout << std::noboolalpha << f << " == " << std::boolalpha << f << std::endl;
```
UPDATE:
If you want more than 4 lines of code without any console output, please go to [cppreference.com's page talking about `std::boolalpha` and `std::noboolalpha`](https://en.cppreference.com/w/cpp/io/manip/boolalpha) which shows you the console output and explains more about the API.
Additionally using `std::boolalpha` will modify the global state of `std::cout`, you may want to restore the original behavior [go here for more info on restoring the state of `std::cout`](https://stackoverflow.com/q/2273330/52074).
|
We're talking about C++ right? Why on earth are we still using macros!?
C++ inline functions give you the same speed as a macro, with the added benefit of type-safety and parameter evaluation (which avoids the issue that Rodney and dwj mentioned.
```
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
```
Aside from that I have a few other gripes, particularly with the accepted answer :)
```
// this is used in C, not C++. if you want to use printf, instead include <cstdio>
//#include <stdio.h>
// instead you should use the iostream libs
#include <iostream>
// not only is this a C include, it's totally unnecessary!
//#include <stdarg.h>
// Macros - not type-safe, has side-effects. Use inline functions instead
//#define BOOL_STR(b) (b?"true":"false")
inline const char * const BoolToString(bool b)
{
return b ? "true" : "false";
}
int main (int argc, char const *argv[]) {
bool alpha = true;
// printf? that's C, not C++
//printf( BOOL_STR(alpha) );
// use the iostream functionality
std::cout << BoolToString(alpha);
return 0;
}
```
Cheers :)
---
@DrPizza: Include a whole boost lib for the sake of a function this simple? You've got to be kidding?
|
Converting bool to text in C++
|
[
"",
"c++",
"string",
"boolean",
""
] |
I'm developing a .NET 3.5 XBAP application that runs perfectly fine in FF3 and IE6/7 etc. I'm just wondering if its possible to get these to run under other browsers, specifically (as its in the limelight at the moment) Google Chrome.
|
XBAP applications do work in google chrome, however you have to set your environments PATH variable to the directory where xpcom.dll is located.
for example SET PATH=PATH;"C:\Program Files\Mozilla Firefox"
|
At the moment, XBAPs do not work in Google Chrome. I've gotten it to run once, somehow, but every time there after I've received an error that the browser cannot locate xpcom.dll. Apparently this error occurs for more than just XBAP applications. From what I've read users will have to wait for a fix seeing as Chrome is still in beta.
**Update:**
Looks like it's not going to be fixed: <http://code.google.com/p/chromium/issues/detail?id=4051>
|
XBAP Application, can these work in Google Chrome?
|
[
"",
"c#",
".net",
"google-chrome",
"xbap",
""
] |
What is the best C++ IDE for a \*nix envirnoment? I have heard the C/C++ module of Eclipse is decent as well as Notepad++ but beyond these two I have no real idea. Any thoughts or comments?
|
On Ubuntu, some the IDEs that are available in the repositories are:
* [Kdevelop](http://www.kdevelop.org/)
* [Geany](http://geany.uvena.de/)
* [Anjuta](http://anjuta.sf.net/)
There is also:
* [Eclipse](http://eclipse.org) (Recommended you don't install from repositories, due to issues with file/folder permissions)
* [Code::blocks](http://www.codeblocks.org/)
And of course, everyone's favourite text-based editors:
* vi/vim
* emacs
Its true that vim and emacs are very powerful tools, but the learning curve is very steep..
I really don't like **Eclipse** that much, I find it buggy and a bit too clunky.
I've started using **Geany** as a bare-bones but functional and *usable* IDE. It has a basic code-completion feature, and is a nice, clean [Gnome] interface.
**Anjuta** I tried for a day, didn't like it at all. I didn't find it as useful as Geany.
**Kdevelop** and **code::blocks** get a bunch of good reviews, but I haven't tried them. I use gnome, and I'm yet to see a KDE app that looks good in gnome (sorry, I'm sure its a great program).
If only bloodshed dev-c++ was released under linux. That is a fantastic (but windows-only) program. You could always run it under Wine ;)
To a degree, it comes down to personal preference. My advice is to investigate Kdevelop, Geany and code::blocks as a starting point.
|
As a programmer who has been writing code under linux for many years, I simply cannot seem to move away from using Vim for writing code.
Once you learn it, and learn some of its more advanced features (Code Folding, how to use ctags, how to work with multiple buffers effectively, etc) moving to another editor is very hard - as everything else seems to be missing features that you're used to.
The only other editor with a superset of vim's features is emacs. I highly recommend learning one or the other - and if you have questions, don't hesitate to ask here or in #emacs or #vim on irc.freenode.net - there's a very large and helpful community that will help you learn what extensions or commands best suit the software editing problems that you're facing.
[Edit: A comment noted that "vim isn't an IDE", I agree. I don't like the IDE moniker because it means a gui with a project manager and a bunch of drop down boxes. I like to use the terminology "**Good Tools**". See [Ted Leung's](http://www.sauria.com/blog/2008/07/20/ides-and-dynamic-languages/) writings on the matter]
|
Best C++ IDE for *nix
|
[
"",
"c++",
"ide",
""
] |
I'm looking into sending regular automated text-messages to a list of subscribed users. Having played with Windows Mobile devices, I could easily implement this using the compact .Net framework + a device hooked up to usb and send the messages through this. I would like to explore other solutions like having a server or something similar to do this. I just have no idea what is involved in such a system.
|
It really all depends on how many text messages you intend to send and how critical it is that the message arrives on time (and, actually arrives).
## SMS Aggregators
For larger volume and good reliability, you will want to go with an SMS aggregator. These aggregators have web service API's (or SMPP) that you can use to send your message and find out whether your message was delivered over time. Some examples of aggregators with whom I have experience are Air2Web, mBlox, etc.
The nice thing about working with an aggregator is that they can guide you through what it takes to send effective messages. For example, if you want your own, distinct, shortcode they can navigate the process with the carriers to secure that shortcode.
They can also make sure that you are in compliance with any rules regarding using SMS. Carriers will flat shut you off if you don't respect the use of SMS and only use SMS within the bounds of what you agreed to when you started to use the aggregator. If you overstep your bounds, they have the aggregator relationships to prevent any service interruptions.
You'll pay per message and may have a baseline service fee. All if this is determined by your volume.
## SMTP to SMS
If you want an unreliable, low-rent solution to a low number of known addresses, you can use an SMTP to SMS solution. In this case you simply find out the mobile provider for the recipient and use their mobile provider's e-mail scheme to send the message. An example of this is 7705551212@cellcompany.com.
In this scenario, you send the message and it is gone and you hope that it gets there. You really don't know if it is making it. Also, some providers limit how messages come in via their SMTP to SMS gateway to limit SMS spam.
But, that scenario is the very easiest to use from virtually any programming language. There are a million C# examples of how to send e-mail and this way would be no different.
This is the most cost-effective solution (i.e. free) until you get a large volume of messages. When you start doing too much of this, the carriers might step in when they find that you are sending a ton of messages through their SMTP to SMS gateway.
## Effective Texting
In many cases you have to make sure that recipients have properly opted-in to your service. This is only a big deal if your texts are going to a really large population.
You'll want to remember that text messages are short (keep it to less than 140 to 160 characters). When you program things you'll want to bake that in or you might accidentally send multipart messages.
Don't forget that you will want to make sure that your recipients realize they might have to pay for the incoming text messages. In a world of unlimited text plans this is less and less of a concern.
|
You can usually get an account with an sms service provider and send messages using an API (SOAP, resful http, smpp ....)
A google search for sms service provider yeilds many results with varying costs.
Here is an informative article [How to Choose an SMS Service Provider](http://www.developershome.com/sms/howToChooseSMSGateway.asp)
|
What kind of technologies are available for sending text messages?
|
[
"",
"c#",
"mobile",
"messaging",
""
] |
I'm a long-time emacs user, and I'm now working about 1/2 time in Java.
What are the best emacs libraries for
1. Debugging Java
2. Code Completion/Intellisense
3. Javadoc browsing
?
|
I've used [JDEE](http://jdee.sourceforge.net/) on several projects. It handles Code Completion. I've never used it for debugging or browsing docs, but it's a big step up from a basic text editor.
|
For javadoc I found <http://javadochelp.sourceforge.net/index.html> to be the best.
Exuberant ctags is your best friend when it comes to navigation.
|
Best java tools for emacs
|
[
"",
"java",
"debugging",
"emacs",
"ide",
"javadoc",
""
] |
I have been reading through the [C++ FAQ](http://yosefk.com/c++fqa/) and was curious about the [`friend`](http://yosefk.com/c++fqa/friend.html) declaration. I personally have never used it, however I am interested in exploring the language.
What is a good example of using `friend`?
---
Reading the FAQ a bit longer I like the idea of the `<<` `>>` operator overloading and adding as a friend of those classes. However I am not sure how this doesn't break encapsulation. When can these exceptions stay within the strictness that is OOP?
|
Firstly (IMO) don't listen to people who say `friend` is not useful. It IS useful. In many situations you will have objects with data or functionality that are not intended to be publicly available. This is particularly true of large codebases with many authors who may only be superficially familiar with different areas.
There ARE alternatives to the friend specifier, but often they are cumbersome (cpp-level concrete classes/masked typedefs) or not foolproof (comments or function name conventions).
Onto the answer;
The `friend` specifier allows the designated class access to protected data or functionality within the class making the friend statement. For example in the below code anyone may ask a child for their name, but only the mother and the child may change the name.
You can take this simple example further by considering a more complex class such as a Window. Quite likely a Window will have many function/data elements that should not be publicly accessible, but ARE needed by a related class such as a WindowManager.
```
class Child
{
//Mother class members can access the private parts of class Child.
friend class Mother;
public:
string name( void );
protected:
void setName( string newName );
};
```
|
At work we **use friends for testing code**, extensively. It means we can provide proper encapsulation and information hiding for the main application code. But also we can have separate test code that uses friends to inspect internal state and data for testing.
Suffice to say I wouldn't use the friend keyword as an essential component of your design.
|
When should you use 'friend' in C++?
|
[
"",
"c++",
"oop",
"encapsulation",
"friend",
""
] |
Let's say the first N integers divisible by 3 starting with 9.
I'm sure there is some one line solution using lambdas, I just don't know it that area of the language well enough yet.
|
Just to be different (and to avoid using a where statement) you could also do:
```
var numbers = Enumerable.Range(0, n).Select(i => i * 3 + 9);
```
**Update** This also has the benefit of not running out of numbers.
|
Using Linq:
```
int[] numbers =
Enumerable.Range(9,10000)
.Where(x => x % 3 == 0)
.Take(20)
.ToArray();
```
Also easily parallelizeable using PLinq if you need:
```
int[] numbers =
Enumerable.Range(9,10000)
.AsParallel() //added this line
.Where(x => x % 3 == 0)
.Take(20)
.ToArray();
```
|
What is the simplest way to initialize an Array of N numbers following a simple pattern?
|
[
"",
"c#",
""
] |
In C# is there a shorthand way to write this:
```
public static bool IsAllowed(int userID)
{
return (userID == Personnel.JohnDoe || userID == Personnel.JaneDoe ...);
}
```
Like:
```
public static bool IsAllowed(int userID)
{
return (userID in Personnel.JohnDoe, Personnel.JaneDoe ...);
}
```
I know I could also use switch, but there are probably 50 or so functions like this I have to write (porting a classic ASP site over to ASP.NET) so I'd like to keep them as short as possible.
|
How about this?
```
public static class Extensions
{
public static bool In<T>(this T testValue, params T[] values)
{
return values.Contains(testValue);
}
}
```
Usage:
```
Personnel userId = Personnel.JohnDoe;
if (userId.In(Personnel.JohnDoe, Personnel.JaneDoe))
{
// Do something
}
```
I can't claim credit for this, but I also can't remember where I saw it. So, credit to you, anonymous Internet stranger.
|
How about something like this:
```
public static bool IsAllowed(int userID) {
List<int> IDs = new List<string> { 1,2,3,4,5 };
return IDs.Contains(userID);
}
```
(You could of course change the static status, initialize the IDs class in some other place, use an IEnumerable<>, etc, based on your needs. The main point is that the closest equivalent to the *in* operator in SQL is the Collection.Contains() function.)
|
Shorthand conditional in C# similar to SQL 'in' keyword
|
[
"",
"c#",
"lambda",
"conditional-statements",
"if-statement",
""
] |
I have a table with an XML column. This column is storing some values I keep for configuring my application. I created it to have a more flexible schema.
I can't find a way to update this column directly from the table view in SQL Management Studio. Other (INT or Varchar for example) columns are editable. I know I can write an UPDATE statement or create some code to update it. But I'm looking for something more flexible that will let power users edit the XML directly.
Any ideas?
> Reiterating again: Please don't answer
> I can write an application. I know
> that, And that is exactly what I'm
> trying to avoid.
|
This is an old question, but I needed to do this today. The best I can come up with is to write a query that generates SQL code that can be edited in the query editor - it's sort of lame but it saves you copy/pasting stuff.
Note: you may need to go into Tools > Options > Query Results > Results to Text and set the maximum number of characters displayed to a large enough number to fit your XML fields.
e.g.
```
select 'update [table name] set [xml field name] = ''' +
convert(varchar(max), [xml field name]) +
''' where [primary key name] = ' +
convert(varchar(max), [primary key name]) from [table name]
```
which produces a lot of queries that look like this (with some sample table/field names):
```
update thetable set thedata = '<root><name>Bob</name></root>' where thekey = 1
```
You then copy these queries from the results window back up to the query window, edit the xml strings, and then run the queries.
(Edit: changed 10 to max to avoid error)
|
I have a cheap and nasty workaround, but is ok. So, do a query of the record, i.e.
```
SELECT XMLData FROM [YourTable]
WHERE ID = @SomeID
```
Click on the xml data field, which should be 'hyperlinked'. This will open the XML in a new window. Edit it, then copy and paste the XML back into a new query window:
```
UPDATE [YourTable] SET XMLData = '<row><somefield1>Somedata</somefield1>
</row>'
WHERE ID = @SomeID
```
But yes, WE Desparately need to be able to edit. If you are listening Mr. Soft, please look at Oracle, you can edit XML in their Mgt Studio equivalent. Let's chalk it up to an oversight, I am still a HUGE fan of SQL server.
|
How to easily edit SQL XML column in SQL Management Studio
|
[
"",
"sql",
"sql-server",
"xml",
""
] |
I want to put a copyright notice in the footer of a web site, but I think it's incredibly tacky for the year to be outdated.
How would I make the year update automatically with PHP
|
You can use either [date](http://php.net/manual/en/function.date.php) or [strftime](http://php.net/manual/en/function.strftime.php). In this case I'd say it doesn't matter as a year is a year, no matter what (unless there's a locale that formats the year differently?)
For example:
```
<?php echo date("Y"); ?>
```
On a side note, when formatting dates in PHP it matters when you want to format your date in a different locale than your default. If so, you have to use setlocale and strftime. According to the [php manual](http://php.net/manual/en/function.date.php) on date:
> To format dates in other languages,
> you should use the setlocale() and
> strftime() functions instead of
> date().
From this point of view, I think it would be best to use strftime as much as possible, if you even have a remote possibility of having to localize your application. If that's not an issue, pick the one you like best.
|
```
<?php echo date("Y"); ?>
```
|
How do I use PHP to get the current year?
|
[
"",
"php",
"date",
""
] |
Is there an easy way to set the zoom level for a windows form in C#? In VBA there was a zoom property of the form.
|
There is no way (that I know of) to do what you ask with typical WinForms.
If you're doing custom painting/drawing, you can zoom that by using a zoom transform, but so far as I know there is no "Zoom" property for the form in the entire world of .NET and native Windows/C++ APIs combined.
You could probably rig something yourself such that you scale controls by a constant factor. And you can probably find 3rd-party controls/surfaces which support this. And who knows what is possible with WPF. But in a typical WinForms world, no.
|
I had the same problem and I solved it this way in c#. Code goes on Form load
```
float scaleX = ((float)Screen.PrimaryScreen.WorkingArea.Width / 1024);
float scaleY = ((float)Screen.PrimaryScreen.WorkingArea.Height / 768);
SizeF aSf = new SizeF(scaleX, scaleY);
this.Scale(aSf);
```
This "more or less" scales form and all children. Loops forever in 800x600 (?)
You have to set the following Form properties:
```
AutoscaleMode = Font
AutoSize = False
```
|
Zoom for a windows form in C#
|
[
"",
"c#",
"winforms",
""
] |
What's the best way to go about validating that a document follows some version of HTML (prefereably that I can specify)? I'd like to be able to know where the failures occur, as in a web-based validator, except in a native Python app.
|
XHTML is easy, use [lxml](http://lxml.de/validation.html).
```
from lxml import etree
from StringIO import StringIO
etree.parse(StringIO(html), etree.HTMLParser(recover=False))
```
HTML is harder, since there's traditionally not been as much interest in validation among the HTML crowd (run StackOverflow itself through a validator, yikes). The easiest solution would be to execute external applications such as [nsgmls](http://www.jclark.com/sp/) or [OpenJade](http://openjade.sourceforge.net/), and then parse their output.
|
[PyTidyLib](http://countergram.github.io/pytidylib/) is a nice python binding for HTML Tidy. Their example:
```
from tidylib import tidy_document
document, errors = tidy_document('''<p>fõo <img src="bar.jpg">''',
options={'numeric-entities':1})
print document
print errors
```
Moreover it's compatible with both [legacy HTML Tidy](http://tidy.sourceforge.net/) and the [new tidy-html5](http://www.html-tidy.org/).
|
Validate (X)HTML in Python
|
[
"",
"python",
"html",
"validation",
"xhtml",
""
] |
Is there a difference between `NULL` and `null` in PHP? Sometimes they seem to be interchangeable and sometimes not.
edit: for some reason when I read the documentation linked to in the answer (before posting this question) I read it as "case sensitive" instead of "case insensitive" which was the whole reason I posted this question in the first place...
|
Null is case insensitive.
From the [documentation](https://www.php.net/manual/en/language.types.null.php):
> There is only one value of type null, and that is the **case-insensitive** keyword NULL.
|
There is no difference. Same type just its a **case insensitive** keyword. Same as `True`/`False` etc...
|
Difference between NULL and null in PHP
|
[
"",
"php",
"null",
""
] |
Normally I would just use:
```
HttpContext.Current.Server.UrlEncode("url");
```
But since this is a console application, `HttpContext.Current` is always going to be `null`.
Is there another method that does the same thing that I could use?
|
Try this!
```
Uri.EscapeUriString(url);
```
Or
```
Uri.EscapeDataString(data)
```
No need to reference System.Web.
**Edit:** Please see [another](https://stackoverflow.com/a/34189188/7391) SO answer for more...
|
I'm not a .NET guy, but, can't you use:
```
HttpUtility.UrlEncode Method (String)
```
Which is described here:
[HttpUtility.UrlEncode Method (String) on MSDN](http://msdn.microsoft.com/en-us/library/4fkewx0t.aspx)
|
UrlEncode through a console application?
|
[
"",
"c#",
".net",
"console",
""
] |
I wrote an application that currently runs against a local instance of MySql. I would like to centralize the DB somewhere on the Net, and share my application.
But, I'm cheap, and don't want to pay for it. Does anyone know of a free on-line relational DB service that I could connect to via C#?
|
What about <http://www.freesql.org> ? Seems like you can't be too picky when you're asking for free, and this seems to offer something.
|
Oops, didn't read the question properly that time! :P
Haven't tried this yet, and their site says they had had a major crash recently, but it looks promising: <http://www.freesql.org/>
|
Anyone know of an on-line free database?
|
[
"",
"c#",
"database",
""
] |
For reasons I won't go into, I wish to ban an entire company from accessing my web site. Checking the remote hostname in php using gethostbyaddr() works, but this slows down the page load too much. Large organizations (eg. hp.com or microsoft.com) often have blocks of IP addresses. Is there anyway I get the full list, or am I stuck with the slow reverse-DNS lookup? If so, can I speed it up?
Edit: Okay, now I know I can use the .htaccess file to ban a range. Now, how can I figure out what that range should be for a given organization?
|
How about an .htaccess:
```
Deny from x.x.x.x
```
if you need to deny a range say: 192.168.0.x then you would use
```
Deny from 192.168.0
```
and the same applies for hostnames:
```
Deny from sub.domain.tld
```
or if you want a PHP solution
```
$ips = array('1.1.1.1', '2.2.2.2', '3.3.3.3');
if(in_array($_SERVER['REMOTE_ADDR'])){die();}
```
For more info on the htaccess method see [this](http://httpd.apache.org/docs/1.3/mod/mod_access.html) page.
Now to determine the range is going to be hard, most companies (unless they are big corperate) are going to have a dynamic IP just like you and me.
This is a problem I have had to deal with before and the best thing is either to ban the hostname, or the entire range, for example if they are on 192.168.0.123 then ban 192.168.0.123, unfortunatly you are going to get a few innocent people with either method.
|
If you're practicing safe webhosting, then you have a firewall. Use it.
Large companies have blocks of IP addresses, but even smaller companies rarely change their IP. So there's an easy way to do this without reducing your performance:
Every month do a reverse lookup on all the IPs in your log and then put all the IPs used by that company in your firewall as deny.
After awhile yo'll begin to see whether they have dynamic addresses or not. If they do, then you may have to do reverse lookups for each connection attempt, but unless they are a small company you shouldn't have to worry about it.
|
How can I ban a whole company from my web site?
|
[
"",
".net",
"php",
"apache",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.