Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have the input 15:20:30
I want to convert to seconds. | Seeing as though you haven't specified the question properly I have interpreted it to represent 15 hours 20 minutes and 30 seconds, as opposed to DateTime.Now. (Obviously this is the same as "How many seconds since midnight")
```
TimeSpan MySpan = new TimeSpan(15, 20, 30);
MySpan.TotalSeconds;
```
Although if you're only wanting the Seconds from the current DateTime.Now (this is not the TotalSeconds, just the current minutes seconds), just use:
```
DateTime.Now.Second
``` | ```
var dt = DateTime.Now;
var ticks = dt.Ticks;
var seconds = ticks/TimeSpan.TicksPerSecond;
```
Each tick is 100 nanoseconds. | how to Convert DateTime Now To second | [
"",
"c#",
"datetime",
""
] |
Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.
The step I get hung up on is this one:
"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this step, see documentation and code samples for your programming language."
Given a string and a secret key (in this case 1234567890) how do I calculate this hash using Python?
----------- UPDATE -------------
The first solution using HMAC.new looks correct however I'm getting a different result than they are.
<http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest-signature.html>
According to Amazon's example when you hash the secret key 1234567890 and the following string
```
GET
webservices.amazon.com
/onca/xml
AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=I
temLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReview
s&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&
Version=2009-01-06
```
You should get the following signature: `'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='`
I am getting this: `'411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'` | ```
import hmac
import hashlib
import base64
dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest()
base64.b64encode(dig).decode() # py3k-mode
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='
``` | ```
import hmac
import hashlib
import base64
digest = hmac.new(secret, msg=thing_to_hash, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(digest).decode()
```
I know this sounds silly, but make sure you don't have a trailing space on your secret by accident. | Calculating a SHA hash with a string + secret key in python | [
"",
"python",
"hash",
"sha256",
""
] |
hI,
I am working with a treeview in C# using visual studio 2005 and want to find a tree node and add nodes below it upon a button being pressed in my windows forms application.
I have tried using treeView1.Nodes.Find("My\_Text", true);
where "My\_Text" is the text associated with the node under which i want to add mode nodes.
However I cannot find a way to use this to my advantage as I dont know what this statement returns.
I ntend to use treeView1.SelectedNode.Nodes.Add(newnode); to add nodes but for that I need to select a node first. And treeView1.Nodes.Find does not look likt it selects the node for me. Any help? | Are you sure that a node with give text exists in your application? I just tried a simple test application and the Find method worked without problems...
```
private void button1_Click(object sender, EventArgs e) {
// WARNING: add checks
TreeNode[] nodes = treeView1.Nodes.Find("Node2",true);
TreeNode node = nodes[0];
node.Nodes.Add("child node");
}
``` | Do you need to use SelectedNode.Nodes.Add()? The Nodes.Add(...) operation can be performed on any TreeNode. So, if you can find the node at all, simply call node.Nodes.Add(..). You don't need to select it first.
Have a look at the documentation or intellisense information to see what the Find() method returns. | + sign in front of a tree node | [
"",
"c#",
"visual-studio",
"treeview",
""
] |
In hibernate as well as simple ORM strategy,i am normally loading all the values for the objects.Is there any way to avoid this.
Due to this my app running slowly.. | There are several ways to achieve this:
* Enable caching. While the SQL won't change, Hibernate will compare the results from the database and reuse existing objects. This doesn't give an enormous boost but it's simple to implement and maintain.
* Create a second mapping (same tables, different object) to load just a subset of the values.
* Move the rarely used data into a second table.
* Load your objects with a custom native SQL query. Here, you must make sure that you know how much has been loaded and how to "fill the gaps". | The Hibernate reference document has a chapter on [Improving Performance](http://docs.jboss.org/hibernate/stable/core/reference/en/html/performance.html). You could look at your fetching strategies or whether using caching would improve performance.
To be more specific you would need to provide more details on your application and how the objects loaded via ORM are used. | How can we reduce the unnecessary loading of objects? | [
"",
"java",
"performance",
"hibernate",
"orm",
""
] |
I've added a field to a MySQL table. I need to populate the new column with the value from another table. Here is the query that I'd like to run:
```
UPDATE table1 t1
SET t1.user_id =
(
SELECT t2.user_id
FROM table2 t2
WHERE t2.usr_id = t1.usr_id
)
```
I ran that query locally on 239K rows and it took about 10 minutes. Before I do that on the live environment I wanted to ask if what I am doing looks ok i.e. does 10 minutes sound reasonable. Or should I do it another way, a php loop? a better query? | Use an `UPDATE JOIN`! This will provide you a native `inner join` to update from, rather than run the subquery for every bloody row. It tends to be *much* faster.
```
update table1 t1
inner join table2 t2 on
t1.usr_id = t2.usr_id
set t1.user_id = t2.user_id
```
Ensure that you have an index on each of the `usr_id` columns, too. That will speed things up quite a bit.
If you have some rows that don't match up, and you want to set `t1.user_id = null`, you will need to do a `left join` in lieu of an `inner join`. If the column is `null` already, and you're just looking to update it to the values in `t2`, use an `inner join`, since it's faster.
I should make mention, for posterity, that this is MySQL syntax *only*. The other RDBMS's have different ways of doing an `update join`. | There are two rather important pieces of information missing:
1. What type of tables are they?
2. What indexes exist on them?
If `table2` has an index that contains `user_id` and `usr_id` as the first two columns and `table1` is indexed on `user_id`, it shouldn't be that bad. | Execute MySQL update query on 750k rows | [
"",
"sql",
"mysql",
""
] |
This is in reference to C++ and using the Visual Studio compilers.
Is there any difference in speed when reading/writing (to RAM) and doing mathematical operations on different types of variables such as bool, short int, int, float, and doubles?
From what I understand so far, mathematical operations with doubles takes much longer (I am talking about 32 bit processors, I know little about 64 bit processors) than, say, operations with floats.
How then do operations (reading/writing to ram and elementary math) with float and int compare? How about int and short int, or even differences between signed and unsigned versions of each of the types? Is there any one data type that would be most efficient to work with as low number counters?
Thanks,
-Faken | There are two different questions here: speed when reading/writing, and arithmetic performance. Those are orthogonal. When reading or writing a large array, of course, the speed depends on the amount of bytes read as O(N), so using `short` over `int` (considering VC++) would slash the time by ~1/2.
For arithmetic, once the operands are in registers, the size of the type doesn't matter so much. IIRC, between types in the same category, it is actually the same (so `short` isn't any faster or slower than `int`). Using 64-bit integer types on a 32-bit platform will have a penalty, naturally, since there's no single instruction to handle that. Floating-point types, on the other hand, are simply slower than all integral types, even though `sizeof(float)==sizeof(int)` on VC++. But, again, operations on `float` aren't any faster than operations on `double`; this is assuming default FPU settings, which promote all operands to 80-bit extended floats - this can be disabled to squeeze out a bit more out of using `float`s, IIRC.
The above is VC++ and x86 specific, as requested by the question. Other platform, and especially other architecture, can differ radically.
The best one data type that is most efficient to work with as number counter (low or not) is `int` - usually regardless of the architecture and implementation (as the Standard recommends it to be the preferred word size of the platform). | > From what I understand so far, mathematical operations with doubles takes much longer (we are talking about 32 bit processors, I know little about 64 bit processors) than say operations with floats.
I don't know (I've virtually never programmed floating-point arithmethic) but I doubt that: because double is native precision (supported by hardware), whereas I don't know about float.
> How then do operations (reading/writing to ram and elementary math) with float and int compare?
Float is slower than int.
> how about int and short int, or even differences between signed and unsigned versions of each of the variables?
Short may be slower than int, because the CPU uses int natively and needs to truncate results to make them short. They'd only be faster if there are so many of them contiguously that they're better at fitting in the CPU cache.
> differences between signed and unsigned versions of each of the variables?
No I don't think so.
> Is there any one data type that would be most efficient to work with as low number counters?
int. | Is there any difference in speed in manipulating different types of variables? | [
"",
"c++",
"performance",
"variables",
""
] |
We need a cross platform solution for compressing files. Our server runs on Windows XP/Vista/7 and 3 Unix distros, SunOS, HPUX, and AIX. Our server creates files that needed to be zipped before being set back to the client. Our initial thought was to compress the files with jar, as most of the servers have java installed, but apparently jar isn't included in the jre, just the jdk. Our server is written in C and the application that needs to create a compressed file is Perl.
I'd really like something I don't have install as our install base is LARGE and adding new required applications is generally difficult. Is there anything that is guaranteed to be built into each of those OSes that I could use for zipping? Even if I have to use something different for each, that would probably be okay also. | If you don't want to have to install anything you're pretty much SOL. Windows doesn't make this easy.
If you want to write something yourself [java.util.zip](http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/package-summary.html) is in the Java 2 Standard Edition (J2SE) and Perl has [Archive::Zip](http://search.cpan.org/dist/Archive-Zip/) | I do like 7-zip a lot but for situations like yours I always go to least-common denominataor: ZIP. Simple old ZIP. Most Unices and linuxes have `zip` and `unzip`. And for windows there are lots of options, including [7-zip](http://www.7-zip.org/), that can manipulate zip files. And probably the clients will have a zip client installed. | Cross platform file compression | [
"",
"java",
"perl",
"compression",
"zip",
""
] |
I'm looking for ways to detect/estimate the **country** from which a **http-request** is coming in **ASP.NET**.
I know there are some solutions with services/country lookups but I never used one.
I'm looking for small/clean solutions.
It's for helping someone filling out a form so it does not have to be 100% accurate.
Thanks in advance.. | You can use one of available web services to match an incoming request to a country.
Otherwise you may decide to grab the MaxMind database file ([GeoLite Country](http://www.maxmind.com/app/geoip_country)), read from this file in your application and perform a match. Thus you will be independent from a third-party service, only pulling regularly updates for the database file.
Also check out similar questions:
[Geolocation web service recommendations](https://stackoverflow.com/questions/1247238/geolocation-web-service-recommendations)
[Know a good IP address Geolocation Service?](https://stackoverflow.com/questions/283016/know-a-good-ip-address-geolocation-service) | You can make a simple HTTP request to this URL:
```
http://api.hostip.info/get_html.php?ip=207.46.197.32
```
using the value of the `REMOTE_ADDR` server variable. That will return the country and city like this:
```
Country: UNITED STATES (US)
City: New York, NY
```
I use that service for a web form just as you describe. Occasionally it doesn't know the answer, but usually it's very good (and it's free and simple 8-)
In C#, you can use [System.Net.WebRequest.Create](http://msdn.microsoft.com/en-us/library/system.net.webrequest.create(v=vs.110).aspx) to read from the URL. | Detect/estimate country of a http-request in ASP.NET | [
"",
"c#",
"asp.net",
"http",
""
] |
I have a table representing standards of alloys. The standard is partly based on the chemical composition of the alloys. The composition is presented in percentages. The percentage is determined by a chemical composition test. [Sample data](https://imgur.com/7gyhr).
But sometimes, the lab cannot measure below a certain percentage. So they indicate that the element is present, but the percentage is less than they can measure.
I was confused how to accurately store such a number in an SQL database. I thought to store the number with a negative sign. No element can have a negative composition of course, but i can interpret this as less than the specified value. Or option is to add another column for each element!! The latter option i really don't like.
Any other ideas? It's a small issue if you think about it, but i think a crowd is always wiser. Somebody might have a neater solution.
---
## Question updated:
Thanks for all the replies.
* The test results come from different labs, so there is no common lower bound.
* The when the percentage of Titanium is less than <0.0004 for example, the number is still important, only the formula will differ slightly in this case.
Hence the value cannot be stored as NULL, and i don't know the lower bound for all values.
Tricky one.
Another possibility i thought of is to store it as a string. Any other ideas? | Since the constraints of the values are well defined (cannot have negative composition), I would go for the "negative value to indicate less-than" approach. As long as this use of such sentinel values are sufficiently documented, it should be reasonably easy to implement and maintain.
An alternative but similar method would be to add 100 to the values, assuming that you can't get more than 100%. So <0.001 becomes 100.001. | What you're talking about is a **sentinel value**. It's a common technique. Strings in most languages after all use 0 as a sentinel end-of-string value. You can do that. You just need to find a number that makes sense and isn't used for anything else. Many string functions will return -1 to indicate what you're looking for isn't there.
0 might work because if the element isn't there there shouldn't even be a record. You also face the problem that it might be mistaken for actually meaning 0. -1 is another option. It doesn't have that same problem obviously.
Another column to indicate if the amount is measurable or not is also a viable option. The case for this one becomes stronger if you need to store different categories of trace elements (eg <1%, <0.1%, <0.01%, etc). Storing the negative of those numbers seems a bit hacky to me. | how to store an approximate number? (number is too small to be measured) | [
"",
"sql",
"variables",
"types",
""
] |
I'm a 2nd year ICT student. I never did PHP before this year and our instructor gave us the basics and at the end of the semester, gave us a project that would combine what we learned in his course and the databases course. We were to use the classic AMP setup on windows.
Now, our instructor told us to make a profile-site, based on how we made smaller ones before in class.
I don't see the point behind the somewhat weird method of entering the user into the database.
First, we do some PHP formchecking to make sure the entered data is safe and somewhat realistic(for instance, zip-codes over here are 4 numbers, never more and no letters or other symbols).
When everything checks out fine, we do the following:
```
$sql = new SqlObject(); //from SqlObject.class.php
$newUser = new User(login,passw,mail,...,...,...); //from User.class.php
$sql->addUser($newUser);
```
The SqlObject class is a class that contains all the SQL commands we need update, insert and generally alter data in the database. We never write SQL in our *normal* pages. But that's not what I'm confused about. It's the User.class.php file.
This file contains only a constructor and exactly the same amount of fields as needs to be entered into the database. For instance:
```
<?php
class User {
// members
var $id;
var $name;
var $password;
// constructor
function User($id=-1,$name='',$password='') {
$this->id = $id;
$this->name = $name;
$this->password = $password;
}
}
?>
```
That's it. The SqlObject.class.php file requires the User.class.php file on the first line.
The function `addUser($user)` in the SqlObject.class.php file looks like this:
```
function addUser($user) {
$insQuery = 'INSERT INTO users(name,password)';
$insQuery.= " VALUES ('".$user->name."', '".$user->password."')";
@mysql_query($insQuery) or showError("user insert failed");
}
```
Why make such a detour via the User.class.php file? Security reason of some kind?
I'll repeat: It's my first year using PHP and I'm still a student.
EDIT: People are complaining that there is no checks on SQL injection before inserting the data.
At the beginning of this post, I mentioned "formchecking".
The `register.php` file does all the escaping and checking of input. This includes several Regex tests, mysql\_real\_escape\_string() and some simpler tests.
Once all tests are passed and all input is escaped, only then will this happen:
```
$sql = new SqlObject(); //from SqlObject.class.php
$newUser = new User(login,passw,mail,...,...,...); //from User.class.php
$sql->addUser($newUser);
```
That code is never executed if the input doesn't receive the treatment that I see some people wanting to give it inside the SqlObject.class.php file.
EDIT2: as promised, blog [posted](http://webdevhobo.blogspot.com/2009/08/prepared-statements-in-php.html) | So, you're asking why not just pass the user and password in directly
```
function addUser($name='',$password='') { etc
```
My guess is that the code you show is an example of future-proofing, the idea being that the User class might do something a lot more detailed in the future, or get the credentials from some other source, rather than having name and password passed to its constructor.
It's an idea of separation of concerns, some bit if code is responsible for assembling the suer data, the addUer function merely uses the stuff it needs. In large programs it really helps to have these kinds of organisation - on the surface it might appear to be adding complexity but when you start to think like this it enables you limit the number of pieces you need to keep in your head. Also you might imagine breaking up the overall programming task so one person looks at the User class, another does the addUser. They can work independently. Silly in this tiny case, but in the real world very beneficial. | First of all, the addUser() method is awful, allows sql injections because it doesn't use prepared statements nor escapes the contents. It should read something like
```
function addUser($user) {
$insQuery = 'INSERT INTO users(name,password)';
$insQuery.= " VALUES ('".mysql_real_escape_string($user->name)."',";
$insQuery.= " '".mysql_real_escape_string($user->password)."')";
@mysql_query($insQuery) or showError("user insert failed");
}
```
This is awful because it teaches you bad practices, your teacher should teach you about SQL injections from day one, and not simplify them just for academic sake.
That aside, the idea is to future proof the code, using abstractions.
Abstractions allow you to think in a higher level. At this current level the User class might seem overkill, because it acts only as a storage facility, but it helps you think in term of domain instances instead of SQL sentences which then will help you make modifications shall such a need arise.
These abstractions also create a single place to complexify the code without having the changes spread all over, for example if you'd then need something else about a user you need only change the User class, for example by adding a, say, printUser() method or whatever.
```
function printUser() {
return "Mr. ".$this->name;
}
```
But this being an easy and artificial academic example, it might not make much sense. You'd need a bigger scenario to really see the benefit of abstractions.
About your edits:
I'm glad that you are told about SQL injections, even if not in the right place :)
The proper place to do the escaping for SQL injection is not in a previous 'formchecking' step, but to do it when sending the data to the SQL server. That 'formchecking' is the proper place to validate as you say, length of zipcodes, or empty fields and so on, but not to escape the strings to be SQL safe.
A simple example should show why:
```
$name = formcheck("John O'Donnell"); //Where you do all your checking step,
//including mysql_real_escape_string
$user = new User($name,"gandalf");
```
But,
```
mysql_real_escape_string("John O'Donnell") = "John O\'Donnell";
```
Now you use your User instance to display the name on the screen:
```
echo "Welcome ".$user->printUser();
```
and you get:
```
Welcome Mr. John O\'Donell
``` | Don't immediately see the point behind this (php, school) | [
"",
"php",
"mysql",
""
] |
I need to get three objects out of a function, my instinct is to create a new type to return the three refs. Or if the refs were the same type I could use an array. However pass-by-ref is easier:
```
private void Mutate_AddNode_GetGenes(ref NeuronGene newNeuronGene, ref ConnectionGene newConnectionGene1, ref ConnectionGene newConnectionGene2)
{
}
```
There's obviously nothing wrong with this but I hesitate to use this approach, mostly I think for reasons of aesthetics and psycholgical bias. Are there actually any good reasons to use one of these approaches over the others? Perhaps a performance issue with creating extra wrapper objects or pushing parameters onto the stack. Note that in my particular case this is CPU intensive code. CPU cycles matter.
Is there a more elegant C#2 of C#3 approach?
Thanks. | For almost all computing problems, you will not notice the CPU difference. Since your sample code has the word "Gene" in it, you may actually fall into the rare category of code that would notice.
Creating and destroying objects just to wrap other objects would cost a bit of performance (they need to be created and garbage collected after all).
Aesthetically I would not create an object just to group unrelated objects, but if they logically belong together it is perfectly fine to define a containing object. | If you're worrying about the performance of a wrapping type (which is a lot cleaner, IMHO), you should use a struct. Current 32-bits implementations of .NET (and the upcomming 64-bits 4.0) support inlining / optimizing away of structs in many cases, so you'd probably see no performance difference whatsoever between a struct and `ref` arguments. | Long lists of pass-by-ref parameters versus wrapper types | [
"",
"c#",
".net",
"pass-by-reference",
""
] |
I'm writing a function which generates all paths in a tree as xpath statements and storing them in a bag below is a naive (sorry this is long) and below that is my attempt to optimize it:
```
/**
* Create the structural fingerprint of a tree. Defined as the multiset of
* all paths and their multiplicities
*/
protected Multiset<String> createSF(AbstractTree<String> t,
List<AbstractTree<String>> allSiblings) {
/*
* difference between unordered and ordered trees is that the
* next-sibling axis must also be used
*
* this means that each node's children are liable to be generated more
* than once and so are memo-ised and reused
*/
Multiset<String> res = new Multiset<String>();
// so, we return a set containing:
// 1. the node name itself, prepended by root symbol
res.add("/" + t.getNodeName());
List<AbstractTree<String>> children = t.getChildren();
// all of the childrens' sets prepended by this one
if (children != null) {
for (AbstractTree<String> child : children) {
Multiset<String> sub = createSF(child, children);
for (String nextOne : sub) {
if (nextOne.indexOf("//") == 0) {
res.add(nextOne);
} else {
res.add("/" + nextOne);
res.add("/" + t.getNodeName() + nextOne);
}
}
}
}
// 2. all of the following siblings' sets, prepended by this one
if (allSiblings != null) {
// node is neither original root nor leaf
// first, find current node
int currentNodePos = 0;
int ptrPos = 0;
for (AbstractTree<String> node : allSiblings) {
if (node == t) {
currentNodePos = ptrPos;
}
ptrPos++;
}
// 3. then add all paths deriving from (all) following siblings
for (int i = currentNodePos + 1; i < allSiblings.size(); i++) {
AbstractTree<String> sibling = allSiblings.get(i);
Multiset<String> sub = createSF(sibling, allSiblings);
for (String nextOne : sub) {
if (nextOne.indexOf("//") == 0) {
res.add(nextOne);
} else {
res.add("/" + nextOne);
res.add("/" + t.getNodeName() + nextOne);
}
}
}
}
return res;
}
```
And now the optimization which is (currently) in a subclass:
```
private Map<AbstractTree<String>, Multiset<String>> lookupTable = new HashMap<AbstractTree<String>, Multiset<String>>();
public Multiset<String> createSF(AbstractTree<String> t,
List<AbstractTree<String>> allSiblings) {
Multiset<String> lookup = lookupTable.get(t);
if (lookup != null) {
return lookup;
} else {
Multiset<String> res = super.createSF(t, allSiblings);
lookupTable.put(t, res);
return res;
}
}
```
My trouble is that the optimized version runs out of heap space (the vm args are set at -Xms2g -Xmx2g) and is very slow on moderately large input. Can anyone see a way to improve on this? | Your code eats RAM exponentially. So one layer more means `children.size()` times more RAM.
Try to use a generator instead of materializing the results: Implement a Multiset which does not calculate the results beforehand but iterates through the tree structure as you call `next()` on the set's iterator. | Run the code through a profiler. That's the only way to get real facts about the code. Everything else is just guesswork. | Slow implementation and runs out of heap space (even when vm args are set to 2g) | [
"",
"java",
"optimization",
"tree",
"traversal",
""
] |
Hope someone can help with this. I've been up and down the web and through this site looking for an answer, but still can't get the Autocomplete AJAX control to work. I've gone from trying to include it in an existing site to stripping it right back to a very basic form and it's still not functioning. I'm having a little more luck using Page Methods rather than a local webservice, so here is my code
```
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="droptest.aspx.cs" Inherits="droptest" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:ScriptManager ID="ScriptManager1" EnablePageMethods="true" runat="server">
</asp:ScriptManager>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
MinimumPrefixLength="1" ServiceMethod="getResults"
TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Services;
using System.Web.Services;
public partial class droptest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public string[] getResults(string prefixText, int count)
{
string[] test = new string[5] { "One", "Two", "Three", "Four", "Five" };
return test;
}
}
```
Tried to keep things as simple as possible, but all I get is either the autocomplete dropdown with the source of the page (starting with the `<! doctype...`) letter by letter, or in IE7 it just says "UNDEFINED" all the way down the list.
I'm using Visual Web Developer 2008 at the moment, this is running on Localhost. I think I've exhausted all the "Try this..." options I can find, everything from adding in [ScriptMethod] to changing things in Web.Config.
Is there anything obviously wrong with this code?
Only other thing that *may* be having an effect is in Global.asax I do a Context.RewritePath to rewrite URLs - does this have any effect on AJAX?
Thanks for any help you can give. | Right, something I've added in from these suggestions has worked!!! Still have a problem though, it works in a standalone project but adding it back into the existing project and it's not working again. So thanks for the help so far, I have a working example, just have to figure out what is killing it inside the other project now. | You also need to include your page name as the servicePath, I think.
```
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server"
MinimumPrefixLength="1" ServiceMethod="getResults" ServicePath="droptest.aspx"
TargetControlID="TextBox1">
</cc1:AutoCompleteExtender>
``` | Tearing my hair out - ASP.Net AJAX AutoComplete not working | [
"",
"c#",
"asp.net-ajax",
"autocomplete",
""
] |
How can I implement Comet / Server push in Google App Engine in Python? | We just announced the Channel API to do comet push with App Engine apps: <http://googleappengine.blogspot.com/2010/05/app-engine-at-google-io-2010.html>
If you're at Google IO, I'll be talking about this at 1pm tomorrow (on the APIs track): <http://code.google.com/events/io/2010/sessions/building-real-time-apps-app-engine-feed-api.html>
Here's the YouTube video of the session: <http://www.youtube.com/watch?v=oMXe-xK0BWA>
Hopefully last update! This is now released: [code.google.com/appengine/docs/python/channel](http://code.google.com/appengine/docs/python/channel) | At this time, I would rule out doing Comet in App Engine (any language). Comet is based on long-lived HTTP connections, and App Engine will time out any single connection in about 30 seconds or so at most; it's hard to conceive of a worse match! | Implement Comet / Server push in Google App Engine in Python | [
"",
"python",
"google-app-engine",
"comet",
"server-push",
"channel-api",
""
] |
Java's e.printStackTrace() doesn't print all the details of the inner exception's stack trace.
Is there a ready way to generate the complete stack trace in string form? (besides formatting it myself)
**Edit**
I just found out what printStackTrace() does - apparently the stack frames it filters out are exactly the ones common to the inner exception and the outer one. So in fact it is rather what I want, and not the 'full' stack trace. | I ended up rolling my own (I took the implementation of Throwable.printStackTrace() and tweaked it a bit):
```
public static String joinStackTrace(Throwable e) {
StringWriter writer = null;
try {
writer = new StringWriter();
joinStackTrace(e, writer);
return writer.toString();
}
finally {
if (writer != null)
try {
writer.close();
} catch (IOException e1) {
// ignore
}
}
}
public static void joinStackTrace(Throwable e, StringWriter writer) {
PrintWriter printer = null;
try {
printer = new PrintWriter(writer);
while (e != null) {
printer.println(e);
StackTraceElement[] trace = e.getStackTrace();
for (int i = 0; i < trace.length; i++)
printer.println("\tat " + trace[i]);
e = e.getCause();
if (e != null)
printer.println("Caused by:\r\n");
}
}
finally {
if (printer != null)
printer.close();
}
}
``` | I suggest that you use the [ExceptionUtils](http://commons.apache.org/lang/api-release/org/apache/commons/lang3/exception/ExceptionUtils.html) class from Apache Commons lang, which provides useful method for that. | Getting full string stack trace including inner exception | [
"",
"java",
"stack-trace",
""
] |
I have a list of zip-codes that I need to search trough using jQuery.
I have the zip-codes in a CSV file like this:
```
2407;ELVERUM
2425;TRYSIL
2427;TRYSIL
2446;ENGERDAL
2448;ENGERDAL
```
The list is pretty big, over 4000 entries, zip-code and corresponding city.
What the fastest way to search trough the list in the browser?
JSON? If that's the case, how can I convert the list to JSON or another format if better?
```
{
"2407": "ELVERUM",
"2425": "TRYSIL"
}
```
Can someone show me the mest way to do this?
**Update**
Would it be possible/faster to search the loaded CSV file with just Regex?
**Update2**
I'm looking for an exact match, and it's only going to search when it has 4 numbers.
**Update3**
Here is my code:
```
$('#postnummer').keyup(function(e) {
if($(this).val().length == 4) {
// Code to search the JSON for an exact match.
}
});
$.getJSON("data.json",function(data){
});
```
Can anyone show me using this code? | This is a web page that will convert your CSV to JSON from a URL. You can use it locally on your computer. Uses JQuery and the [CSV](http://js-tables.googlecode.com/) and [JSON](http://jquery-json.googlecode.com/files/jquery.json-1.3.min.js) plug-ins.
Note: this script is a quick hack specific to the CSV given.
```
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script src="http://js-tables.googlecode.com/svn/trunk/jquery.csv.min.js"></script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-1.3.min.js"></script>
<script>
jQuery(function($){
$('#conv').click(function(){
$.get($('#myurl').val(), function(data){
var csvobj = {};
var csvray = $.csv(';')(data);
$(csvray).each(function(){
csvobj[this[0]] = this[1];
});
$('#jsondata').val( "areacodes=" + $.toJSON(csvobj) );
});
});
});
</script>
Url to CSV: <input type="text" id="myurl" value="tilbud5.csv" />
<input type="button" id="conv" value="convert url to json" />
<br/>
<textarea id="jsondata" rows="1000" cols="100"></textarea>
```
Using the JSON data, this is just an example:
```
$('#postnummer').keyup(function(e) {
if($(this).val().length == 4) {
alert(areacodes[$(this).val()]);
}
});
$.getJSON("data.json?callback=?");
``` | At 4,000 entries, you should just parse it as JSON using the form you suggested:
```
{
"2407": "ELVERUM",
"2425": "TRYSIL"
}
```
If you are planning to search by looking for the exact match of a zipcode, this will also give you the fastest search time. If you do something where the user types "24" and you need to find all zipcodes that begin with "24", then you will need something a little more advanced.
I'm not sure what mechanisms jQuery provides for parsing JSON. The way it is typically done, is to use eval:
```
var zips = eval("(" + data + ")");
```
Or on modern browsers, you can use the faster and safer JSON library.
```
var zips = JSON.parse(data);
``` | Search zip-codes fast with jQuery | [
"",
"javascript",
"jquery",
"json",
"csv",
""
] |
How do I implement no-op macro in C++?
```
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) what goes here?
#else
#define conditional_noop(x) std::cout << (x)
#endif
int main() {
conditional_noop(123);
}
```
I want this to do nothing when NOOP is defined and print "123", when NOOP is not defined. | As mentioned before - nothing.
Also, there is a misprint in your code.
it should be **#else** not **#elif**. if it is **#elif** it is to be followed by the new condition
```
#include <iostream>
#ifdef NOOP
#define conditional_noop(x) do {} while(0)
#else
#define conditional_noop(x) std::cout << (x)
#endif
```
Have fun coding!
EDIT: added the [do] construct for robustness as suggested in another answer. | While leaving it blank is the obvious option, I'd go with
```
#define conditional_noop(x) do {} while(0)
```
This trick is obviously no-op, but forces you to write a semicolon after `conditional_noop(123)`. | How do I implement no-op macro (or template) in C++? | [
"",
"c++",
"c",
"templates",
"macros",
""
] |
A sort of follow up/related question to [this](https://stackoverflow.com/questions/27857/c-c-source-code-visualization/).
I'm trying to get a grip on a large code base that has hundreds and hundreds of classes and a large inheritance hierarchy. I want to be able to see the "main veins" of the inheritance hierarchy at a glance - not all the "peripheral" classes that only do some very specific / specialized thing. Visual Studio's "View Class Diagram" makes something that looks like a train and its sprawled horizontally across the screen and isn't very organized. You can't grok it easily.
I've just tried doxygen and graphviz but the results are .. somewhat similar to Visual Studio. I'm getting sweet looking call graphs but again *too much detail* for what I'm trying to get.
I need a quick way to generate the inheritance hierarchy, in some kind of *collapsible* view. | Why not just do it manually, it is a great learning experience when starting to work with a large code base. I usually just look at what class inherits from what, and what class contain what instances, references or pointers to other classes. Have a piece of paper next to you and get drawing... | Instead of going into the full Class Designer tool, just use the "Class View" or the "Object Browser" in Visual Studio - they present fully collapsible class heirarchies. | C++ code visualization | [
"",
"c++",
"inheritance",
"visualization",
""
] |
I have a function and its contents as a string.
```
var funcStr = "function() { alert('hello'); }";
```
Now, I do an eval() to actually get that function in a variable.
```
var func = eval(funcStr);
```
If I remember correctly, in Chrome and Opera, simply calling
```
func();
```
invoked that function and the alert was displayed.
But, in other browsers it wasn't the case. nothing happened.
I don't want an arguement about which is the correct method, but how can I do this? I want to be able to call variable(); to execute the function stored in that variable. | How about this?
```
var func = new Function('alert("hello");');
```
To add arguments to the function:
```
var func = new Function('what', 'alert("hello " + what);');
func('world'); // hello world
```
Do note that functions are objects and can be assigned to any variable as they are:
```
var func = function () { alert('hello'); };
var otherFunc = func;
func = 'funky!';
function executeSomething(something) {
something();
}
executeSomething(otherFunc); // Alerts 'hello'
``` | IE cannot `eval` functions (Presumably for security reasons).
The best workaround is to put the function in an array, like this:
```
var func = eval('[' + funcStr + ']')[0];
``` | executing anonymous functions created using JavaScript eval() | [
"",
"javascript",
"eval",
""
] |
So yea, i'm planning on selling a web application i've made. I know i could never stop people from copying files and sharing them, but how would i go about placing pieces of code that could alert me of usage?
I know someone motivated enough will eventually crack it.. i'm just interested in the possible solutions(using php, especially).
Thanks guys! | What are you talking about is analogous of a trojan into commercial software. Why would anybody pay for software that sends monitoring beacons out to the web?
Instead you could simply sell the software with a licensing scheme and provide services that require valid licenses. That way people who steal your software cannot obtain security patches, support, or upgrades, and other goodies. If you do not have a business ready to support the software you are about to sell then you may not be ready to sell your software at this time. | Try [Zend Guard](http://www.zend.com/en/products/guard/) | How does one protect a web application sold on a per license basis from piracy? | [
"",
"php",
"web-applications",
"piracy",
""
] |
How do I add a list of values to an existing set? | You can't add a list to a set because lists are mutable, meaning that you can change the contents of the list after adding it to the set.
You can however add tuples to the set, because you cannot change the contents of a tuple:
```
>>> a.add(('f', 'g'))
>>> print a
set(['a', 'c', 'b', 'e', 'd', ('f', 'g')])
```
---
**Edit**: some explanation: The documentation defines a `set` as *an unordered collection of distinct hashable objects.* The objects have to be hashable so that finding, adding and removing elements can be done faster than looking at each individual element every time you perform these operations. The specific algorithms used are explained in the [Wikipedia article](http://en.wikipedia.org/wiki/Hash_tree). Pythons hashing algorithms are explained on [effbot.org](https://web.archive.org/web/20200704001207/http://effbot.org/zone/python-hash.htm) and pythons `__hash__` function in the [python reference](https://docs.python.org/3/reference/datamodel.html#object.__hash__).
Some facts:
* **Set elements** as well as **dictionary keys** have to be hashable
* Some unhashable datatypes:
* `list`: use `tuple` instead
* `set`: use `frozenset` instead
* `dict`: has no official counterpart, but there are some
[recipes](https://stackoverflow.com/questions/1151658/python-hashable-dicts)
* Object instances are hashable by default with each instance having a unique hash. You can override this behavior as explained in the python reference. | #### Adding the contents of a list
Use [`set.update()`](https://docs.python.org/3/library/stdtypes.html#frozenset.update) or the `|=` operator:
```
>>> a = set('abc')
>>> a
{'a', 'b', 'c'}
>>> xs = ['d', 'e']
>>> a.update(xs)
>>> a
{'e', 'b', 'c', 'd', 'a'}
>>> xs = ['f', 'g']
>>> a |= set(xs)
>>> a
{'e', 'b', 'f', 'c', 'd', 'g', 'a'}
```
---
#### Adding the list itself
It is not possible to directly add the list itself to the set, since set elements must be [hashable](https://stackoverflow.com/questions/14535730/what-do-you-mean-by-hashable-in-python).
Instead, one may convert the list to a tuple first:
```
>>> a = {('a', 'b', 'c')}
>>> xs = ['d', 'e']
>>> a.add(tuple(xs))
>>> a
{('a', 'b', 'c'), ('d', 'e')}
``` | Add list to set | [
"",
"python",
"list",
"set",
""
] |
I am trying to utilize the AttachmentCollection Class in C# and when I try to create a new instance of it it gives me an error saying "Error 32 The type 'System.Net.Mail.AttachmentCollection' has no constructors defined"....
Here is what I was trying, how to a create a new instance of this if there are no constructors defined ?
```
AttachmentCollection attachmentCollection = new AttachmentCollection();
```
Thanks for your help! | Some types aren't designed to be instantiated.
They might be Abstract, meaning that you are expected to extend the class and fill in some of its functionality.
They might also require some extensive work to get them created correctly. Those types often expose public static methods or have factories which you can use to instantiate them.
The docs state that "Instances of the AttachmentCollection class are returned by the MailMessage.AlternateViews and MailMessage.Attachments properties." Seems like the designers didn't want you to create this collection; its purpose is to be used only with the MailMessage class.
Let the MailMessage class handle its AttachmentCollections for you. Create an instance of MailMessage and then fill in AlternateViews and Attachments, rather than create the collection, fill it in and then assign it to the properties.
One last thing, most public properties that are collections don't have setters. Its considered a bad design to allow users of your types to be able to set or even null out your public collection properties. | You can't create a new instance of it without using reflection.
Instead, you can create a new MailMessage "message = new MailMessage(...)" (which creates it's own AttachmentCollection), and call "message.Attatchments.Add( ... )" to add an attachment.
The constructor for AttachmentCollection is internal, it's a type designed to only be used from MailMessage.
See the msdn docs for [AttachmentCollection](http://msdn.microsoft.com/en-us/library/system.net.mail.attachmentcollection.aspx). | AttachmentCollection attachmentCollection in C# | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
""
] |
I know how to select *one* random item from an array, but how about *ten* random items from an array of, say, twenty items? (In PHP.)
What makes it a little more complicated is that each item actually has two parts: a filename, and a description. Basically, it's for a webpage that will display ten random images each time you reload. The actual format of this data doesn't really matter, although it's simple enough that I'd prefer to contain it in flat-text or even hard code it rather than set up a database. (It's also not meant to change often.) | You can select one or more random items from an array using [`array_rand()`](https://www.php.net/manual/en/function.array-rand.php) function. | You could [`shuffle`](http://docs.php.net/shuffle) the array and then pick the first ten elements with [`array_slice`](http://docs.php.net/array_slice):
```
shuffle($array);
$tenRandomElements = array_slice($array, 0, 10);
``` | How do I select 10 random things from a list in PHP? | [
"",
"php",
"arrays",
"random",
""
] |
I have a class that stores a list of dictionary entries. I want bind that to a datasource for gridview from codebehind.
Code for dictionary type of , representing ErrorMessage and failed field.
```
public partial class FailedFields
{
private Dictionary<string, string> Code_Error = new Dictionary<string, string>();
public void AddFailedField(string field, string message)
{
Code_Error.Add(field, message);
}
public Dictionary<string, string> GetFailedFields()
{
return Code_Error;
}
}
```
Code for List of Dictionary entries.
```
public partial class ErrorFieldsList
{
private static List<Order.FailedFields> ErrorList = new List<Slab.FailedFields>();
public void AddErrorField(Order.FailedFields errs)
{
ErrorList.Add(errs);
}
public List<Order.FailedFields> GetErrorMessages()
{
return ErrorList;
}
}
```
Running in Visual Studio debug mode, i can see the list has the error list, but i cannot get it to display in the gridview. Bellow is one of the many ways (the one that makes most sense) i tried to set the list as a datasource.
```
ErrorBoxGridView.DataSource = FailedRecords.GetErrorMessages(). ;
ErrorBoxGridView.DataBind();
```
Any idea where i am going wrong ?
Also, i don't want to specify a datasource in the aspx page because i only want to display this when the error occurs.
*If interested why i am doing this to store error messages, have a look at this:[link 1](https://stackoverflow.com/questions/1284135/errorproviderfrom-windows-forms-for-asp-net-linq-to-sql)*
**Solved Here** [Related Question](https://stackoverflow.com/questions/1303866/datasource-from-cascading-listclassa-containing-listclassb)
I will document a complete project when i finish on the wiki. | This can not be done I think. What I'd do is:
1. Instead of using `Dictionary<string, string>` define a class that contains two public properties for field and message
2. Create an object data source for that class (using Visual Studios "Data Sources" window)
3. Have `GetErrorMessages()` return `List<ErrorClass>` instead of `Dictionary`
4. Assign that list to the binding source.
**EDIT**
This is to clarify things according to the latest comments. What you need is *one* class that contains the information for *one* error. For example:
```
public class ErrorInfo
{
public string Field { get { ... } }
public string Message { get { ... } }
}
```
After that you place a `BindingSource` on your form and (in code) set its `DataSource` property to a *list* of error message classes. For example:
```
private List<ErrorInfo> errorList = new List<ErrorInfo>();
errorList.Add(new ErrorInfo() { ... });
errorList.Add(new ErrorInfo() { ... });
errorList.Add(new ErrorInfo() { ... });
bindingSource.DataSource = errorList;
```
The data grid view is bound to the `BindingSource`. You should see data now. You can manually create columns and set them to the respective property names of your `ErrorInfo` class as well, but then you'd have to set `dataGridView.AutoCreateColumns` to `false` somewhere in your code. | [Databind List of Dictionnary into a GridView](https://stackoverflow.com/questions/5713492/databind-list-of-dictionnary-into-a-gridview)
```
List<Dictionary<string,string>> resultSet = SOME List of Dictionaries...
DataGridView.DataSource = resultSet.Select(x => new {
fieldOne = x["key1"], fieldTwo = x["key2"]
}).ToList();
DataGridView.DataBind();
```
Now u can Bind fieldOne and fieldTwo in the DataGridView element...
Kindly check the Link for the precise ans...
Thanks | how to bind datasource to List<Dictionary<string, string>>? | [
"",
"c#",
"list",
"dictionary",
"datasource",
""
] |
I need to handle tens of Gigabytes data in one binary file. Each record in the data file is variable length.
So the file is like:
```
<len1><data1><len2><data2>..........<lenN><dataN>
```
The data contains integer, pointer, double value and so on.
I found python can not even handle this situation. There is no problem if I read the whole file in memory. It's fast. But it seems the `struct` package is not good at performance. It almost stuck on unpack the bytes.
Any help is appreciated.
Thanks. | `struct` and `array`, which other answers recommend, are fine for the details of the implementation, and might be all you need if your needs are always to sequentially read all of the file or a prefix of it. Other options include [buffer](http://docs.python.org/library/functions.html?highlight=buffer#buffer), [mmap](http://docs.python.org/library/mmap.html), even [ctypes](http://docs.python.org/library/ctypes.html), depending on many details you don't mention regarding your exact needs. Maybe a little specialized Cython-coded helper can offer all the extra performance you need, if no suitable and accessible library (in C, C++, Fortran, ...) already exists that can be interfaced for the purpose of handling this humongous file as you need to.
But clearly there are peculiar issues here -- how can a data file contain **pointers**, for example, which are intrinsically a concept related to addressing *memory*? Are they maybe "offsets" instead, and, if so, how exactly are they based and coded? Are your needs at all more advanced than simply sequential reading (e.g., random access), and if so, can you do a first "indexing" pass to get all the offsets from start of file to start of record into a more usable, compact, handily-formatted auxiliary file? (*That* binary file of offsets would be a natural for `array` -- unless the offsets need to be longer than `array` supports on your machine!). What is the distribution of record lengths and compositions and number of records to make up the "tens of gigabytes"? Etc, etc.
You have a very large scale problem (and no doubt very large scale hardware to support it, since you mention that you can easily read all of the file into memory that means a 64bit box with many tens of GB of RAM -- wow!), so it's well worth the detailed care to optimize the handling thereof -- but we can't help much with such detailed care unless we know enough detail to do so!-). | For help with parsing the file without reading it into memory you can use the [bitstring](http://python-bitstring.googlecode.com) module.
Internally this is using the struct module and a bytearray, but an immutable Bits object can be initialised with a filename so it won't read it all into memory.
For example:
```
from bitstring import Bits
s = Bits(filename='your_file')
while s.bytepos != s.length:
# Read a byte and interpret as an unsigned integer
length = s.read('uint:8')
# Read 'length' bytes and convert to a Python string
data = s.read(length*8).bytes
# Now do whatever you want with the data
```
Of course you can parse the data however you want.
You can also use slice notation to read the file contents, although note that the indices will be in bits rather than bytes so for example `s[-800:]` would be the final 100 bytes. | Any efficient way to read datas from large binary file? | [
"",
"python",
"file",
"binary",
""
] |
A year ago I saw a beautiful simple code that gets a data table and saves it in an excel file.
The trick was to use the web library (something with http) and I'm almost sure it was a stream.
I find a lot of code with response but I can't make it work in a win-form environment.
There is also a cell by cell code - not interested -too slow.
I want to paste it as a range or something close.
Thanks | I believe this is the code you're looking for:
[DataTable to Excel](http://www.codeproject.com/KB/office/ExcelDataTable.aspx)
It uses an `HtmlTextWriter`. | There are many component libraries out there that will provide this kind of functionality.
However, you could probably, most simply output the data as a CSV file and the load that into Excel. | Save a datatable to excel sheet in vb.net winform application | [
"",
"c#",
"vb.net",
"winforms",
"excel",
"datatable",
""
] |
I want to hide the guts of my URL programmatically.
I know I can use:
```
Server.Transfer("url",boolean)
```
This is not what I want in this case. I would like to be able to manipulate the URL after I get the variables I need.
How would I do this in ASP.NET?
---
### Edit:
My URL:
```
URL.aspx?st=S&scannum=481854
```
I want to change it when the page loads to just be `URL.aspx?` but I need to first get the `st` and `scannum` values. | It's not possible to do what I want to do. I would want to change the appearance of my url in javascript without refreshing. If this was possible, hackers would rule the world. | Have you seen this article that covers [Url Rewriting in ASP.NET](http://msdn2.microsoft.com/en-us/library/ms972974.aspx)?
I recommend checking out [ASP.NET MVC](http://www.asp.net/mvc/) as well. MVC stands for Model View Controller. This framework will use a "controller" to route the end user to "views" that display your data (your "model"). MVC does all the routing for you based on the URL. | How can I rewrite my URL in ASP.NET? | [
"",
"c#",
".net",
"asp.net",
""
] |
```
$(document).onload()
```
it's internally implemented by window.onload event
then what about
```
$(document).ready()
```
what's the native javascript to implement it? | For Mozilla, Opera and webkit, jQuery binds the [DOMContentLoaded](https://developer.mozilla.org/en/Gecko-Specific_DOM_Events) event, for IE jQuery uses the [onreadystatechange](http://msdn.microsoft.com/en-us/library/ms536957%28VS.85%29.aspx) event.
Look the internal bindReady function on the [jQuery source code](https://github.com/jquery/jquery/blob/1.3.2/src/event.js#L620). | What do you mean?
.ready() is a function jQuery wrote to handle the inconsistent way that all the browsers may report 'load complete' for the given element.
.onload() may work in X browser but not Y. This is (part) of what jQuery is for - to solve this problem for you. | Is there a native Javascript implementation of jQuery's document.ready()? | [
"",
"javascript",
"jquery",
""
] |
Got it from php.net, but I am not sure is this how everybody destroy all sessions?
```
// Unset all Sessions
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time() -42000, '/');
}
session_destroy();
```
Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions?
Oh yeah, btw, what is that `session_name()`? All session name? e.g `$_SESSION['var1']`, `$_SESSION['var2']`, ... ?
I dont need to use `unset($_SESSION['var1']);` any more right?
Whats the different between using `session_destroy()` and `unset($_SESSION[])`? | You should first know what sessions are: You can consider sessions as a data container on the server side that’s associated with a random identifier, the session ID. That session ID needs to be provided by the client so that the server can load the data associated to that session ID (and thus to that session) into the `$_SESSION` variable. Everything in that `$_SESSION` variable is also called *session variables* of the current active session.
Now to your questions:
> Does the code will destroy all the sessions?? Is it the most common way? how do you guys destroy php sessions??
The provided code just deletes the session data of the current session. The `$_SESSION = array();` statement will simply reset the session variable `$_SESSION` so that a future access on the session variable `$_SESSION` will fail. But the session container itself is not deleted yet. That will be done by calling `session_destroy`.
See also [*Truly destroying a PHP Session?*](https://stackoverflow.com/questions/508959/truly-destroying-a-php-session)
> Oh yeah, btw, what is that session\_name()?? All session name? e.g $\_SESSION['var1'], $\_SESSION['var2']... ?
The [session\_name](http://docs.php.net/session_name) is just used to identify the session ID parameter passed in a cookie, the URL’s query or via a POST parameter. PHP’s default value is `PHPSESSID`. But you can change it to whatever you want to.
> I dont need to use unset($\_SESSION['var1']); any more right???
No. The initial `$_SESSION = array();` deletes all the session data.
> Whats the different between using session\_destroy and unset($\_SESSION[])??
[`session_destroy`](http://docs.php.net/session_destroy) will delete the whole session container while `unset` or resetting the `$_SESSION` variable will only delete the session data for the current runtime. | This only destroys the current users session, not all the other users session.
Try using the session\_save\_path() to find out where the session data is being stored, and then delete all the files there. | Is this a proper way to destroy all session data in php? | [
"",
"php",
"session",
""
] |
In my master page I have the line
```
<div class ="breadcrumbs" runat="server"><%= SitePath()%></div>
```
SitePath() involks a custom class that builds navigation elements based on the combination of the static sitemap and dynamically generated pages. It returns the html for a custom breadcrumb navigation element.
Here is the SitePath() code from my code behind
```
public string SitePath()
{
BreadCrumbNav breadNav = new BreadCrumbNav();
breadNav.divClass = ".dv";
breadNav.homeTitle = "ABC Home";
return breadNav.Build();
}
```
I'd like to be able to override this from my dynamic pages so I can add to the path. For Example...
```
public override string SitePath()
{
BreadCrumbNav breadNav = new BreadCrumbNav();
breadNav.divClass = ".dv";
breadNav.homeTitle = "ABC Home";
breadNav.AddPage("Cooking Equipment", "PathyGoodness/Cooking+Equipment.ASPX");
breadNav.AddPage("Toasters", "PathyGoodness/Cooking+Equipment/Toasters.ASPX");
return breadNav.Build();
}
```
Is there a way to bring the master page methods into scope so I can override them- or do I need to go about this in a different way? It feels like I'm missing something really obvious, but I seem to be stuck.
Thanks for your help! | Since the Master page is not actually inherited, but rather used as a template, this is not directly possible.
A few other approaches you could try:
Firstly, put this in a ContentPlaceholder and override it in the ASPX markup of your individual pages only where necessary.
A more complicated approach would be to create an interface for all your pages to inherit from that guarantees they have a SitePath() method. Call that method on the *page* instead, from the Master, and in those pages that do not "override" the behavior, simply call the Master. In others, add your specific implementation to that method, and voila! (I suppose you could also use an abstract BasePage-type class to call the Master from that method) | Generally im against putting page/context specific methods in the masterpage class. Why? Because, as Josh mentioned, Masterpages is just templates. You'll never inherit from a masterpage and you can't show a masterpage without also having access to a Page object. Therefor it makes more sense to put such methods in the Page class. | Overriding a master page function in ASP.net | [
"",
"c#",
"asp.net",
"master-pages",
""
] |
Say, I'd like to have a tool (or script?) taking project (or .h file) and building searchable tree of "includes" included into it (of included into of included into and so so on). Is there exist something like this? Should I write this by myself [of course I am :), but may be somebody had it already written or may be has an idea how to get it]? | Not entirely sure this is what you're after, but you can easily get a list of includes by generating the post-CPP-processed file from the base c file, and grepping out the file/line number comments, e.g., using gcc
```
gcc -E main.c {usual flags} | grep '#' | cut -d' ' -f3 | sort | uniq
```
where main.c is your base c file. | I know this is an old question, a slightly more useful output than the gcc/g++ -E output alone would also used the -H flag (instead or in addition to):
`g++ -H {my -I and other flags} -E -o /dev/null file.cpp`
here is a sample output, tree structure helps figure out who included what
as a bonus it also lists at the bottom which files may benefit from an include guard
```
. generated/gen-cpp/File.h
.. /usr/include/thrift/TProcessor.h
... /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/string
.... /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/x86_64-redhat-linux/bits/c++config.h
..... /usr/include/bits/wordsize.h
..... /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/x86_64-redhat-linux/bits/os_defines.h
...... /usr/include/features.h
....... /usr/include/sys/cdefs.h
........ /usr/include/bits/wordsize.h
....... /usr/include/gnu/stubs.h
........ /usr/include/bits/wordsize.h
........ /usr/include/gnu/stubs-64.h
..... /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/x86_64-redhat-linux/bits/cpu_defines.h
.... /usr/lib/gcc/x86_64-redhat-linux/4.4.6/../../../../include/c++/4.4.6/bits/stringfwd.h
...
``` | Do you know tool building tree of include files in project\file? | [
"",
"c++",
"scripting",
"include",
""
] |
Given this following sample code which clones a table row, sets some properties and then appends it to a table:
```
$("#FundTable").append(
objButton.parents("tr").clone()
.find(".RowTitle").text("Row " + nAddCount).end()
.find(".FundManagerSelect").attr("id", "FundManager" + nAddCount)
.change(function() { ChangeFundRow(); }).end()
.find(".FundNameSelect").attr("id", "FundName" + nAddCount).end()
);
```
Does anyone have any suggestions as to how this might be formatted to be easier on the eye? Is there any accepted convention for doing this?
It would be useful to have a set of rules that can be followed, and that can be incorporated into a set of standards. | I would refactor to this. I find more than 3 chained methods uneasy on the eye
```
var $clonedRow = objButton.parents("tr").clone();
$clonedRow.find(".RowTitle")
.text("Row " + nAddCount);
$clonedRow.find(".FundManagerSelect")
.attr("id", "FundManager" + nAddCount)
.change( ChangeFundRow );
$clonedRow.find(".FundNameSelect")
.attr("id", "FundName" + nAddCount);
$clonedRow.appendTo("#FundTable");
``` | I indent as if it were bracketed:
```
$("#FundTable")
.append(objButton.parents("tr")
.clone()
.find(".RowTitle")
.text("Row " + nAddCount)
.end()
.find(".FundManagerSelect")
.attr("id", "FundManager" + nAddCount)
.change(function() {
ChangeFundRow(); // you were missing a semicolon here, btw
})
.end()
.find(".FundNameSelect")
.attr("id", "FundName" + nAddCount)
.end()
)
;
``` | Is there a preferred way of formatting jQuery chains to make them more readable? | [
"",
"javascript",
"jquery",
"chaining",
""
] |
We have been able to create a web site. We did this using the information in this link:
<https://msdn.microsoft.com/en-us/library/ms525598.aspx>
However, we would like to use a port number other that port 80. How do we do this?
We are using IIS 6 | If you're using IIS 7, there is a new managed API called [Microsoft.Web.Administration](http://blogs.msdn.com/carlosag/archive/2006/04/17/MicrosoftWebAdministration.aspx)
An example from the above blog post:
```
ServerManager iisManager = new ServerManager();
iisManager.Sites.Add("NewSite", "http", "*:8080:", "d:\\MySite");
iisManager.CommitChanges();
```
If you're using IIS 6 and want to do this, it's more complex unfortunately.
You will have to create a web service on every server, a web service that handles the creation of a website because direct user impersonation over the network won't work properly (If I recall this correctly).
You will have to use Interop Services and do something similar to this (This example uses two objects, server and site, which are instances of custom classes that store a server's and site's configuration):
```
string metabasePath = "IIS://" + server.ComputerName + "/W3SVC";
DirectoryEntry w3svc = new DirectoryEntry(metabasePath, server.Username, server.Password);
string serverBindings = ":80:" + site.HostName;
string homeDirectory = server.WWWRootPath + "\\" + site.FolderName;
object[] newSite = new object[] { site.Name, new object[] { serverBindings }, homeDirectory };
object websiteId = (object)w3svc.Invoke("CreateNewSite", newSite);
// Returns the Website ID from the Metabase
int id = (int)websiteId;
```
See more [here](http://msdn.microsoft.com/en-us/library/ms524569.aspx) | Heres the solution.
[Blog article : How to add new website in IIS 7](http://startcoding.in/2012/01/24/how-to-add-new-website-into-iis-programatically-using-asp-net-c/)
On Button click :
```
try
{
ServerManager serverMgr = new ServerManager();
string strWebsitename = txtwebsitename.Text; // abc
string strApplicationPool = "DefaultAppPool"; // set your deafultpool :4.0 in IIS
string strhostname = txthostname.Text; //abc.com
string stripaddress = txtipaddress.Text;// ip address
string bindinginfo = stripaddress + ":80:" + strhostname;
//check if website name already exists in IIS
Boolean bWebsite = IsWebsiteExists(strWebsitename);
if (!bWebsite)
{
Site mySite = serverMgr.Sites.Add(strWebsitename.ToString(), "http", bindinginfo, "C:\\inetpub\\wwwroot\\yourWebsite");
mySite.ApplicationDefaults.ApplicationPoolName = strApplicationPool;
mySite.TraceFailedRequestsLogging.Enabled = true;
mySite.TraceFailedRequestsLogging.Directory = "C:\\inetpub\\customfolder\\site";
serverMgr.CommitChanges();
lblmsg.Text = "New website " + strWebsitename + " added sucessfully";
}
else
{
lblmsg.Text = "Name should be unique, " + strWebsitename + " is already exists. ";
}
}
catch (Exception ae)
{
Response.Redirect(ae.Message);
}
```
---
Looping over sites whether name already exists
```
public bool IsWebsiteExists(string strWebsitename)
{
Boolean flagset = false;
SiteCollection sitecollection = serverMgr.Sites;
foreach (Site site in sitecollection)
{
if (site.Name == strWebsitename.ToString())
{
flagset = true;
break;
}
else
{
flagset = false;
}
}
return flagset;
}
``` | Programmatically create a web site in IIS using C# and set port number | [
"",
"c#",
"iis",
"iis-6",
"port",
""
] |
I have a Windows service which I want to periodically execute an external program. I'm currently doing this the usual way
```
Process program = Process.Start(@"C:\mpewatch\db_parameters\DBParameters.exe");
```
This doesn't seem to be working. I'm executing this from a separate thread which is started in my service's `OnStart` handler. Is there any conceptual problem with this? Is it not possible to execute external programs from a service like this? | Your question didn't indicate the operating system.
On Windows XP, you can configure your Windows service to interact with the desktop by opening the service control panel, double-clicking your service, selecting the Log On tab, configuring the service to run as local system, and checking the checkbox. It's pretty straightforward. You might try testing with something like Notepad.exe just to see if you can get it working.
On Vista (and presumably Windows 7), however, you may be out of luck. I have read that the ability for Windows services to interact with the desktop has been removed in Vista. I forget what the terminology is, but basically services will run in "shell 0," whereas users will occupy "shell 1". User applications will be able to communicate with services and vice versa using technology like WCF, but services will not be able to communicate directly with the desktop. For example, any error boxes that pop up will have to be dealt with by swapping to "shell 0." Again, this is based on something I read a few months ago, and I haven't gone looking at it again. For me, I've structured my Windows service to be configured using WCF via a front-end app.
I'm sorry I don't have a link for you, but if your service will eventually have to migrate to a newer OS (or you are already there), this is something to check on. | You *can* execute external programs from a service, but there are security issues. For example, your service may be running under an account which does not have read access to the folder where the external program resides, even if your interactive account does have that access.
For test purposes, try to configure the service to run under your interactive account. If the program is invoked as expected, then the problem with the original account is that it does not have sufficient privileges to run the program. | Unable to execute a program from a service | [
"",
"c#",
"windows-services",
"external-process",
""
] |
I'm trying to create a web user interface for a Java application. The user interface is going to be very simple, consisting of a single page with a form for users to pose their queries, and a results page -- sort of like Google's search engine or Ask.com.
I'm quite familiar with the base API of Java, but I don't have much experience in using Java for Web environments (though I've used ASP.NET), so I'm looking for some advice:
* *What **web application server** should I use?* Note that my interface is very light, and I just want something that is fast, easy to start/reset/stop and (re)deploy my application. Also, I need it to work on **multiple environments**, namely, GNU/Linux, Mac OS X, and Windows XP/Vista. Additionally, I'm using `ant` and `Eclipse`, so it would be great if I could easily add some `ant` targets for server management, and/or manage the server using the IDE. I've looked into **Tomcat** and **Jetty**, and the latter seems to be very light and easy to install and deploy. This is ideal, because the GUI is just for demonstration purposes, and I'll probably need to deploy it in different computers. However, Tomcat has been around for a very long time, and it seems more mature.
* As for the **web pages**, Java Server Pages look like a good fit, as they seem sufficiently simple for what I'm trying to accomplish (processing a form and outputting the result), but I'm all ears for suggestions.
* I also have another requirement, which requires me to explain the "basic" workflow of the application: Basically, I have a class `Engine` which has a method `run(String)` which will process the user's input and return the results for display. This class is the *core* of the application. Now, I'd like to **instantiate** this class **only once**, as it requires a **lot** of memory, and takes a very long time to startup, so I'd like to create it when the application/server starts, and store that reference for the entire span of the application (i.e., until I stop the server). Then, for each user request, I'd simply invoke the `run` method of the `Engine` instance, and display its results. *How can this be accomplished in Java?*
--- | 1. App Server. You see Tomcat as heavy in terms of runtime footprint, or amount of learning or ...? I would tend to chose something that has well established integration with an IDE. So Eclipse + Tomcat or Apache Geronimo, perhaps in it's [WebSphere Community Edition](http://www-01.ibm.com/software/webservers/appserv/community/) guise would do the job. From what I've seen these are sufficient for what you want, and the learning curves are really pretty manageable.
2. Yes JSPs. You may yet find that your presentation needs become a tad more complex. The extra effort of going to JSF might yet pay off - nice widgets such as Date pickers.
3. In your processing you will have a servlet (or an action class if you're using JSF) that class can have a member variable of type Engine initialised on startup and then used for every request. The thing to bear in mind is that many users will hit that servlet, and hence that engine at the same time. Is your Engine safe to be used from more than one thread at the same time?
To expand in this point. When implementing JSPs, there are two models refered to as (with some inventiveness) as Model 1 and Model 2. See [this explanation](http://www.javafaq.nu/java-article447.htl).
In the case of model 1 you tend to put code directly into the JSP, it's acting in a controller role. Persoanlly, even when dealing with small, quickly developed apps, I do not so this. I always use Model 2. However if you choose you can just put some Java into your JSP.
```
<% MyWorker theWorker = MyWorkerFactory.getWorker();
// theWorker.work();
%>
```
I woudl favour having a factory like this so that you can control the creation of the worker. The factory would have something like (to give a really simple example)
```
private static MyWorker s_worker = new MyWorker();
public static synchronized getWorker() {
return s_worker;
}
```
Alternatively you could create the worker when that method is first called.
In the case of model 2 you naturally have a servlet into which you are going to put some code, so you can just have
```
private MyWorker m_worker = MyWorkerFactory.getWorker();
```
This will be initialised when the servlet is loaded. No need to worry about setting it to load on startup, you just know that it will be initialsed before the first request is run.
Better still, use the init() method of the servlet. This is guranteed to be called before any requests are processed and is the servlet API architected place for such work.
```
public class EngineServlet extends HttpServlet {
private Engine engine;
// init is the "official" place for initialisation
public void init(ServletConfig config) throws ServletException {
super.init(config);
engine = new Engine();
}
``` | The technology you need to learn is the Sun Java Servlet specification since that is what ALL non-trivial java webservers implement. This enables you to write servlets which can do all the things you need server side. You can then develop against any container working well with your iDe, and deploy on any other container working well in production.
You also need to learn basic HTML as you otherwise would need to learn JavaServer Faces or similar which is a rather big mouthfull to create the submit button you need with the other entries in a HTML form.
For your Engine to work you can create a servlet with a singleton in web.xml, which you can then call. Be absolutely certain it is thread safe otherwise you will have a lot of pain. For starters you can declare your invoking servlet synchronized to ensure that at most one call of run() is active at any time. | Web User Interface for a Java application | [
"",
"java",
"jsp",
"tomcat",
"jetty",
"application-server",
""
] |
Using IE 6/7/8, I receive a JavaScript error code.
The line of code is:
```
document.getElementById('all').style.backgroundColor = color;
```
The IE 6/7/8 is:
```
Invalid property value
```
Thanks in advance! | Are you running this code after the DOM is completely loaded? Perhaps there is no 'panel-hlisting-all' yet? If you're using Prototype, you might try:
```
document.observe("dom:loaded", function() { // Wait until everything is loaded.
document.getElementById('panel-hlisting-all').style.background = color;
});
```
Just a thought — and I have no way of testing it on IE (thankfully/unfortunately), but what if you tried:
```
document.getElementById('panel-hlisting-all').style.backgroundColor = color;
```
**Added:**
Also note that `color` must be a string containing a valid CSS color (`#FFFFFF`, `rgb(255,255,255)`, `rgba(255,255,255,1)`). | Since you're trying to set the `backgroundColor` when you get this error, my guess would be that the property whose value is invalid - is `backgroundColor`!
Set a breakpoint on that line and find out what value `color` has. | JavaScript error - Invalid property value | [
"",
"javascript",
"html",
""
] |
I scanned my login script using [**SQL Inject Me**](https://addons.mozilla.org/en-US/firefox/addon/7597) Firefox addon
According to the Test Results, my script was vulnerable to SQL Injection. Result by example
```
Results:
Server Status Code: 302 Found
Tested value: 1' OR '1'='1
Server Status Code: 302 Found
Tested value: 1' OR '1'='1
Server Status Code: 302 Found
Tested value: 1 UNI/**/ON SELECT ALL FROM WHERE
Server Status Code: 302 Found
Tested value: %31%27%20%4F%52%20%27%31%27%3D%27%31
```
My script
1. login.php - Login form
2. check-login.php - To check login detail and here is the code.
$email = clean($\_POST['username']);
$pass = clean($\_POST['password']);
$user = "select \* from tbl\_admin where admin='$email' and pass='$pass'";
// some code
$\_SESSION['login\_mes'] = "You have successfully logged in !";
header("Location:admin.php");
exit();
} else {
$\_SESSION['login\_mes'] = "Invalid email address or password, please try again.";
header("Location:login.php");
exit();
}
The problems came when login failed. If I remove the
```
} else {
$_SESSION['login_mes'] = "Invalid email address or password, please try again.";
header("Location:login.php");
exit();
}
```
No failures detect by SQL Inject Me and how to fix this part? | 302 is the server's way of saying "I want you to go to [somewhere else]" (in this case login.php).
It is not an error but a perfectly normal response. Especially in your case it makes much more sense (if you ask me) to send the user to a login page after a SQL injection attempt than to let him in. | Four years later but I was just looking into this question and thought that I would share for the next person.
After some analysis, we concluded that the 302 is in itself not a concern. The concern is what page preceded the 302 which might have been sent but was swept away by the 302 before it could be displayed. If the previous page received by the browser (and perhaps recorded by Fiddler) contained database errors (or other information that a hacker might find useful) than that is bad. If the 302 is the initial response and it has an empty body, just a header, then I think that you are OK.
You have to display the error page (the purpose of the 302) so I don't see how that could be considered "too much information". | How to fix Server Status Code: 302 Found by SQL Inject Me Firefox Addon | [
"",
"php",
"mysql",
"sql-injection",
""
] |
I want to build a desktop application - a map viewer , something like this : `http://sunsite.ubc.ca/UBCMap/` in Java . Whenever someone hovers the mouse over a building on the map , there should be a balloon tool-tip saying something about that building on the map like its office phone number etc and that building should glow in the 2-d map. Can someone provide me some directions as to what framework should i use in Java to build something like this(e.g JavaFx) ? Is there any sample code which does something similar ? | If really all you have is an image and you want tooltips over it - here is a 30 second description.
* Subclass JPanel
* override paint() method to draw image
* Define some number of Shape objects (polygons, rects, etc...) as your "buildings" along with a text tooltip string
* override getTooltip in JPanel subclass. On each call iterate over your Shape objects, testing if the point is inside shape (shape has a method for this). return tooltip appropriate for Shape, or null if your mouse isn't over shape
* if you want rollover effects, register MouseMotionListener and use it to find the "hover" shape. Call repaint() and render your "hover" in some special way.
* boom! you're done
HINT: You will need to register your JPanel with TooltipManager most likely. | If your map really is as simple as the example you linked to, I would highly recommend avoiding the use of java (or javaFX altogether). You can do what you want with any of the javascript DHTML mapping apis. See
* Google Maps API
* OpenLayers
Java is overkill. Applets are slow to load and difficult to properly deploy under a varied number of environments. Better to publish a KML file (or something equivalent) and leverage someone else's maps than to write and maintain an entire application yourself. | Interactive Map viewer desktop application in Java | [
"",
"java",
"user-interface",
"javafx",
""
] |
Obviously we will still maintain it, but how useful will it be, once the C++ standard guarantees is.
What about synchronization primitives (Mutex, conditional variables) with advent of the new standard?
**Do you consider pthread harder to master as opposed to std::thread?** | C isn't going away. POSIX isn't going away. Multithreaded code written in C for POSIX isn't going away. So pthreads isn't going away.
Many implementations of std::thread will use pthreads under the hood.
"The Pthreads API is defined in the ANSI/IEEE POSIX 1003.1 - 1995 standard." -- POSIX Threads Programming <https://computing.llnl.gov/tutorials/pthreads/> | POSIX is an operating system standard. C++0X is a language standard. Having threads in the second will not obsolete the first. There is a collaboration between the two so that the second is implementable on the first. (And there is also work in process to have a C++ interface for POSIX). | Will pthreads become obsolete once std:thread makes into C++Ox | [
"",
"c++",
"standards",
"c++11",
""
] |
Well as I have posted earlier too...I have created a site in two languages. One with URL `www.mainDomain.com` (English) and other with `www.fr.subDomain.com` (French).
Both are done in CakePHP,in french I have just changed the views of it to French. But the problem is, when anybody login's in English version and then switches to the French version, the session doesn't recognizes it and ask for login again. It has become to be the biggest bug in the Web application which I have done till far.
For that, as Swanny told me to go through [a link](http://www.cake-toppings.com/tag/subdomains/) and I did it on my application as it was said on the link.Apparently,it worked for login which shared session between two domains(main domain and it's subdomain). But when I checked it thoroughly, I recognized that both the sites are throwing the latest NEWS from Database, both data are different. Just to check if I was wrong I changed the some save variable to database in session array. But now it refused to remember anything (session). Could anyone suggest me what could be problem with this and how can I resolve this...???
Thanks in advance | I'm not sure I completely understand, but I'm gonna try. I think this is about a PHP setting called `session.cookie_domain`.
Assuming your websites have the following URLs:
* <http://www.example.org/>
* <http://fr.example.org/>
* <http://de.example.org/>
The setting you want is: `.example.org`.
You can adjust this in `php.ini`, a `.htaccess` file or even in PHP itself:
```
<?php ini_set('session.cookie_domain', '.example.org'); ?>
```
If your websites run on two completely different domains, e.g.:
* <http://example1.org/>
* <http://example2.org/>
... then there is no way to share the cookie between these two different domains. | @dooltaz That is a great solution. Be issue is that cake seems to be setting the cookie after me. What I did instead is send the user ro a redirect method and then move the cookie setting to the afterFilter
```
function afterFilter() {
if (!empty($this->params['url']['session_key'])) {
// Setup variables here...
setcookie(Configure::read('Session.cookie'), $this->params['url']['session_key'], time()+360000, '/');
// Cakes cookie method will put your cookie name in [] so it does not work.
}
}
```
(Also fixed typo in your code..) | Problem in maintaining session between two different domains on a website done in CakePHP | [
"",
"cakephp",
"session",
"php",
""
] |
I am using MySql 5
Hi I am using/start learing JDBC. Well I got stuck here: After an user authenticated, I would like to start/generate the session for the user. How do I do that?
In php, I know, we can start by using the "start\_session()" function. Is there any similar function in JDBC?
If there is no such kind of functions, how do we create/start session? I am really new to JDBC, so this question may sound stupid to you all, but I really cant find the answer over the internet and thats why I ask this question here. (My best resource)
Oh ya, btw, if its possible, can you include in the answer about the session destroy/delete as well? Thanks in millions
**EDIT**
Okay, looks like this question abit too easy(or too tough??). Maybe could try this one, **is there any other way that java can unique identify an logged in user beside using session??** | start\_session in php creates a user session if it does not exist.
In the jave web app we have a HttpSession class whose instance is created by doing:
request.getSession(boolean)
This call : Gets the current valid session associated with this request, if create is false or, if necessary, creates a new session for the request, if create is true.
This has nothing to do with JDBC calls - that are mainly related to connection establishment and execution of queries. | Assuming you are talking in the context of web application. There is a session provided by the Servlet container. You authenticate the user and set the credentials in the session of that user, to re-use whenever necessary, for example to know the privileges of the user etc..
Regarding JDBC, we usually go with connection pooling mechanism. So, it has nothing to do with the HTTP session of the user. We get the connection from the pool, and place it back once done. If you need to manage transaction or something you can look into JTA.
**[Edited]**
Try to look at the code of [this Simple Login application](http://simple.souther.us/not-so-simple.html). I am sure it will help. | Java Database Connectivity (JDBC) session handling? | [
"",
"java",
"jdbc",
"authentication",
"session",
""
] |
So I'm thinking of using a reference type as a key to a .NET Dictionary...
**Example:**
```
class MyObj
{
private int mID;
public MyObj(int id)
{
this.mID = id;
}
}
// whatever code here
static void Main(string[] args)
{
Dictionary<MyObj, string> dictionary = new Dictionary<MyObj, string>();
}
```
My question is, how is the hash generated for custom objects (ie not int, string, bool etc)? I ask because the objects I'm using as keys may change before I need to look up stuff in the Dictionary again. If the hash is generated from the object's address, then I'm probably fine... but if it is generated from some combination of the object's member variables then I'm in trouble.
**EDIT:**
I should've originally made it clear that I don't care about the equality of the objects in this case... I was merely looking for a fast lookup (I wanted to do a 1-1 association without changing the code of the classes involved).
Thanks | The hash used is the return value of the .GetHashcode method on the object. By default this essentially a value representing the reference. It is not guaranteed to be unique for an object, and in fact likely won't be in many situations. But the value for a particular reference will not change over the lifetime of the object even if you mutate it. So for this **particular** sample you will be OK.
In general though, it is a very bad idea to use objects which are not immutable as keys to a Dictionary. It's way too easy to fall into a trap where you override Equals and GetHashcode on an object and break code where the type was formerly used as a key in a Dictionary. | The default implementation of GetHashCode/Equals basically deals with *identity*. You'll always get the same hash back from the same object, and it'll *probably* be different to other objects (very high probability!).
In other words, if you just want reference identity, you're fine. If you want to use the dictionary treating the keys as *values* (i.e. using the data within the object, rather than just the object reference itself, to determine the notion of equality) then it's a bad idea to mutate any of the equality-sensitive data within the key after adding it to the dictionary.
The MSDN documentation for `object.GetHashCode` is a little bit overly scary - basically you shouldn't use it for *persistent* hashes (i.e. saved between process invocations) but it will be consistent *for the same object* which is all that's required for it to be a valid hash for a dictionary. While it's not guaranteed to be unique, I don't think you'll run into enough collections to cause a problem. | What does .NET Dictionary<T,T> use to hash a reference? | [
"",
"c#",
".net",
"hash",
""
] |
I have 2 chekboxes on a page. There are wrapped in a table cell each within their own row. Doing a document.getElementById('chk1\_FEAS~1005') returns the element but document.getElementById('chk5\_STG2~1005') is null. For what reasons could this be happening? (I'm testing in IE 8).
```
<input id="chk1_FEAS~1005" value="JobStages###StageCode~JobCode###FEAS~1005" onclick="addRemoveRow(this.value,this.checked)" style="border-width:0px;padding:1px;margin:0px;height:14px;" type="checkbox" />
<input id="chk5_STG2~1005" value="JobStages###StageCode~JobCode###STG2~1005" onclick="addRemoveRow(this.value,this.checked)" style="border-width:0px;padding:1px;margin:0px;height:14px;" type="checkbox" />
``` | Your Id has invalid characters:
> ID and NAME tokens must begin with a
> letter ([A-Za-z]) and may be followed
> by any number of letters, digits
> ([0-9]), hyphens ("-"), underscores
> ("\_"), colons (":"), and periods
> (".").
More information [here](http://www.w3.org/TR/html4/types.html). | ```
document.getElementById('hk5_STG2~1005')
```
should be
```
document.getElementById('chk5_STG2~1005')
```
:-) | document.getElementById not working | [
"",
"javascript",
"client-side",
""
] |
I have a table that has a lot of duplicates in the Name column. I'd
like to only keep one row for each.
The following lists the duplicates, but I don't know how to delete the
duplicates and just keep one:
```
SELECT name FROM members GROUP BY name HAVING COUNT(*) > 1;
```
Thank you. | See the following question: [Deleting duplicate rows from a table](https://stackoverflow.com/questions/1043488/deleting-duplicate-rows-from-a-table/1043505#1043505).
The adapted accepted answer from there (which is my answer, so no "theft" here...):
You can do it in a simple way assuming you have a unique ID field: you can delete all records that are the same except for the ID, but don't have "the minimum ID" for their name.
Example query:
```
DELETE FROM members
WHERE ID NOT IN
(
SELECT MIN(ID)
FROM members
GROUP BY name
)
```
In case you don't have a unique index, my recommendation is to simply add an auto-incremental unique index. Mainly because it's good design, but also because it will allow you to run the query above. | It would probably be easier to select the unique ones into a new table, drop the old table, then rename the temp table to replace it.
```
#create a table with same schema as members
CREATE TABLE tmp (...);
#insert the unique records
INSERT INTO tmp SELECT * FROM members GROUP BY name;
#swap it in
RENAME TABLE members TO members_old, tmp TO members;
#drop the old one
DROP TABLE members_old;
``` | How to keep only one row of a table, removing duplicate rows? | [
"",
"sql",
"sqlite",
"duplicates",
""
] |
Is there some way to know if a `JScrollBar` is visible or not inside a `JPanel`?
I mean, some times, my panel has many rectangles (think of it as buttons) and needs a scrollbar and some times it doesn't need it. I'd like to know if I can know when it is being shown. | If you extend the `JPanel` and add yourself the `JScrollbar`s (horizontal and/or vertical), then you can control when they must be visible or invisible
(you can check if they are currently visible with the `isvisible()` function)
You can find two example of such classes that determine the need for visible scrollbar depending on their content:
* [`JGraphPanel`](http://www.koders.com/java/fid5EE718E124C09FC470BAB3864C3DE582A13DF458.aspx?s=jpanel+scrollbar+isvisible#L33) (its callback [`actionPerformed(Event e)`](http://www.koders.com/java/fid5EE718E124C09FC470BAB3864C3DE582A13DF458.aspx?s=jpanel+scrollbar+isvisible#L88) will adjust the visibility based on a zoom factor)
* [`Plane`](http://www.koders.com/java/fid8955059994F4F7A31D4860E61914F080BB4B2CC6.aspx?s=jpanel+scrollbar+isvisible#L23) (its function [`adjustComponents()`](http://www.koders.com/java/fid8955059994F4F7A31D4860E61914F080BB4B2CC6.aspx?s=jpanel+scrollbar+isvisible#L93) will call `setVisible()` on the `JScrollBar` if needed) | Assuming you have a reference to a `JScrollPane`, you should be able to just call
```
yourJScrollPane.getHorizontalScrollBar().isVisible()
```
or
```
yourJScrollPane.getVerticalScrollBar().isVisible()
``` | JScrollBar visible | [
"",
"java",
"swing",
""
] |
I have the following code which I use to map a nested list in Python to produce a list with the same structure.
```
>>> nested_list = [['Hello', 'World'], ['Goodbye', 'World']]
>>> [map(str.upper, x) for x in nested_list]
[['HELLO', 'WORLD'], ['GOODBYE', 'WORLD']]
```
Can this be done with list comprehension alone (without using the map function)? | For nested lists you can use nested list comprehensions:
```
nested_list = [[s.upper() for s in xs] for xs in nested_list]
```
Personally I find `map` to be cleaner in this situation, even though I almost always prefer list comprehensions. So it's really your call, since either will work. | Remember the Zen of Python:
> There is generally more than one -- and probably *several* -- obvious ways to do it.\*\*
\*\* Note: Edited for accuracy.
Anyway, I prefer map.
```
from functools import partial
nested_list = map( partial(map, str.upper), nested_list )
``` | Mapping a nested list with List Comprehension in Python? | [
"",
"python",
"list",
"list-comprehension",
"nested-lists",
"map-function",
""
] |
I've run into a bit of a problem with my class hierarchy, in a WPF application. It's one of those issues where you have two inheritance trees merging together, and you can't find any logical way to make your inheritance work smoothly *without* multiple inheritance. I'm wondering if anyone has any bright ideas for getting this kind of system working, without making it impossible to follow or debug.
I'm a low-level engineer, so my first thought is always, "Oh! I'll just write some of these classes in native C++, and reference them externally! Then I can have all my old-school OO fun!" Alas, this doesn't help when you need to inherit from managed controls...
Allow me to show a snippet of my current projected class diagram:
```
____________________________________ _____________________________________
| CustomizableObject | | System.Windows.Controls.UserControl |
|____________________________________| |_____________________________________|
| string XAMLHeader() | ▲
| string XAMLFooter() |◄--┐ |
| CustomizableObject LoadObject() | \ |
| <Possible other implementations> | \ |
|____________________________________| \ |
▲ ▲ \ |
| | \ |
| | \ |
_________________ ______________________ \ _____________________
| SpriteAnimation | | SpriteAnimationFrame | └---| CustomizableControl |
|_________________| |______________________| |_____________________|
▲ ▲
| |
| |
________ _____________
| Sprite | | SpriteFrame |
|________| |_____________|
```
The problem is pretty clear: the separation of the CustomizableObject and CustomizableControl object trees --- and the insertion of UserControl into one, but not both, of the trees.
It makes no practical sense to move the implementation of CustomizableObject into its derived classes, since the implementation doesn't vary by class. Furthermore, it would be really confusing to have it implemented multiple times. So I really don't want to make CustomizableObject an interface. The interface solution doesn't make any sense to me. (Interfaces have *never* really made much sense to me, to be honest...)
So I say again, anyone have any bright ideas? This one's a real pickle. I'd like to learn more about making interfaces work WITH my object tree, rather than against it. I'm making this simple sprite engine using WPF and C# as a solid exercise, more than anything. This is so easy to solve in C++ - but I need to figure out how to solve these problems in a managed environment, rather than throwing my hands in the air and running back to Win32 whenever the going gets tough. | One approach is to use extension methods with an interface to provide your "derived class" implementation, much like System.Linq.Queryable:
```
interface ICustomizableObject
{
string SomeProperty { get; }
}
public static class CustomizableObject
{
public static string GetXamlHeader(this ICustomizableObject obj)
{
return DoSomethingWith(obj.SomeProperty);
}
// etc
}
public class CustomizableControl : System.Windows.Controls.UserControl, ICustomizableObject
{
public string SomeProperty { get { return "Whatever"; } }
}
```
**Usage:** As long as you have a using directive for (or are in the same namespace as) the namespace where your extension methods are defined:
```
var cc = new CustomizableControl();
var header = cc.GetXamlHeader();
``` | You have two options here; use interfaces, or use composition. Honestly, interfaces are very powerful, and after reading this line
> The interface solution doesn't make any sense to me. (Interfaces have never really made much sense to me, to be honest...)
I think that you should learn how to use them properly. That said, if there is simply some logic that multiple class need, but it does not make sense for these classes to inherit from the same base class, just create a class to encapsulate that logic and add a member variable of that class to your classes that are giving you problems. This way all of the classes contain the logic but can be separate in their inheritance hierarchies. If the classes should implement a common interface(s), then use interfaces. | What are some good alternatives to multiple-inheritance in .NET? | [
"",
"c#",
".net",
".net-3.5",
"inheritance",
"multiple-inheritance",
""
] |
I have built a C# .net web service that takes a complex type as a parameter. Is there a testing tool that I can run against my web service and pass all of the values to the complex parameter type?
Some background info:
I ran the xsd.exe tool against my XSD and have created a .cs class. This .cs class has the dataset that is used as my complex parameter. Now I need to test out my webmethod and pass values to it as the client would. I have tried [WebService Studio](http://www.codeplex.com/WebserviceStudio "WebService Studio") and [Storm](http://www.codeplex.com/storm "Storm"), but it seems that neither of the products can handle complex types. Is there any other product that can do this? Or do I have write my own test application from scratch? | [soapUI](http://soapUI.org) will help you do this.
However, the way I usually do it is to write automated unit tests using NUNIT or MSTEST, add a Service Reference and then just write the tests. This has the additional benefit that you are creating the same kind of client code your users will need to do. If your service is hard to use, then you'll find out pretty quick. | For classic ASMX services, I used Web Service Studio 2.0 which handled every complex type I threw at it. You can get the classic version (2.0) from [http://archive.msdn.microsoft.com/webservicestudio20/](http://archive.msdn.microsoft.com/webservicestudio20/Release/ProjectReleases.aspx?ReleaseId=1394).
I know there is an updated version on codeplex that you linked to and it looks like it's been updated to support complex types. (A while back there was a useless tool on codeplex that couldn't do complex types.)
Just curious what specific issue you are having with Web Service Studio?
UPDATE: After re-reading your question, it sounds like you are using a DataSet in your service. If so, then you are going to have interoperability problems consuming that service from most toolkits; they can't handle the DataSet because it is a "dynamic" type. The easiest way around that issue is to [avoid DataSets](http://msdn.microsoft.com/en-us/magazine/cc188755.aspx#S4).
If that is the case, then I agree with others that you will need to create your own .NET application that can consume your service. | Is there a testing tool to test a C# .net web service that contains complex types? | [
"",
"c#",
".net",
"web-services",
"testing",
""
] |
I'm looking for a javascript unit test framework that I can use as part of my automated maven build. This CANNOT use an actual browser, and it MUST be fully browserless.
I've tried looking at a few posts on SO, but none seem to meet my needs. Is there such a javascript unit tester? I'm anxious to find out. | I was trying to solve the same problem. It seems, that this is not as common, as one might think from our perspective.
[RhinoUnit](http://code.google.com/p/rhinounit/) looks very good.
If you need browser capabilities within Rhino, take a look at
* <http://ejohn.org/blog/bringing-the-browser-to-the-server/>
* <http://groups.google.com/group/envjs>
* <http://github.com/thatcher/env-js/tree/master> | There are two projects called JSUnit ([www.jsunit.net](https://github.com/pivotal/jsunit)) and ([jsunit.berlios.de](http://jsunit.berlios.de/)). The latter is designed to work with [Rhino and Maven](http://jsunit.berlios.de/maven2.html). Note that there will be browser-specific problems that such tests will not discover, but it should help with basic functionality. | Browserless, ant-task-oriented Javascript Unit Testing? | [
"",
"javascript",
"unit-testing",
"build-automation",
"maven-1",
""
] |
Given an array:
```
$a = array(
'abc',
123,
'k1'=>'v1',
'k2'=>'v2',
78,
'tt',
'k3'=>'v3'
);
```
With its internal pointer on one of its elements, how do I insert an element after the current element?
And how do I insert an element after a key-known element, say 'k1'?
Performance Care~ | You could do it by splitting your array using `array_keys` and `array_values`, then splice them both, then combine them again.
```
$insertKey = 'k1';
$keys = array_keys($arr);
$vals = array_values($arr);
$insertAfter = array_search($insertKey, $keys) + 1;
$keys2 = array_splice($keys, $insertAfter);
$vals2 = array_splice($vals, $insertAfter);
$keys[] = "myNewKey";
$vals[] = "myNewValue";
$newArray = array_merge(array_combine($keys, $vals), array_combine($keys2, $vals2));
``` | I found a great answer [here](http://eosrei.net/articles/2011/11/php-arrayinsertafter-arrayinsertbefore) that works really well. I want to document it, so others on SO can find it easily:
```
/*
* Inserts a new key/value before the key in the array.
*
* @param $key
* The key to insert before.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_after()
*/
function array_insert_before($key, array &$array, $new_key, $new_value) {
if (array_key_exists($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
if ($k === $key) {
$new[$new_key] = $new_value;
}
$new[$k] = $value;
}
return $new;
}
return FALSE;
}
/*
* Inserts a new key/value after the key in the array.
*
* @param $key
* The key to insert after.
* @param $array
* An array to insert in to.
* @param $new_key
* The key to insert.
* @param $new_value
* An value to insert.
*
* @return
* The new array if the key exists, FALSE otherwise.
*
* @see array_insert_before()
*/
function array_insert_after($key, array &$array, $new_key, $new_value) {
if (array_key_exists ($key, $array)) {
$new = array();
foreach ($array as $k => $value) {
$new[$k] = $value;
if ($k === $key) {
$new[$new_key] = $new_value;
}
}
return $new;
}
return FALSE;
}
``` | How to efficiently insert elements after another known (by key or pointer) element in a PHP array? | [
"",
"php",
"performance",
"arrays",
""
] |
I have a holder div on the page where I want to load small images in on random position as a collage with 10px padding on each.
How can I make sure that images never overlap each other or holder div?
Is there a plugin or function that I could use?
My code so far:
```
<script src="jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#my_canvas img").each(
function(intIndex) {
var l = Math.floor(Math.random() * $("#my_canvas").width());
var t = Math.floor(Math.random() * $("#my_canvas").height());
$(this).css("left", l);
$(this).css("top", t);
$(this).bind(
"click",
function() {
alert("l=" + l + " t=" + t);
}
);
}
);
```
});
```
<style type="text/css">
#my_canvas
{
background: #eee;
border: black 1px solid;
width: 800px;
height: 400px;
}
#my_canvas img
{
padding: 10px;
position:absolute;
}
</style>
<div id="my_canvas">
<img src="images/1.jpg" />
<img src="images/9.jpg" />
<img src="images/2.jpg" />
<img src="images/3.jpg" />
<img src="images/4.jpg" />
<img src="images/5.jpg" />
<img src="images/6.jpg" />
<img src="images/7.jpg" />
<img src="images/8.jpg" />
</div>
``` | I guess there is no plugin. I will implement this like Sander suggested by making predefined div grid and just loading random images to those divs. It's easier and faster than calculating image dimenssions/positions and does pretty much the same job. Not random but visually looks good :) | Store the picked coordinates in an array, so that you can compare the coordinates of each new image you place against the previous.
If the coordinates that you picked overlaps a previous image, pick new coordinates. Limit the number of tries so that if you can't place an image with say 1000 tries, you start over with the first image. | Generate random element position and prevent overlapping in JavaScript | [
"",
"javascript",
"jquery",
"css",
"random",
"css-position",
""
] |
Here's the deal. I have an application with three tabs. Through various interactions with the items in the tabs I end up launching other activities. The client has reviewed this and would like the activities launched "within" the tabs, so the tabs remain visible and if the user clicks the tab it goes back to the original activity defined in the setContent function. Is this possible and how would I go about this from other activities? (ie the child activities, not the one that defines the TabHost and has access to call setContent)? | **It is possible to launch activities within tabs**. Therefore set the tabspec content to an ActivityGroup instead of a regular Activity.
```
tabHost.addTab(tabHost.newTabSpec("Tab")
.setIndicator("Tab")
.setContent(new Intent(this, YourActivityGROUP.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
```
From within that ActivityGroup you can then start another Activity like this that only updates the contentview of the tab you're in.
```
class YourActivityGROUP extends ActivityGroup{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//you van get the local activitymanager to start the new activity
View view = getLocalActivityManager()
.startActivity("ReferenceName", new
Intent(this,YourActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
this.setContentView(view);
}
}
``` | Here is my solution
```
public class ActivityStack extends ActivityGroup {
private Stack<String> stack;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null) stack = new Stack<String>();
//start default activity
push("FirstStackActivity", new Intent(this, FirstStackActivity.class));
}
@Override
public void finishFromChild(Activity child) {
pop();
}
@Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1) finish();
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent();
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
```
Launch tab
```
Intent intent = new Intent().setClass(this, ActivityStack.class);
TabHost.TabSpec spec = tabHost.newTabSpec("tabId")
spec.setContent(intent);
```
Call next activity
```
public class FirstStackActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), SecondStackActivity .class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("SecondStackActivity", intent);
}
});
setContentView(textView);
}
}
```
Call next again
```
public class SecondStackActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView = new TextView(this);
textView.setText("First Stack Activity ");
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(getParent(), ThirdStackActivity .class);
ActivityStack activityStack = (ActivityStack) getParent();
activityStack.push("ThirdStackActivity", intent);
}
});
setContentView(textView);
}
}
```
Works on emulator 2.2 | Launching activities within a tab in Android | [
"",
"java",
"android",
""
] |
I vaguely understand the concept of an object graph. Does it only apply to in memory objects built via composition; or is inheritance a structual attribute of the graph as well? | Inheritance has nothing to do with an object graph. Think of an object graph as an "instance graph", where vertices are instances, and (directed) edges are references between instances. The type of a particular instance has no bearing whatsoever on the graph; and yes, it is generally only built via composition.
The inheritance structure of a class is an entirely different concept that is often drawn as a graph (actually, with single-inheritance, it's a tree). This is just a coincidence. | Personally I would only use the term "object graph" for in memory objects, and use a term like "class graph", "inheritance tree", etc. for the class structure tree. | Object Graphs and Inheritance | [
"",
"c#",
"oop",
"object",
""
] |
I have an application where a user performs an action and receives points. Would it be a better idea to perform the arithmetic in the application and update the points database field with the resulting value, or have the database do the math?
Assuming a user with 0 points is to receive 2 additional:
```
//app does the math (0+2) and issues this statement
update users set points = 2 where id = 1
```
vs
```
//app only knows to update by 2, db does the math
update users set points = points+2 where id = 1
```
Is there any difference in terms of SQL performance? Is one approach better than the other as far as application design, where this logic should reside, etc?
**Edit:** This edit may be coming too late to serve much good, but I just wanted to respond to some of the feedback and make a clarification. While I'm curious of any db performance difference, this is not a *concern*. My concern is where this logic would best reside and why one should be favored over the other and in which scenarios.
On one hand nearly all of my logic resides within the application so it would be consistent to do the math there, [like Hank's answer](https://stackoverflow.com/questions/1271570/is-it-better-to-update-or-increment-a-value-when-persisting-to-a-database/1271599#1271599). But on the other hand, there is some potential latency/threading issues that may suggest the logic should be performed by the db, as brought up by [Blixt](https://stackoverflow.com/questions/1271570/is-it-better-to-update-or-increment-a-value-when-persisting-to-a-database/1271602#1271602) and [Andrew](https://stackoverflow.com/questions/1271570/is-it-better-to-update-or-increment-a-value-when-persisting-to-a-database/1271656#1271656). | There is a difference in the two operations. The first says:
> The user should have two points; no more, no less.
The second says:
> The user should get two more points, in addition to what he/she already has.
I would refrain from putting this kind of data logic in the business logic layer. The business logic should be "the user gets two points" and it should tell the database this. It shouldn't take matters into its own hands and say "well the database told me the user has two points, so now they have four!" This is dangerous if there's latency between the business layer and the database, or very many updates going on simultaneously in multiple threads.
*I realized I didn't actually put which choice I prefer in clear text:*
Determine in the business logic how many points a user should get. Then issue a statement that tells the database to increment the score of the user by those points. By doing this, you're making the database responsible for keeping the data consistent, which is a task that should only ever belong to a database. I mean it's what they do, right?
```
UPDATE users SET points = points + ? WHERE user_id = ?;
```
Your business logic layer would simply fill in the blanks.
If you're doing a huge project, you might even want to consider putting this in a stored procedure since you might change the data structure in the future (such as breaking out the points to another table or some such):
```
userChangePoints ?, ?
``` | Whilst in some sense it can be viewed as premature optimisation, for a multi-threaded / user environment difference between the two would be quite critical in that directly reading and then setting the value allows two transactions to interfere and result in one of them potentially being lost.
Sending in a points update with points=points+2at least isolates the two statements, but then if submitted twice by different users simultaneously would give you a results of 4.
That equally may not suit the situation / application, but I think your choice should take into account what isolation / protection you need.
This is then specfic to the app, can a user be logged in twice etc, but the principal of the difference between the two remains. | Is it better to update or increment a value when persisting to a database? | [
"",
".net",
"sql",
"sql-server",
""
] |
I have some work items pooled using the legacy QueueUserWorkItem function (I need to support OSs earlier than vista, so
```
for( <loop thru some items >)
{
QueueUserWorkItem( )
}
```
I need to wait on these before proceeding to the next step.
I've seen several similar answers...but they are in .NET.
I'm thinking of using a storing an Event for each item and waiting on them(gasp!), but are there other better, lightweight ways? (no kernel locks)
Clarification: I know of using Events. I'm interested in solutions that don't require a kernel-level lock. | AFAIK the only ways you can do this is to have a counter that is InterlockIncrement'ed as each task finishes.
You can then either do a
```
while( counter < total )
Sleep( 0 );
```
of the task can signal an event (or other sync object) and you can do the following
```
while( count < total )
WaitForSingleObject( hEvent, INFINITE );
```
The second method will mean that the main thread uses less processing time.
Edit: TBH the only way to avoid a kernel lock is to spin lock and that will mean you'll have one core wasting time that could otherwise be used to process your work queue (or indeed anything else). If you REALLY must avoid a kernel lock then spin lock with a Sleep( 0 ). However I'd definitely recommend just using a kernel lock, get the extra CPU time back for doing worthwhile processing and stop worrying about a 'non' problem. | This is possible w/o any wait if you actually split the execution stack: up to the for loop you execute on the calling thread, after the for loop you finish on the last queue thread:
```
CallerFunction(...)
{
sharedCounter = <numberofitems>;
for (<loop>)
{
QueueUserWorkItem(WorkerFunction, ...);
}
exit thread; (return, no wait logic)
}
WorkerFunction(, ...)
{
// execute queued item here
counter = InterlockeDdecrement(sharedCounter);
if (0 == counter)
{
// this is the last thread, all others are done
continue with the original logic from CallerFunction here
}
}
```
Whether this will work or not depends on many factors and I can't say w/o knowing more about the caller context, if is possible to suspend its execution on the calling thread and resume it on a queued thread. Btw by 'exit thread' I do not mean an abrupt thread abort, but a gracious return, and the entire calling stack is prepared to hand over execution context to the queue thread. Not a trivial task, I reckon. | wait for works item to complete pooled using QueueUserWorkItem (not .NET) | [
"",
"c++",
"winapi",
"multithreading",
""
] |
I am currently working on building a very simple site for an open source research project for my University. I am using JQuery to animate the sub-navigation of the site. However, my code only seems to work in IE and not Firefox or Chrome.
I'm not sure if it is a compatibility issue, or if it is my fault. I looked up examples on the web, and I do not see any differences in code as to why mine will not work.
The HTML for the section of the site is as follows :
```
<!-- START NAVIGATION & SUB NAVIGATION -->
<div class="nav">
<ul>
<li><a class="nav_home" href='#'><span>home</span></a></li>
<li><a class="nav_about" href="#"><span>about</span></a></li>
<li><a><span>research</span></a></li>
<li><a><span>findings</span></a></li>
<li><a><span>contact</span></a></li>
</ul>
</div>
<div class="sub_nav">
<ul class="sub_nav_home">
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
</ul>
<ul class="sub_nav_about">
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
<li><a><span>sub link</span></a></li>
</ul>
</div>
<!-- FINISH NAVIGATION -->
```
\*\*Note: this is just testing information to make sure I can get the navigation working before implementing the real thing. Also, only the first two links work. I didn't see the need to implement them all until I got it working.
And the JavaScript is as follows :
```
var current_sub = 0;
$(document).ready(function() {
//hide elements
$("div.sub_nav > ul").hide();
function get_sub_navigation(nav_name)
{
if(current_sub != 0)
{
$(current_sub).fadeOut("slow", function ()
{
$(nav_name).slideDown("slow");
});
}
else
{
$(nav_name).slideDown("slow");
}
current_sub = nav_name;
}
$("a.nav_home").click(function(event)
{
event.preventDefault();
get_sub_navigation("ul.sub_nav_home");
}
);
$("a.nav_about").click(function(event)
{
event.preventDefault();
get_sub_navigation("ul.sub_nav_about");
}
);
});
```
Ok, so the first thing is does is hide all sub nav lists. Then I have a listener for two of the nav links that should call `get_sub_navigation`. That function will check if there is one showing (just used 0 for default/nothing) and if there is hide it and if not, then show one.
As you can see, it is not finished code but, I don't want move any further until I can get this figured out.
Any help is much appreciated! | Call [`event.preventDefault()`](http://docs.jquery.com/Events/jQuery.Event#event.preventDefault.28.29) in your event handler, not `$(nav_name).preventDefault()` in your navigation function (or pass the event into it). I suspect that the default is not getting prevented, and the page is being redrawn. | First of all, to hide the ul elements by default on page load you can simply use css instead of javascript:
```
div.sub_nav > ul { visibility: hidden; }
```
(i'm not 100% IE <= 6.0 will be 100% OK with this selector, though)
Second, and while i am by no means a jQuery expert, i would imagine that since the selector returns multiple elements it needs a different approach.
try
```
$("div.sub_nav > ul").each( function() {
$(this).hide();
});
``` | JQuery, hide not working in Firefox | [
"",
"javascript",
"jquery",
"layout",
"web",
""
] |
I want to call Type.GetFields() and only get back fields declared as "public const". I have this so far...
```
type.GetFields(BindingFlags.Static | BindingFlags.Public)
```
... but that also includes "public static" fields. | Trying checking whether [`FieldInfo.Attributes`](http://msdn.microsoft.com/en-us/library/system.reflection.fieldinfo.attributes.aspx) includes [`FieldAttributes.Literal`](http://msdn.microsoft.com/en-us/library/system.reflection.fieldattributes.aspx). I haven't checked it, but it sounds right...
(I don't think you can get *only constants* in a single call to `GetFields`, but you can filter the results returned that way.) | ```
type.GetFields(BindingFlags.Static | BindingFlags.Public).Where(f => f.IsLiteral);
``` | Type.GetFields() - only returning "public const" fields | [
"",
"c#",
".net",
"reflection",
""
] |
Looking at the "highlight" JQuery effect:
<http://docs.jquery.com/UI/Effects/Highlight>
You can change the background color of any DIV to fade in/out
However, the example is to "highlight" on a "click" event
```
$("div").click(function () {
$(this).effect("highlight", {}, 3000);
});
```
How can I programatically call the highlight method as though it was a function within my code (instead of activate on a 'click' event)? | ```
$("div").effect("highlight", {}, 3000);
```
As pointed by JorenB this will highlight all the div's in your page.
If you only want to highlight one div like:
```
<div id="myDiv"></div>
```
You should do:
```
$("div#myDiv").effect("highlight", {}, 3000);
```
If you want to highlight all div's with a specific classe you cand do:
```
<div id="myDiv1" class="myClass"></div>
<div id="myDiv2" class="myClass"></div>
$("div.myClass").effect("highlight", {}, 3000);
```
For more information on selectors see [JQuery Selectors](http://docs.jquery.com/Selectors). | it would simply be
```
$([your selector]).effect("highlight", {}, 3000);
``` | JQuery - "highlight" effect help | [
"",
"javascript",
"jquery",
"html",
"jquery-ui",
""
] |
I have experienced problems since moving to the latest version of one of the IDEA plugins I use. I can download ZIP files of previous versions of the plugin from their website but I can't find any installation instructions for how to *manually install a specific version* of a plugin.
Anyone know how to do this? | Think you can simple drop the jar in the plugins directory:
> `idea.plugins.path=${user.home}/.IntelliJIdea80/config/plugins`
On Windows:
> `idea.plugins.path=%USERPROFILE%\.IntelliJIdea80\config\plugins` | You could also download the zip and then in **Settings Plugins** press **install plugin from disk** and choose the **zipfile**.
Works like a charm on my Mac =) | How do I install a specific version of an IDEA plugin? | [
"",
"java",
"ide",
"plugins",
"intellij-idea",
""
] |
I need to write python application connect to trixbox that run as SIP server. But I not found any library that implement in python. I found SIP SKD at <http://www.vaxvoip.com/> but it not support python. Can anyone suggest me an alternative to VaxVoip?
Thank you. | There are [Python bindings](http://trac.pjsip.org/repos/wiki/Python_SIP_Tutorial) for the PJSUA API. | [Twisted](http://twistedmatrix.com/trac/) supports SIP. That's really cool | Python SIP library | [
"",
"python",
"voip",
"sip",
"trixbox",
""
] |
I'm in the process of writing an HTML screen scraper. What would be the best way to create unit tests for this?
Is it "ok" to have a static html file and read it from disk on every test?
Do you have any suggestions? | To guarantee that the test can be run over and over again, you should have a static page to test against. (Ie. from disk is OK)
If you write a test that touches the live page on the web, thats probably not a unit test, but an integration test. You could have those too. | For my ruby+mechanize scrapers I've been experimenting with integration tests that transparently test against as many possible versions of the target page as possible.
Inside the tests I'm overloading the scraper HTTP fetch method to automatically re-cache a newer version of the page, in addition to an "original" copy saved manually. Then each integration test runs against:
* the original manually-saved page (somewhat like a unit test)
* the freshest version of the page we have
* a live copy from the site right now (which is skipped if offline)
... and raises an exception if the number of fields returned by them is different, e.g. they've changed the name of a thumbnail class, but still provides some resilience against tests breaking because the target site is down. | Unit testing screen scraper | [
"",
"c#",
"unit-testing",
"tdd",
"screen-scraping",
""
] |
How can I add `readonly` to a specific `<input>`? `.attr('readonly')` does not work. | jQuery <1.9
```
$('#inputId').attr('readonly', true);
```
jQuery 1.9+
```
$('#inputId').prop('readonly', true);
```
Read more about [difference between prop and attr](https://stackoverflow.com/q/5874652/340046) | Use [$.prop()](http://api.jquery.com/prop/)
```
$("#descrip").prop("readonly",true);
$("#descrip").prop("readonly",false);
``` | How to add a “readonly” attribute to an <input>? | [
"",
"javascript",
"jquery",
""
] |
I have the following code (I'm a Dot Net developers and I thought if I can bring my OOP knowledge to PHP)
```
class user {
var $_un;
function user($un) {
$_un = $un;
}
function adduser() {
}
function checkuser() {
}
function printuser () {
echo $_un;
}
}
$newuser = new user('Omar Abid');
$newuser->printuser();
```
So the problem is simple "$\_un" is empty!! I want it to be filled, when the class is created using the constructor and then saved.
I used to do that in C# .net, but here it doesn't work for some reasons.
Thanks! | In order to access class members in PHP you need to use [`$this->`](http://uk.php.net/manual/en/language.oop5.basic.php) .
So what you're currently doing is declaring a local variable called `$_un`, rather than assigned to the member variable `$this->_un` .
Try changing your code to:
```
function user($un) {
$this->_un = $un;
}
function printuser () {
echo $this->_un;
}
```
And it should work. | Rather than user() you should use \_\_construct(), it's the preferred way to add a Constructor in PHP5.
Also consider to add visibility to your methods and members (public / protected / private)
```
public function __construct($un) {
$this->_un = $un;
}
``` | PHP variables in classes | [
"",
"php",
"oop",
"variables",
""
] |
Is there a way to detect if content of my iframe has changed?
My workaround is I have a loop which constantly check for the height of the content it effective but not efficient is there another way of doing this? | Since the contents of the iframe has a separate `window` element, you can do this in a script inside of the iframe.
```
$(window).resize(function(){
var object = $(this)
// Use `object.height()` and `object.width()`.
});
```
You could also use `$("#the_iframe")[0].contentWindow.window` (or something like that) instead of `window` to access the `window` object of the iframe from the scope that contains the iframe. | ```
setInterval(function() {
var ifm = document.getElementById("UIMain");
var h = ifm.contentWindow.document.body.scrollHeight;
ifm.height = h < 400 ? 400 : h;
}, 800);
```
pure javascript is OK.didn't need jquery. | How do I detect iframe resize? | [
"",
"javascript",
"jquery",
"iframe",
"resize",
""
] |
Is there a neater way for getting the number of digits in an int than this method?
```
int numDigits = String.valueOf(1000).length();
``` | Your String-based solution is perfectly OK, there is nothing "un-neat" about it. You have to realize that mathematically, numbers don't have a length, nor do they have digits. Length and digits are both properties of a *physical representation* of a number in a specific base, i.e. a String.
A logarithm-based solution does (some of) the same things the String-based one does internally, and probably does so (insignificantly) faster because it only produces the length and ignores the digits. But I wouldn't actually consider it clearer in intent - and that's the most important factor. | The logarithm is your friend:
```
int n = 1000;
int length = (int)(Math.log10(n)+1);
```
NB: only valid for n > 0. | Way to get number of digits in an int? | [
"",
"java",
"integer",
""
] |
```
SET SERVEROUTPUT ON
DECLARE
v_student_id NUMBER := &sv_student_id;
v_section_id NUMBER := 89;
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN
SELECT final_grade
INTO v_final_grade
FROM enrollment
WHERE student_id = v_student_id
AND section_id = v_section_id;
CASE -- outer CASE
WHEN v_final_grade IS NULL THEN
DBMS_OUTPUT.PUT_LINE ('There is no final grade.');
ELSE
CASE -- inner CASE
WHEN v_final_grade >= 90 THEN v_letter_grade := 'A';
WHEN v_final_grade >= 80 THEN v_letter_grade := 'B';
WHEN v_final_grade >= 70 THEN v_letter_grade := 'C';
WHEN v_final_grade >= 60 THEN v_letter_grade := 'D';
ELSE v_letter_grade := 'F';
END CASE;
-- control resumes here after inner CASE terminates
DBMS_OUTPUT.PUT_LINE ('Letter grade is: '||v_letter_grade);
END CASE;
-- control resumes here after outer CASE terminates
END;
```
the above code I have taken from the book *"Oracle PL/SQL by Example, 4th Edition 2009"* my problem is when I enter a `student_id` not present in the table it returns me the following error
```
Error report: ORA-01403: no data found
ORA-06512: at line 7
01403. 00000 - "no data found"
*Cause:
*Action:
```
but according to the book it should have returned a null value and then follow the case flow. | When you are selecting INTO a variable and there are no records returned you should get a NO DATA FOUND error. I believe the correct way to write the above code would be to wrap the SELECT statement with it's own BEGIN/EXCEPTION/END block. Example:
```
...
v_final_grade NUMBER;
v_letter_grade CHAR(1);
BEGIN
BEGIN
SELECT final_grade
INTO v_final_grade
FROM enrollment
WHERE student_id = v_student_id
AND section_id = v_section_id;
EXCEPTION
WHEN NO_DATA_FOUND THEN
v_final_grade := NULL;
END;
CASE -- outer CASE
WHEN v_final_grade IS NULL THEN
...
``` | There is an alternative approach I used when I couldn't rely on the `EXCEPTION` block at the bottom of my procedure. I had variables declared at the beginning:
```
my_value VARCHAR := 'default';
number_rows NUMBER := 0;
.
.
.
SELECT count(*) FROM TABLE INTO number_rows (etc.)
IF number_rows > 0 -- Then obtain my_value with a query or constant, etc.
END IF;
``` | PL/SQL block problem: No data found error | [
"",
"sql",
"oracle",
"plsql",
"oracle10g",
"ora-01403",
""
] |
Can someone show me a piece of java code that parses this date:
2009-08-05
INTO THIS GMT DATE:
2009/217:00:00
====
what i have so far is:
```
java.text.SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
java.util.Calendar cal = Calendar.getInstance(new SimpleTimeZone(0, "GMT"));
format.setCalendar(cal);
java.util.Date date = format.parse(sdate);
```
but its not working | Here is the format you're looking for:
```
Date date = new SimpleDateFormat("yyyy-MM-dd").parse("2009-08-05");
String parsedDate = new SimpleDateFormat("yyyy/D:HH:mm").format(date);
``` | ```
format.setTimeZone(TimeZone.getTimeZone("GMT"));
```
That's how to set it to GMT at least. Not sure where you are getting 2009/217 from 2009-08-05 | How do I parse a standard date into GMT? | [
"",
"java",
"date",
"date-format",
"simpledateformat",
""
] |
I need to read the `Manifest` file, which delivered my class, but when I use:
```
getClass().getClassLoader().getResources(...)
```
I get the `MANIFEST` from the first `.jar` loaded into the Java Runtime.
My app will be running from an applet or a webstart,
so I will not have access to my own `.jar` file, I guess.
I actually want to read the `Export-package` attribute from the `.jar` which started
the Felix OSGi, so I can expose those packages to Felix. Any ideas? | You can do one of two things:
1. Call `getResources()` and iterate through the returned collection of URLs, reading them as manifests until you find yours:
```
Enumeration<URL> resources = getClass().getClassLoader()
.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try {
Manifest manifest = new Manifest(resources.nextElement().openStream());
// If the line above leads to <null> manifest Attributes try from JarInputStream:
// Manifest manifest = resources.nextElement().openStream().getManifest();
// check that this is your manifest and do what you need or get the next one
...
} catch (IOException E) {
// handle
}
}
```
2. You can try checking whether `getClass().getClassLoader()` is an instance of `java.net.URLClassLoader`. Majority of Sun classloaders are, including `AppletClassLoader`.
You can then cast it and call `findResource()` which has been known - for applets, at least - to return the needed manifest directly:
```
URLClassLoader cl = (URLClassLoader) getClass().getClassLoader();
try {
URL url = cl.findResource("META-INF/MANIFEST.MF");
Manifest manifest = new Manifest(url.openStream());
// do stuff with it
...
} catch (IOException E) {
// handle
}
``` | You can find the URL for your class first. If it's a JAR, then you load the manifest from there. For example,
```
Class clazz = MyClass.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
// Class not from JAR
return;
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) +
"/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
// If the line above leads to <null> manifest Attributes try instead from JarInputStream:
//Manifest manifest = new URL(manifestPath).openStream().getManifest();
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue("Manifest-Version");
``` | Reading my own Jar's Manifest | [
"",
"java",
"osgi",
"manifest.mf",
"apache-felix",
""
] |
I have created a scroll div which works and is fine. However, my boss now wants to give the client the option of turning of the scrolling feature. I have done this with a simple boolean variable, the problem being that the results page, which has the scrolling feature, has several pages and if the user clicks on to the next page the scroll feature is enabled again (scroll\_thumb="true"). What is the best way to keep a variable available to several pages in your app? I don't really want to start passing it in the url, or use a hidden form field, is there another way?
This set of pages are running in .net 3.0 framework but are written in classic asp.
Thanks, R. | Store it in a cookie. | You should use the framework's (ASP, ASP.NET, or whatever web application framework you're using) state mechanisms to maintain this state across pages. Session state or view state (or whatever more modern state mechanism they have now) is what should be used.
Rolling your own state maintenance in your own cookie(s) would be a bad way to go. Let the framework help you manage this (it'll likely use it's own cookie, but that should be more or less transparent to you). | JavaScript persistent variable | [
"",
"javascript",
""
] |
SQL reporting services has a little search box in the top of the report viewer. When used, it finds the search text, navigates to containing page and highlights the text on the page. My question is how can I do this when the report loads.
Currently I have a reportviewer embedded in my page. Is there a method that will find? I am using sql 2008 express and Dot Net 2
For example I send the serial number 1234 to the report so that when it opens it acts like the user searched for the text and finds it for them in the report.
---
Ed gave me the answer to the url part. `http://server/Reportserver?/SampleReports/Product Catalog&rc:FindString=mystring` but I still can't figure out the reportviewer.
---
Here is some of the page code:
```
using Microsoft.Reporting.WebForms;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Int32 iID = Convert.ToInt32(Request.QueryString["ID"]);
String reportsPath = ConfigurationManager.AppSettings["ReportsPath"];
String sReportName = "ReportInvoice";
reportViewer1.Reset();
reportViewer1.ProcessingMode = ProcessingMode.Remote;
reportViewer1.ShowParameterPrompts = false;
reportViewer1.ServerReport.ReportServerUrl = new Uri(ConfigurationManager.AppSettings["ReportViewerUrl"]);
reportViewer1.ServerReport.ReportServerCredentials = new ReportServerCredentials();//http://localhost/reportserver
reportViewer1.AsyncRendering = false;
ReportParameter[] reportParams = new ReportParameter[1];
reportViewer1.ServerReport.ReportPath = reportsPath + sReportName;
reportParams[0] = new ReportParameter("invoiceID", iID.ToString());
reportViewer1.ServerReport.Refresh();
}
}
```
Thanks in advance. | See [this MSDN page](http://msdn.microsoft.com/en-us/library/ms153977%28SQL.90%29.aspx) (SQL 2005 version, but 2008 is the same, I believe). | I read through alot of the MSDN articles on the web based report viewer and tried several ways to fire off the search but only found this one to work:
First, in code you can set the search text box like so:
```
TextBox txt;
txt = (TextBox) this.ReportViewer1.Controls[1].Controls[4].Controls[0];
txt.Text = "test";
```
I did it in the ReportViewer's PreRender event. Position 1 in the first control list is the toolbar control, #4 is the search group control and then in that group the first control is the text box. The second number (4) could vary based on what you are showing / not showing in the toolbar. I was working with the default report viewer settings. It's a hack but it works.
Then I tried firing off the search event myself but this didn't result in the search working although it did fire off the event and with the correct information....
So here's what I did.
I created a javascript function:
```
<script type="text/javascript">
function OnFirstLoad() {
if (!isPostBack)
document.getElementById('ReportViewer1').ClientController.ActionHandler('Search', document.getElementById('ReportViewer1_ctl01_ctl04_ctl00').value);
}
</script>
```
I read the source of the .aspx page and found the text "find" and figured out what the client side call was. You will notice the ctl01 & ctl04 and ctl00 follow the same numbering as the server side code. You would need to change this to reflect your code. Again the second one (ctl04) is the one that is likely to change depending on how your toolbar is setup.
I then set the onload event for the body of the page to the javascript function:
```
<body onload="OnFirstLoad();">
```
The last trick was to only call this code the first time. So I added this to the page load event of the form code behind:
```
If (!IsPostBack)
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = false;", true);
else
ClientScript.RegisterClientScriptBlock(GetType(), "IsPostBack", "var isPostBack = true;", true);
```
This creates a variable that the javascript function checks. On the first go round it's false so it calls the report viewers search function, otherwise it's true and doesn't fire.
This is a pretty bad hack in my opinion and fragile. Changes of the report viewer's toolbar settings may require changes to the javascript and the code to set the text box.
I created a report that had several pages and the first hit wasn't until the third page and it went straight to it. From there the next button worked great until the end of the report.
To bad it's not as simple as the windows based report viewer or the server based report viewer. :)
Good Luck! | Sql Reporting services - find item in report - on load | [
"",
"c#",
"asp.net",
"sql-server",
"reporting-services",
""
] |
I have an object that has a generic IList in it that is being returned from a WCF web service method:
```
[DataContract(Name = "PageableList_Of_{0}")]
public class PageableResults<T>
{
[DataMember]
public IList<T> Items { get; set; }
[DataMember]
public int TotalRows { get; set; }
}
[OperationContract]
PageableResults<ContentItem> ListCI();
```
When I call this method on the service it executes the entire method fine, but at the very end it throws a System.ExecutionEngineException without an InnerException. I've tried returning a concrete List<> object and that seems to work, but unfortunately I need to find a workaround to return an IList. Are there any attributes I need to put in to solve this? | You'll have to add KnownTypes attribute on the class definition above your class definition for each usage of T. Like this:
```
[KnownType(typeof(ContentItem))]
[DataContract(Name = "PageableList_Of_{0}")]
public class PageableResults<T>
{
[DataMember]
public IList<T> Items { get; set; }
[DataMember]
public int TotalRows { get; set; }
}
[OperationContract]
PageableResults ListCI();
```
Alternatively you can define your own collection class, that has a TotalRows property, like this:
```
[KnownType(typeof(ContentItem))]
[DataContract(Name = "PageableList_Of_{0}")]
public class PageableResults<T> : EntityCollectionWorkaround<T>
{
[DataMember]
public int TotalRows { get; set; }
}
```
Where EntityCollectionWorkaround is defined here:
<http://borismod.blogspot.com/2009/06/v2-wcf-collectiondatacontract-and.html> | I don't think you can do this. How will the serializer know what to desearialize to? Lots of things could implement an IList, and an interface doesn't have a constructor. | WCF IList Serialization Issue | [
"",
"c#",
"wcf",
"web-services",
""
] |
I'm not sure what I'm wanting to do is even a good idea, but here's the problem anyway: I have `MyClass` which I want to implement two different types of the generic `IEnumerable` class, e.g.
```
public class MyClass : IEnumerable<KeyValuePair<string, string>>,
IEnumerable<KeyValuePair<MyEnum, string>>
```
Now, the problem with doing this is when I try to define necessary methods from the interfaces, the compiler complains "Type 'MyClass' already defines a member called 'GetEnumerator' with the same parameter types". This is because I have these two methods:
```
public IEnumerator<KeyValuePair<MyEnum, string>> GetEnumerator() { ... }
public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { ... }
```
I have to have `GetEnumerator()` with no parameters because of the interface, and the only thing that differs is the return type, which is not allowed.
Here are what I see as my options:
1. I was considering having a "main" `IEnumerable` generic type which `MyClass` would implement, and then just adding extra methods that differ by parameters and not just return type (e.g. `Add`), without implementing the extra generic interfaces.
2. I could create a generic base class for `MyClass`, call it `MyBaseClass<T>`, and it would implement `IEnumerable<KeyValuePair<T, string>>`. Then, I would have different versions of `MyClass`, e.g. `MyClass<string>` and `MyClass<MyEnum>`.
Which seems preferable here, or am I missing something that would be an even better solution? | You can use explicit interface declarations in order to get different implementations for each of the two interfaces that you are implement. For example:
```
public class MyClass : IEnumerable<KeyValuePair<string, string>>,
IEnumerable<KeyValuePair<MyEnum, string>>
{
IEnumerator<KeyValuePair<MyEnum, string>> IEnumerable<KeyValuePair<MyEnum, string>>.GetEnumerator()
{
// return your enumerator here
}
IEnumerator<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator()
{
// return your enumerator here
}
IEnumerator IEnumerable.GetEnumerator()
{
var me = this as IEnumerable<KeyValuePair<string, string>>;
return me.GetEnumerator();
}
}
```
However, because IEnumerable<> derives from IEnumerable, you'll have to pick which one you want to return from the IEnumerable.GetEnumerator() call. | You can explicity implement each interface like this:
```
IEnumerable<KeyValuePair<string, string>> IEnumerable<KeyValuePair<string, string>>.GetEnumerator() { ... }
IEnumerator<KeyValuePair<MyEnum, string>> IEnumerator<KeyValuePair<MyEnum, string>>.GetEnumerator() { ... }
``` | C# implement two different generic interfaces | [
"",
"c#",
"generics",
"interface",
""
] |
I am looking for a spell checker for c++ source code. Unfortunately all I can find is Visual Studio specific. I would like something which works on Linux.
## Edit:
Ultimately I want to automate it in some way. I am not very proficient in spell checking, but what I am thinking of is a not-interactive console tool which prints error messages, or something like that.
Personally I use vim, but not everyone on the project does of course.
Currently we are using svn so it is possible to integrate it into the pre-commit-hook maybe?
Don't you guys do something similar? | I found something!
```
svn co svn://anonsvn.kde.org/home/kde/trunk/quality/krazy2 krazy2
```
this is part of the quality management of KDE.
Besides a multitude of checks (KDE-specific, qt-specific, cpp-specific, ...) there is automated spell checking.
hope this helps | Eclipse (Java based so will do mac, linux etc.) has spellcheckers built in. With the CDT plugin you can edit and build C++ code. | Spell checker for comments, strings, maybe more | [
"",
"c++",
"c",
"linux",
"spell-checking",
""
] |
What are the advantages and disadvantages of storing JSON data in MySQL database vs. serialized array? | 1. JSON [encode](http://www.php.net/manual/en/function.json-encode.php "json_encode")() & [decode](http://www.php.net/manual/en/function.json-decode.php "json_decode")()
* PHP Version >= 5.0.0
+ Nesting Limit of 20.
* PHP Version >= 5.2.3
+ Nesting Limit of 128.
* PHP Version >= 5.3.0
+ Nesting Limit of 512.
* Small footprint vs PHP's serialize'd string.
2. [serialize](http://www.php.net/manual/en/function.serialize.php "serialize")() & [unserialize](http://www.php.net/manual/en/function.unserialize.php "unserialize")()
* PHP Version >= 4.0.0
+ Methods are not lost on PHP Datatype Object.
+ \_\_wakeup() magic method called on any object being unserialize. (VERY POWERFUL)
+ It has been noted that it is some times best the [base64 encode](http://php.net/manual/en/function.base64-encode.php "base64_encode") strings put into the database, and [base64 decode](http://php.net/manual/en/function.base64-decode.php "base64_decode") strings taken out of the database with this function, as there are some issues with the handling of some white space characters.
The choice is yours. | ## Pro JSON:
* The JSON data can be used by many different languages, not just PHP
* JSON data is human readable and writable.
* It takes up less space
* It is faster to encode JSON than to serialize
## Pro Serialized Array:
* It is faster do unserialize than to JSON decode
---
As the comments indicate, JSON takes up less space than a serialize array. I also checked whether JSON or Serializing is faster, and surprisingly, it is faster to JSON encode than to Serialize. It is faster to unserialize than to JSON decode though.
This is the script I used to test:
```
<?php
function runTime(){
$mtime = microtime();
$mtime = explode(' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
return $mtime;
}
?>
<pre>
<?php
$start = runTime();
$ser;
for($i=0; $i<1000; $i++){
$a = array(a => 1, x => 10);
$ser = serialize($a);
}
$total = runTime() - $start;
echo "Serializing 1000 times took \t$total seconds";
?>
<?php
$start = runTime();
$json;
for($i=0; $i<1000; $i++){
$a = array(a => 1, x => 10);
$json = json_encode($a);
}
$total = runTime() - $start;
echo "JSON encoding 1000 times took \t$total seconds";
?>
<?php
$start = runTime();
$ser;
for($i=0; $i<1000; $i++){
$a = unserialize($ser);
}
$total = runTime() - $start;
echo "Unserializing 1000 times took \t$total seconds";
?>
<?php
$start = runTime();
$json;
for($i=0; $i<1000; $i++){
$a = json_decode($json);
}
$total = runTime() - $start;
echo "JSON decoding 1000 times took \t$total seconds";
?>
</pre>
``` | JSON vs. Serialized Array in database | [
"",
"php",
"mysql",
"serialization",
"mysql-json",
""
] |
I have the query below that fetches 500 records according to certain criteria. The fact that there are many rows (millions). I want to get total number of records so I can say "display 500 out of .... rows". Can I do this with this query? currently I have separate query to do that but I was wondering if I can do it in same query.
Cheers,
Tam
The Query:
```
SELECT * FROM APPL_PERF_STATS
WHERE (GENERIC_METHOD_NAME != 'NULL' AND CURRENT_APPL_ID != 'NULL' AND EVENT_NAME != 'NULL')
AND ROWNUM < 500
AND current_appl_id LIKE '%OrderingGUI%'
AND event_name LIKE '%/ccui%'
AND generic_method_name LIKE '%com.telus.customermgt.service.CustomerMgtSvc.getCustomer%' AND appl_perf_interval_typ_id = 1440
AND cover_period_start_ts >= to_date('06-07-2008 11:53','dd-mm-yyyy HH24:mi')
AND cover_period_start_ts <= to_date('11-08-2009 11:53','dd-mm-yyyy HH24:mi')
ORDER BY CURRENT_APPL_ID, EVENT_NAME, GENERIC_METHOD_NAME, CREATE_TS
``` | In practice, when I am given such a problem I generally select one more than I am willing to display (say 500, so pull 501), and if I reached this amount then tell the user "More than 500 records were returned" which gives the user the ability to refine the query. You could run a count of the query first, then return top n rows, but that will require another trip to the server and depending on query complexity and data volume, may take a long time.
Another method would be to add to a statistics table counts which you can sum up right before you execute this query. The theory is that your statistics table would hold much less data than your primary tables and therefore can be mashed by the server quickly. If you write a process (stored procedures work best) to update these and then return your results.
I'm not sure about your application, or your users. But mine generally either don't care about the total amount of records, or want only the total amount of records and don't want the detail. | In Oracle at least you can do this using analytic functions:
For example:
```
select
count(*) over (partition by null) total_num_items,
p.*
from
APPL_PERF_STATS p
where
...
```
Note that (as APC mentioned) you'll need to embed the ordered query in a sub-query before using ROWNUM to restrict the output to *n* lines.
Although this is a method of getting the total number of lines in the returned resultset, in the background Oracle will be counting all the rows. So, if there are "millions of rows" then there will be a performance hit. If the performance hit is excessive, the approach I'd use would be to pre-aggregate the total row count as a separate batch job. You may find materialized views useful if this is the case. | Getting total number of records while fetching limited set - Oracle | [
"",
"sql",
"oracle",
""
] |
For some reason this PHP code below will not work, I can not figure it out.
It is very strange,
file\_exists does not seem to see that the image does exist, I have checked to make sure a good file path is being inserted into the file\_exists function and it is still acting up
If I change file\_exists to !file\_exists it will return an images that exist and ones that do not exist
```
define('SITE_PATH2', 'http://localhost/');
$noimg = SITE_PATH2. 'images/userphoto/noimagesmall.jpg';
$thumb_name = 'http://localhost/images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if (file_exists($thumb_name)) {
$img_name = $thumb_name;
}else{
$img_name = $noimg;
}
echo $img_name;
``` | `file_exists()` needs to use a file path on the hard drive, not a URL. So you should have something more like:
```
$thumb_name = $_SERVER['DOCUMENT_ROOT'] . 'images/userphoto/1/2/2/59874a886a0356abc1_thumb9.jpg';
if(file_exists($thumb_name)) {
some_code
}
```
<https://www.php.net/file_exists> | [docs](http://docs.php.net/file_exists) say:
> As of PHP 5.0.0, this function can also be used with **some** URL wrappers. Refer to [List of Supported Protocols/Wrappers](http://docs.php.net/manual/en/wrappers.php) for a listing of which wrappers support [`stat()`](http://docs.php.net/manual/en/function.stat.php) family of functionality. | PHP's file_exists() will not work for me? | [
"",
"php",
"file-exists",
""
] |
I wanna to declare an array:
int a[256][256][256]
And the program hang. (I already comment out all other codes...)
When I try int a[256][256], it runs okay.
I am using MingW C++ compiler, Eclipse CDT.
My code is:
int main(){
int a[256][256][256];
return 0;
}
Any comment is welcomed. | This might happen if your array is local to a function. In that case, you'd need a stack size sufficient to hold 2^24 ints (2^26 bytes, or 64 MB).
If you make the array a global, it should work. I'm not sure how to modify the stack size in Windows; in Linux you'd use "ulimit -s 10000" (units are KB).
If you have a good reason not to use a global (concurrency or recursion), you can use malloc/free. The important thing is to either increase your stack (not a good idea if you're using threads), or get the data on the heap (malloc/free) or the static data segment (global).
Ideally you'd get program termination (core dump) and not a hang. I do in cygwin. | Maybe you don't have 16MB of free continuous memory? Kind of hard to imagine but possible... | multidimensional array in C++ hang | [
"",
"c++",
"multidimensional-array",
"eclipse-cdt",
""
] |
I am developing a heavily scripted Web application and am now doing some Error handling. But to do that, I need a way to access the AJAX parameters that were given to jQuery for that specific AJAX Request. I haven't found anything on it at jquery.com so I am asking you folks if you have any idea how to accomplish that.
Here is an example of how I want to do that codewise:
```
function add_recording(filename) {
updateCounter('addRecording','up');
jQuery.ajax({
url: '/cgi-bin/apps/ajax/Storyboard',
type: 'POST',
dataType: 'json',
data: {
sid: sid,
story: story,
screen_id: screen_id,
mode: 'add_record',
file_name: filename
},
success: function(json) {
updateCounter('addRecording','down');
id = json[0].id;
create_record(id, 1, 1, json);
},
error: function() {
updateCounter('addRecording','error',hereBeData);
}
})
}
```
hereBeData would be the needed data (like the url, type, dataType and the actual data).
updateCounter is a function which updates the Status Area with new info. It's also the area where the User is notified of an Error and where a Dismiss and Retry Button would be generated, based on the Info that was gathered in hereBeData. | Regardless of calling `complete()` `success()` or `error()` - `this` will equal the object passed to $.ajax() although the values for URL and data will not always be exactly the same - it will convert paramerters and edit the object around a bit. You can add a custom key to the object to remember your stuff though:
```
$.ajax({
url: '/',
data: {test:'test'},
// we make a little 'extra copy' here in case we need it later in an event
remember: {url:'/', data:{test:'test'}},
error: function() {
alert(this.remember.data.test + ': error');
},
success: function() {
alert(this.remember.data.test + ': success');
},
complete: function() {
alert(this.remember.data.url + ': complete');
}
});
```
Of course - since you are setting this data originally from some source - you could rely on the variable scoping to keep it around for you:
```
$("someelement").click(function() {
var theURL = $(this).attr('href');
var theData = { text: $(this).text(); }
$.ajax({
url: theUrl,
data: theData,
error: function() {
alert('There was an error loading '+theURL);
}
});
// but look out for situations like this:
theURL = 'something else';
});
``` | Check out what parameters you can get in the [callback for error](http://docs.jquery.com/Ajax/jQuery.ajax#options).
```
function (XMLHttpRequest, textStatus, errorThrown) {
// typically only one of textStatus or errorThrown
// will have info
this; // the options for this ajax request
}
``` | Save temporary Ajax parameters in jQuery | [
"",
"javascript",
"jquery",
"ajax",
"web-applications",
""
] |
I am trying to implement the Ajax feature in the comments section of my blog. I have downloaded prototype-1.6.0.3.js and have placed it in the js folder inside webroot.
I have made the following changes in the layout file(default.ctp)
```
$javascript->link(array('prototype'));
```
Also, following code has been added to controllers
```
var $helpers = array('Html', 'Form', 'Ajax','Javascript');
```
This is my code in the posts\_controller.php file
```
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid Post.', true));
$this->redirect(array('action'=>'index'));
}
$post = $this->Post->read(null,$id);
$comments = $this->Post->Comment->find('all',
array('conditions'=>array('Post.id'=>$id)));
$this->set(compact('post','comments'));
}
```
My code in view.ctp file
```
<h2>Comments</h2>
<div id="comments">
<?php foreach($comments as $comment): ?>
<div class="comment">
<p><b><?php echo $comment['Comment']['name']; ?></b></p>
<p><?php echo $comment['Comment']['content']; ?></p>
</div>
<?php endforeach; ?>
<?php echo $ajax->form('/comments/add','post',array('update'=>'comments'));?>
<?php echo $form->input('Comment.name');?>
<?php echo $form->input('Comment.content');?>
<?php echo $form->input('Comment.post_id',array('type'=>'hidden','value'=>$post['Post']['id']));?>
<?php echo $form->end('Add Comment');?>
</div>
```
I have added the following function in the comments\_controller.php
```
function add() {
if (!empty($this->data)) {
$this->Comment->create();
if ($this->Comment->save($this->data)) {
$comments = $this->Comment->find('all',array('conditions'=>array('post_id'=>$this->data['Comment']['post_id']),'recursive'=>-1);
$this->set(compact('comments'));
$this->render('add_success','ajax');
} else {
$this->render('add_failure','ajax');
}
}
}
```
And following is the code in the add\_success.ctp file
```
<?php foreach($comments as $comment): ?>
<div class="comment">
<p><b><?php echo $comment['Comment']['name'];?></b></p>
<p><?php echo $comment['Comment']['content'];?></p>
</div>
<?php endforeach;?>
```
Now the problem is that I am not able to add comments. Nothing happens when I click on the add comments button. I have manually added comments in the databse and that works. But I am having problems when I am trying the Ajax Helper.
Where is the problem??And guys, sorry for such a long question.[:(] | Do you have firebug installed so you can test to see if it is making the ajax request?
Perhaps try doing $form->submit('Add Comment'); to generate the button and see if it makes a difference and actually performs the ajax request.
Do you get any javascript errors? | it looks like you're following the example from ["Beginning CakePHP"](http://apress.com/book/view/9781430209775) I think I made the same error too
it's not mentioned in the book, but the name of the .js file (in webroot/js) must match the helper function argument, so do **one** of these:
1) rename prototype-1.6.0.3.js (inside your webroot/js folder) to prototype.js
OR
2) change the helper function to
```
$javascript->link(array('prototype-1.6.0.3'));
``` | Problem with Ajax Helper in Cake PHP | [
"",
"php",
"cakephp",
""
] |
This seems like an easy thing, but I'm drawing a blank.
```
Select * from
....
inner join
(
select JobsID, Value from Jobs where Value **is the highest**
) as MaxJob on MaxJob.CustID = A.CustID
inner join
(
select other information based upon MaxJob.JobID
) as OtherStuff
```
Is there a nice way to have that first subquery give me the Job ID of the job with the maximum Value?
Thanks... this seems easy and I'm sure I'm overlooking something very elementary. One of those days...
Edit: Due to this question being a bit ambiguous, I've written up a much more detailed question [here](https://stackoverflow.com/questions/1258469/sql-server-2005-syntax-help-select-info-based-upon-max-value-of-sub-query) (since this question was answered correctly). | If you want the single JobId with the highest Value:
```
SELECT JobId FROM Jobs WHERE Value = SELECT MAX(Value) FROM Jobs
```
But, that may give you multiple JobIds if thay all have the same Value. So, assuming you don't want that, I'd probably do:
```
SELECT MAX(JobId) as JobId FROM Jobs WHERE Value = SELECT MAX(Value) FROM Jobs
``` | ```
Select top 1 JobId, Value from Jobs order by Value desc
```
This may result in a worse performance than max(Value), but it is less code | SQL Sub-query -- Select JobID with a maximum JobValue | [
"",
"sql-server",
"sql-server-2005",
"sql-server-2008",
"sql",
""
] |
In C#, how does one obtain a generic enumerator from a given array?
In the code below, `MyArray` is an array of `MyType` objects. I'd like to obtain `MyIEnumerator` in the fashion shown,
but it seems that I obtain an empty enumerator (although I've confirmed that `MyArray.Length > 0`).
```
MyType[] MyArray = ... ;
IEnumerator<MyType> MyIEnumerator = MyArray.GetEnumerator() as IEnumerator<MyType>;
``` | Works on 2.0+:
```
((IEnumerable<MyType>)myArray).GetEnumerator()
```
Works on 3.5+ (fancy LINQy, a bit less efficient):
```
myArray.Cast<MyType>().GetEnumerator() // returns IEnumerator<MyType>
``` | You can decide for yourself whether casting is ugly enough to warrant an extraneous library call:
```
int[] arr;
IEnumerator<int> Get1()
{
return ((IEnumerable<int>)arr).GetEnumerator(); // <-- 1 non-local call
// ldarg.0
// ldfld int32[] foo::arr
// castclass System.Collections.Generic.IEnumerable`1<int32>
// callvirt instance class System.Collections.Generic.IEnumerator`1<!0> System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator()
}
IEnumerator<int> Get2()
{
return arr.AsEnumerable().GetEnumerator(); // <-- 2 non-local calls
// ldarg.0
// ldfld int32[] foo::arr
// call class System.Collections.Generic.IEnumerable`1<!!0> System.Linq.Enumerable::AsEnumerable<int32>(class System.Collections.Generic.IEnumerable`1<!!0>)
// callvirt instance class System.Collections.Generic.IEnumerator`1<!0> System.Collections.Generic.IEnumerable`1<int32>::GetEnumerator()
}
```
And for completeness, one should also note that the following is not correct--and will crash at runtime--because `T[]` chooses the *non*-generic `IEnumerable` interface for its default (i.e. non-explicit) implementation of `GetEnumerator()`.
```
IEnumerator<int> NoGet() // error - do not use
{
return (IEnumerator<int>)arr.GetEnumerator();
// ldarg.0
// ldfld int32[] foo::arr
// callvirt instance class System.Collections.IEnumerator System.Array::GetEnumerator()
// castclass System.Collections.Generic.IEnumerator`1<int32>
}
```
The mystery is, why doesn't `SZGenericArrayEnumerator<T>` inherit from `SZArrayEnumerator`--an internal class which is currently marked 'sealed'--since this would allow the (covariant) generic enumerator to be returned by default? | obtain generic enumerator from an array | [
"",
"c#",
"arrays",
"generics",
"ienumerator",
""
] |
Using the command line:
```
"xsd.exe" "OFX 2.1.1 schema/OFX2_Protocol.xsd" /c /namespace:OFX /nologo"
```
The resulting C# source file fails to build with these errors:
```
D:\blah\OFX2_Protocol.cs(19,6): error CS0579: Duplicate 'System.CodeDom.Compiler.GeneratedCodeAttribute' attribute
D:\blah\OFX2_Protocol.cs(20,6): error CS0579: Duplicate 'System.SerializableAttribute' attribute
D:\blah\OFX2_Protocol.cs(21,6): error CS0579: Duplicate 'System.Diagnostics.DebuggerStepThroughAttribute' attribute
D:\blah\OFX2_Protocol.cs(22,6): error CS0579: Duplicate 'System.ComponentModel.DesignerCategoryAttribute' attribute
D:\blah\OFX2_Protocol.cs(23,6): error CS0579: Duplicate 'System.Xml.Serialization.XmlTypeAttribute' attribute
D:\blah\OFX2_Protocol.cs(24,6): error CS0579: Duplicate 'System.Xml.Serialization.XmlRootAttribute' attribute
```
A similar XSD schema, which I copied from the OFX2 schema then trimmed down to the useful bits that I wanted, generates a C# file which builds just fine, yet has all the same attributes as the full schema's C# representation.
Any idea why? Is the OFX schema broken? Is xsd.exe broken? Is C# broken? Am I broken? | Ok, this answer is a long time coming...
I just ran into the same issue. The problem wasn't in foo.cs, but in foo.designer.cs. You have to remove the duplicate attributes in the second class.
C# should either allow duplicate attributes accross partial classes, or fix xsd to omit attributes in all but the .cs file. | i had the same issue (the same "duplicate attributes" problem) with different schemas. the reason was due to 2 xsd schemas (2 generated files) and in each of them i had the same "type" of element, but with different definitions. renaming of one of the types into different name solved the problem | xsd.exe generates duplicate attributes when run on OFX2 schema | [
"",
"c#",
"xsd.exe",
"ofx",
""
] |
If there are 2 columns in database, eg.
```
code varchar(3)
name nvarchar(50)
```
How to tell hibernate to pass varchar for searching by code?
In the hibernate mappings string is mapped to nvarchar and it produces queries like:
```
Select code, name From table where code=N'AAA' (instead of code='AAA')
```
This is very bad as it causes index scan instead of index seek operation (scanning all index nodes instead of directly going to requested one)
As code is used in millions of rows as well as in several indexes and foreign keys, changing it from varchar to nvarchar will cause performance degradation (more IO operations as nvarchar uses twice more space than varchar).
Is there any way to tell hibernate to do mapping according to database type, not to Java type?
Thanks | ```
<type-mapping>
<sql-type jdbc-type="NVARCHAR" hibernate-type="string" />
</type-mapping>
```
Add the above code in the hibernate reveng file. | Probably you already solved this, but I had a similar problem.
I'm using jTDS JDBC driver and I solved the index scan problem by adding:
```
;sendStringParametersAsUnicode=false;prepareSQL=0
```
to the end of the jTDS connection string.
Probably it would not had solved your problem because by doing this, jTDS will only use VARCHAR (no NVARCHAR anymore).
Also, I had to disable the prepared SQL, because Hibernate is using 'like' instead of '=' when generating the queries and by using 'like' combined with a variable (SELECT ... WHERE column LIKE @var) causes an index scan (MSSQL 2000). | Mapping to varchar and nvarchar in hibernate | [
"",
"sql",
"hibernate",
"varchar",
"nvarchar",
""
] |
Do you know if it is possible to know in a django template if the TEMPLATE\_DEBUG flag is set?
I would like to disable my google analytics script when I am running my django app on my development machine. Something like a {% if debug %} template tag would be perfect. Unfortunately, I didn't find something like that in the documentation.
For sure, I can add this flag to the context but I would like to know if there is a better way to do that. | Assuming you haven't set `TEMPLATE_CONTEXT_PROCESSORS` to some other value in `settings.py`, Django will automatically load the `debug` context preprocessor (as noted [here](https://docs.djangoproject.com/en/stable/ref/templates/api/#using-requestcontext)). This means that you will have access to a variable called `debug` in your templates *if* `settings.DEBUG` is true *and* your local machine's IP address (which can simply be 127.0.0.1) is set in the variable `settings.INTERNAL_IPS` (which is described [here](https://docs.djangoproject.com/en/stable/ref/settings/#internal-ips)). `settings.INTERNAL_IPS` is a tuple or list of IP addresses that Django should recognize as "internal". | If modifying `INTERNAL_IPS` is not possible/suitable, you can do this with a context processor:
in `myapp/context_processors.py`:
```
from django.conf import settings
def debug(context):
return {'DEBUG': settings.DEBUG}
```
in `settings.py`:
```
TEMPLATE_CONTEXT_PROCESSORS = (
...
'myapp.context_processors.debug',
)
```
Then in my templates, simply:
```
{% if DEBUG %} .header { background:#f00; } {% endif %}
``` | How to check the TEMPLATE_DEBUG flag in a django template? | [
"",
"python",
"django",
"templates",
""
] |
What exactly does it mean if a function is defined as virtual and is that the same as pure virtual? | From [Wikipedia's Virtual function](https://en.wikipedia.org/wiki/Virtual_function)
...
> In object-oriented programming, in languages such as C++, and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method for which dynamic dispatch is facilitated. This concept is an important part of the (runtime) polymorphism portion of object-oriented programming (OOP). In short, a virtual function defines a target function to be executed, but the target might not be known at compile time.
Unlike a non-virtual function, when a virtual function is overridden the most-derived version is used at all levels of the class hierarchy, rather than just the level at which it was created. Therefore if one method of the base class *calls* a virtual method, the version defined in the derived class will be used instead of the version defined in the base class.
This is in contrast to non-virtual functions, which can still be overridden in a derived class, but the "new" version will only be used by the derived class and below, but will not change the functionality of the base class at all.
whereas..
> A pure virtual function or pure virtual method is a virtual function that is required to be implemented by a derived class if the derived class is not abstract.
When a pure virtual method exists, the class is "abstract" and can not be instantiated on its own. Instead, a derived class that implements the pure-virtual method(s) must be used. A pure-virtual isn't defined in the base-class at all, so a derived class *must* define it, or that derived class is also abstract, and can not be instantiated. Only a class that has no abstract methods can be instantiated.
A virtual provides a way to override the functionality of the base class, and a pure-virtual *requires* it. | I'd like to comment on Wikipedia's definition of virtual, as repeated by several here. [At the time this answer was written,] Wikipedia defined a virtual method as one that can be overridden in subclasses. [Fortunately, Wikipedia has been edited since, and it now explains this correctly.] That is incorrect: any method, not just virtual ones, can be overridden in subclasses. What virtual does is to give you polymorphism, that is, the **ability to select at run-time the most-derived override of a method**.
Consider the following code:
```
#include <iostream>
using namespace std;
class Base {
public:
void NonVirtual() {
cout << "Base NonVirtual called.\n";
}
virtual void Virtual() {
cout << "Base Virtual called.\n";
}
};
class Derived : public Base {
public:
void NonVirtual() {
cout << "Derived NonVirtual called.\n";
}
void Virtual() {
cout << "Derived Virtual called.\n";
}
};
int main() {
Base* bBase = new Base();
Base* bDerived = new Derived();
bBase->NonVirtual();
bBase->Virtual();
bDerived->NonVirtual();
bDerived->Virtual();
}
```
What is the output of this program?
```
Base NonVirtual called.
Base Virtual called.
Base NonVirtual called.
Derived Virtual called.
```
Derived overrides every method of Base: not just the virtual one, but also the non-virtual.
We see that when you have a Base-pointer-to-Derived (bDerived), calling NonVirtual calls the Base class implementation. This is resolved at compile-time: the compiler sees that bDerived is a Base\*, that NonVirtual is not virtual, so it does the resolution on class Base.
However, calling Virtual calls the Derived class implementation. Because of the keyword virtual, the selection of the method happens at *run-time*, not compile-time. What happens here at compile-time is that the compiler sees that this is a Base\*, and that it's calling a virtual method, so it insert a call to the vtable instead of class Base. This vtable is instantiated at run-time, hence the run-time resolution to the most-derived override.
I hope this wasn't too confusing. In short, any method can be overridden, but only virtual methods give you polymorphism, that is, run-time selection of the most derived override. In practice, however, overriding a non-virtual method is considered bad practice and rarely used, so many people (including whoever wrote that Wikipedia article) think that only virtual methods can be overridden. | Virtual/pure virtual explained | [
"",
"c++",
"virtual",
""
] |
For any custom dialog (form) in a WinForm application I can set its size and position before I display it with:
```
form.StartPosition = FormStartPosition.Manual;
form.DesktopBounds = MyWindowPosition;
```
This is particularly important when dealing with multiple monitors. Without such code, when you open a dialog from an application that you have dragged to a second monitor, the dialog appears on the primary monitor. This presents a poor user experience.
I am wondering if there are any hooks to set the position for the standard .NET OpenFileDialog and SaveFileDialog (which do not have a StartPosition property). | I suspect that the best you can do is make sure you use the [overload of `ShowDialog`](http://msdn.microsoft.com/en-us/library/9a55b9ds.aspx) that accepts an `IWin32Window` to use as the parent. This *might* help it choose an appropriate location; most commonly:
```
using(var dlg = new OpenFileDialog()) {
.... setup
if(dlg.ShowDialog(this) == DialogResult.OK) {
.... use
}
}
``` | Check out [this article](http://www.codeproject.com/KB/dialog/OpenFileDialogEx.aspx?display=Print) on CodeProject. Excerpt:
> Here is when the handy .NET
> NativeWindow comes into the picture, a
> NativeWindow is a window wrapper where
> it processes the messages sent by the
> handle associated to it. It creates a
> NativeWindow and associates the
> OpenFileWindow handle to it. From this
> point, every message sent to
> OpenFileWindow will be redirected to
> our own WndProc method in the
> NativeWindow instead, and we can
> cancel, modify, or let them pass
> through.
>
> In our WndProc, we process the message
> WM\_WINDOWPOSCHANGING. If the open
> dialog is opening, then we will change
> the original horizontal or vertical
> size depending of the StartLocation
> set by the user. It will increment the
> size of the window to be created. This
> happens only once when the control is
> opened.
>
> Also, we will process the message
> WM\_SHOWWINDOW. Here, all controls
> inside the original OpenFileDialog are
> created, and we are going to append
> our control to the open file dialog.
> This is done by calling a Win32 API
> SetParent. This API lets you change
> the parent window. Then, basically
> what it does is attach our control
> to the original OpenFileDialog in the
> location it set, depending on the
> value of the StartLocation property.
>
> The advantage of it is that we still
> have complete control over the
> controls attached to the
> OpenFileDialog window. This means we
> can receive events, call methods, and
> do whatever we want with those
> controls. | Setting the start position for OpenFileDialog/SaveFileDialog | [
"",
"c#",
"winforms",
"openfiledialog",
"multiple-monitors",
""
] |
In this snippet:
```
class ClassWithConstants
{
private const string ConstantA = "Something";
private const string ConstantB = ConstantA + "Else";
...
}
```
Is there a risk of ending up with `ConstantB == "Else"`? Or do the assigments happen linearly? | You will always get "SomethingElse". This is because ConstantB depends upon ConstantA.
You can even switch lines and you'll get the same result. The compiler knows that ConstantB depends upon ConstantA and will handle it accordingly, even if you write it in partial classes.
To be completely sure you can run VS Command Prompt and call ILDASM. There you can see the actual compiled code.
Additionally, if you try to do the following you'll get a compile error:
```
private const string ConstantB = ConstantA + "Else";
private const string ConstantA = "Something" + ConstantB;
```
**Error**: The evaluation of the constant value for 'ConsoleApplication2.Program.ConstantB' involves a circular definition
This sort of proves the compiler knows its dependencies.
---
Added: Spec reference pointed out by [Jon Skeet](https://stackoverflow.com/users/22656/jon-skeet):
> This is explicitly mentioned in section 10.4 of the C# 3 spec:
> Constants are permitted to depend on other constants within the same program as long as the dependencies are not of a circular nature. The compiler automatically arranges to evaluate the constant declarations in the appropriate order.
>
> --- | this string concatenation happens at compile-time because there are only string literals (search for **constant folding** in compiler construction literature).
Don't worry about it. | C#: Is this field assignment safe? | [
"",
"c#",
"constants",
"field",
"variable-assignment",
""
] |
What does the colon operator (":") do in this constructor? Is it equivalent to `MyClass(m_classID = -1, m_userdata = 0);`?
```
class MyClass {
public:
MyClass() : m_classID(-1), m_userdata(0) {
}
int m_classID;
void *m_userdata;
};
``` | This is a **member initializer list**, and is part of the constructor's implementation.
The constructor's signature is:
```
MyClass();
```
This means that the constructor can be called with no parameters. This makes it a *default constructor*, i.e., one which will be called by default when you write `MyClass someObject;`.
The part `: m_classID(-1), m_userdata(0)` is called **member initializer list**. It is a way to initialize some fields of your object (all of them, if you want) with values of your choice.
After executing the member initializer list, the constructor body (which happens to be empty in your example) is executed. Inside it you could do more assignments, but once you have entered it all the fields have already been initialized - either to random, unspecified values, or to the ones you chose in your initialization list. This means the assignments you do in the constructor body will not be initializations, but changes of values. | It is an initialization list.
By the time you get in the body of the constructor, all fields have already been constructed; if they have default constructors, those were already called. Now, if you assign a value to them in the body of the constructor, you are calling the copy assignment operator, which may mean releasing and reacquiring resources (e.g. memory) if the object has any.
So in the case of primitive types like int, there's no advantage compared to assigning them in the body of the constructor. In the case of objects that have a constructor, it is a performance optimization because it avoids going through two object initializations instead of one.
An initialization list is necessary if one of the fields is a reference because a reference can never be null, not even in the brief time between object construction and the body of the constructor. The following raises error C2758: 'MyClass::member\_' : must be initialized in constructor base/member initializer list
```
class MyClass {
public :
MyClass(std::string& arg) {
member_ = arg;
}
std::string& member_;
};
```
The only correct way is:
```
class MyClass {
public :
MyClass(std::string& arg)
: member_(arg)
{
}
std::string& member_;
};
``` | What does a colon following a C++ constructor name do? | [
"",
"c++",
"constructor",
"initialization-list",
"ctor-initializer",
""
] |
My script consists of two parts.
The first part generates HTML page.
The second part loads a resourse from the net and saves it into a file.
Loading is a long operation and can take up to 10 seconds.
The first and the second parts are completely indepenent (loading has no impact on the look of the page).
At the end of the first part I call flush(), that makes page displayed instantly.
However, embedded SWF movie is not displayed at this moment.
SWF is the key element of the page and it must be displayed as fast as possible.
It is embedded in the page with SwfObject library.
And the problem is that SwfObject starts to open SWF on "onLoad" event of the page.
But "onLoad" event comes at the end of the *second* part.
That is "onLoad" can occure in 10 seconds.
So in spite flush() call the user has to wait for 10 seconds in vain.
Is it possible to solve the task on PHP side?
Is it possible to run "loading" task (the second part) in a separate process?
Is it possible to tell the browser before the second part starts, that the page is reay and you can broadcast the "onLoad" event.
Thanks for reading this very long story. | I suggest splitting your code into two separate PHP files:
The first file generates the HTML page containing the SWF.
The second file fetches the resource and saves it.
The trick is that in the onLoad event of the first page you run a small snippet of JavaScript which requests the URL of the second page.
The code in the first page would look something like this:
```
...
<body onload="makeRequest('page2.php')">
...
```
where makeRequest is a function something like the one here: <http://www.captain.at/howto-ajax-form-post-get.php>
This [AJAX Tutorial](http://www.w3schools.com/Ajax/default.asp) make be helpful for understanding that.
Of course, if these things are truly independent you should look at running the second one in a separate process or thread. [pcntl-fork](https://www.php.net/manual/en/function.pcntl-fork.php) may help here. | PHP doesn't support threading so you would have to write a script that will do the second part and run it using `exec()` method. But that's probably not the best solution as well.
What you probably can do is forget about move the second part that takes long time to separate script or controller action if you are using MVC controllers. Then just run the first part and your page will load quickly. Then you can add a AJAX to call that new script/action to run the second part of your algorithm after your page has loaded. | PHP: How to display page before the script is over? | [
"",
"php",
""
] |
If I have an object with an array as an attribute, what is the easiest way to access it?
```
$obj->odp = array("ftw", "pwn", array("cool" => 1337));
//access "ftw"
$obj->odp->0
//access 1337
$obj->odp->2->cool
```
This doesn't seem to work. Is there something I'm doing wrong, or do I have to first assign it to a variable?
```
$arr = $obj->odp;
//access "ftw"
$arr[0]
//access 1337
$arr[2]["cool"]
``` | Arrays can only be accessed with the array syntax (`$array['key']`) and objects only with the object syntax (`$object->property`).
Use the object syntax only for objects and the array syntax only for arrays:
```
$obj->odp[0]
$obj->odp[2]['cool']
``` | Do it like this:
```
$obj->odp[0]['cool']
``` | PHP: Arrays as Attributes | [
"",
"php",
"arrays",
"object",
"attributes",
""
] |
I am going to play a devil's advocate for a moment. I have been always wondering why browser detection (as opposed to feature detection) is considered to be a flat out as a bad practise. If I test a certain version of certain browser and confirm that, that certain functionality behaves is in some predictable way then it seems OK to decide to do special case it. The reasoning is that it will be in future foolproof, because this partial browser version is not going to change. On the other hand, if I detect that a DOM element has a function X, it does not necessarily mean that:
1. This function works the same way in all browsers, and
2. More crucially, it will work the same way even in all future browsers.
I just peeked into the jQuery source and they do feature detection by inserting a carefully constructed snippet of HTML into DOM and then they check it for certain features. It’s a sensible and solid way, but i would say that it would be a bit too heavy if i just did something like this in my little piece of personal JavaScript (without jQuery). They also have the advantage of practically infinite QA resources. On the other hand, what you often see people doing is that they check for the existence of function X, and then based on this, they assume the function will behave certain way in all browsers which have this function.
I’m not saying anything in the sense that feature detection is not a good thing (if used correctly), but I wonder why browser detection is usually immediately dismissed even if it sounds logical. I wonder whether it is another trendy thing to say. | It seems to me browser detection has been widely frowned upon since [this post](http://ejohn.org/blog/future-proofing-javascript-libraries/) by Resig a couple of years ago. Resig's comments however were specific to libraries/framework code, i.e. code that will be *consumed* by other [domain-specific] applications/sites.
I think feature detection is without question a good fit *for libraries/frameworks*. For domain-specific applications however I'm not so sure browser detection is that bad. It's suitable for working around known browser characteristics that are difficult to feature-detect, or for browsers that have bugs in their implementation of the feature itself. Times that browser detection is appropriate:
* sites/applications that are not cross-browser and need to show a warning/dialog/DifferentPage tailoring to that client's browser. This is common in legacy applications.
* Banks or private sites with strict policies on what browsers and versions are supported (to avoid known security exploits that may compromise user's data)
* micro-optimizations: occasionally one browser is ridiculously faster than the others when performing some operation a certain way. It can be advantageous depending on your user base to branch on that particular browser/version.
* Lack of png transparency in IE6
* many display/rendering issues (read: IE css support) that are only witnessed in specific browser versions and you don't actually know what feature to test for.
That said, there are some [major pitfalls](https://developer.mozilla.org/en/Browser_Detection_and_Cross_Browser_Support) (probably committed by most of us) to avoid when doing browser detection. | [Here's a good article](http://www.jibbering.com/faq/faq_notes/not_browser_detect.html) explaining how feature detection is superior in so many ways to browser sniffing.
The truth is that sniffing is extremely fragile. It's fragile in theory, as it relies on an **arbitrary** `userAgent` string and then practically maps that string to a certain behavior. It's also fragile in practice, as time has shown. Testing every major and minor version of dozens of browsers and trying to parse build numbers of some of those versions is not practical at all; Testing certain behavior for quirks, on the other hand, is much more robust. Feature tests, for example, often catch bugs and inconsistencies that browser vendors incidentally copy from each other.
From my own experience, fixing Prototype.js in IE8, I know that 90% of the problems could have been avoided if we didn't sniff in the first place.
While fixing Prototype.js I discovered that some of the features that need to be tested are actually very common among JS libraries, so I made a little collection of [common feature tests](http://kangax.github.com/cft/) for anyone willing to get rid of sniffing. | Browser detection versus feature detection | [
"",
"javascript",
"html",
"dom",
"cross-browser",
""
] |
I'm using the jQuery plugin [Validation](http://plugins.jquery.com/project/validate) to validate a form. I have a select list looking like this:
```
<select id="select">
<option value="">Choose an option</option>
<option value="option1">Option1</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
</select>
```
Now, I want to make sure that the user selects anything but "Choose an option" (which is the default one). So that it won't validate if you choose the first option. How can this be done? | Just add a class of required to the select
```
<select id="select" class="required">
``` | For starters, you can "disable" the option from being selected accidentally by users:
```
<option value="" disabled="disabled">Choose an option</option>
```
Then, inside your JavaScript event (doesn't matter whether it is jQuery or JavaScript), for your form to validate whether it is set, do:
```
select = document.getElementById('select'); // or in jQuery use: select = this;
if (select.value) {
// value is set to a valid option, so submit form
return true;
}
return false;
```
Or something to that effect. | Validate select box | [
"",
"javascript",
"jquery",
"html",
"validation",
"forms",
""
] |
[This question](https://stackoverflow.com/questions/546804/select-distinct-from-multiple-fields-using-sql) explained about a way of getting distinct combination of multiple columns. But I want to know the difference between the methods of DISTINCT, UNION, GROUP BY keyword method for this purpose. I am getting different results when using them.
My queries are like this
Query 1.
```
select
column1,
column2,
column3
from table
group by 1,2,3
```
Query 2.
```
select distinct
column1,
column2,
column3
from table
```
Query 3.
```
SELECT DISTINCT(ans) FROM (
SELECT column1 AS ans FROM sametable
UNION
SELECT column2 AS ans FROM sametable
UNION
SELECT column3 AS ans FROM sametable
) AS Temp
```
I am getting different number of rows for above queries(Edit: The first two are giving equal number of rows but last one is giving differnetly). Can any body explain what the above queries are doing? Especially the third one?
**EDIT:** Note that I am doing UNION on same table. In that case what will happen? | Starting with what I think is the simplest, DISTINCT, really is just that. It returns the distinct combinations of rows. Think of this dataset:
```
COL1 COL2 COL3
A B C
D E F
G H I
A B C <- duplicate of row 1
```
This will return 3 rows because the 4th row in the dataset exactly matches the first row.
Result:
```
COL1 COL2 COL3
A B C
D E F
G H I
```
The GROUP BY is frequently used for summaries and other calculations
select COL1, SUM(COL2)
from table
group by column1;
For this dataset:
```
COL1 COL2
A 5
A 6
B 2
C 3
C 4
C 5
```
would return
```
COL1 SUM(COL2)
A 11
B 2
C 12
```
a UNION just takes results from different queries and presents them as 1 result set:
```
Table1
COL1
A
Table2
COLX
B
Table3
WHATEVER_COLUMN_NAME
Giddyup
select COL1 from Table1
UNION
select COLX from Table2
UNION
select WHATEVER_COLUMN_NAME from Table3;
```
Result Set:
```
A
B
Giddyup
```
When performing a union, the column datatypes must match up. You can't UNION a number column with a char column (unless you explicitly perform a data conversion) | Lets assume this is your db data:
```
column1 | column2 | column3
1 | 2 | 1
1 | 2 | 2
1 | 2 | 1
3 | 1 | 2
1 | 2 | 2
1 | 2 | 2
1 | 2 | 2
```
### First query
In the first example you will get all column combinations from the db (as `GROUP BY 1,2,3` does nothing) including duplicates, so it will return:
```
1 | 2 | 1
1 | 2 | 2
1 | 2 | 1
3 | 1 | 2
1 | 2 | 2
1 | 2 | 2
1 | 2 | 2
```
### 2nd query
Second example takes unique values for column tuples so you will end with
```
1 | 2 | 1
1 | 2 | 2
3 | 1 | 2
```
### 3rd query
Last query takes all values from three columns and then it removes duplicates from that set. So you will get all values from any of the tables. In the end this will return
```
1
2
3
```
Does this makes it clear? | What is the difference between group by, distinct, Union for selecting distinct values for multiple columns? | [
"",
"sql",
"group-by",
"union",
"distinct",
""
] |
I have a trivial .Net 2.0 SOAP web service. I want to access it from Silverlight application that is hosted on the same server, but different port. I know that for this to work I need to provide a `clientaccesspolicy.xml` or `crossdomain.xml` policy file (the service is available at `http://example:8085/RemoteObject.rem?wsdl` , so the policy file has to be present at `http://example:8085/crossdomain.xml`). What should I add to the following simple web service to [self-serve the policy file like the WCF example does](http://silverlight.net/forums/p/95440/218611.aspx#3.2_Ho)?
The web service is being run on Mono, although that shouldn't change anything - there's just no IIS involved.
```
using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
namespace ConsoleApplication1
{
class RemoteObject : MarshalByRefObject
{
static void Main()
{
var channel = new HttpChannel(8085);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(RemoteObject), "RemoteObject.rem",
WellKnownObjectMode.Singleton);
Console.WriteLine("Press ENTER to exit the server.");
Console.ReadLine();
}
public DateTime Now()
{
return DateTime.Now;
}
}
}
```
EDIT: because of all the unusable answers, let me repeat myself: I need to do this with .Net 2.0, not 3.0 or 3.5. **WCF is not available**. | **EDIT2**: *my coworker has found a usable solution: [Web Service Enhancements](http://msdn.microsoft.com/en-us/library/aa529246.aspx) from Microsoft. It does need IIS and it has been deprecated with the introduction of WCF, but works well with plain .Net Framework 2.0 and should be deployable with [Mono XSP](http://www.mono-project.com/ASP.NET#ASP.NET_hosting_with_XSP).*
**EDIT**: *solution below is pointless, because .Net 2.0 exposes web services using SOAP 1.1 rpc/encoded model, and Silverlight requires SOAP 1.2 document/literal. So while the workaround works for the problem indicated in the question, the web service still cannot be consumed.*
I managed to make this work without resorting to extreme hacks. The key to my solution was to insert an additional `IServerChannelSink` into the request processing queue. So, I changed
```
var channel = new HttpChannel(8085);
```
to register my custom `IServerChannelSink` before the normal pipeline:
```
var provider = ChainProviders(
new PolicyServerSinkProvider(),
new SdlChannelSinkProvider(),
new SoapServerFormatterSinkProvider(),
new BinaryServerFormatterSinkProvider());
var channel = new HttpChannel(new Hashtable(1) {{"port", 8085}}, null, provider);
```
I use a helper method to chain the sink providers together:
```
private static IServerChannelSinkProvider ChainProviders(
params IServerChannelSinkProvider[] providers)
{
for (int i = 1; i < providers.Length; i++)
providers[i-1].Next = providers[i];
return providers[0];
}
```
`PolicyServerSinkProvider` simply creates a `PolicyServerSink`:
```
internal class PolicyServerSinkProvider : IServerChannelSinkProvider
{
public void GetChannelData(IChannelDataStore channelData){}
public IServerChannelSink CreateSink(IChannelReceiver channel)
{
IServerChannelSink nextSink = null;
if (Next != null)
nextSink = Next.CreateSink(channel);
return new PolicyServerSink(channel, nextSink);
}
public IServerChannelSinkProvider Next { get; set; }
}
```
`PolicyServerSink` delegates all messages down the chain, except when it gets a request for `crossdomain.xml` - then it writes the needed xml into the response stream.
```
internal class PolicyServerSink : IServerChannelSink
{
public PolicyServerSink(
IChannelReceiver receiver, IServerChannelSink nextSink)
{
NextChannelSink = nextSink;
}
public IDictionary Properties { get; private set; }
public ServerProcessing ProcessMessage(
IServerChannelSinkStack sinkStack, IMessage requestMsg,
ITransportHeaders requestHeaders, Stream requestStream,
out IMessage responseMsg, out ITransportHeaders responseHeaders,
out Stream responseStream)
{
if (requestMsg != null || ! ShouldIntercept(requestHeaders))
return NextChannelSink.ProcessMessage(
sinkStack, requestMsg, requestHeaders, requestStream,
out responseMsg, out responseHeaders, out responseStream);
responseHeaders = new TransportHeaders();
responseHeaders["Content-Type"] = "text/xml";
responseStream = new MemoryStream(Encoding.UTF8.GetBytes(
@"<?xml version=""1.0""?><!DOCTYPE cross-domain-policy SYSTEM "
+ @"""http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd"">"
+ @"<cross-domain-policy><allow-access-from domain=""*"" />"
+ @"</cross-domain-policy>")) {Position = 0};
responseMsg = null;
return ServerProcessing.Complete;
}
private static bool ShouldIntercept(ITransportHeaders headers)
{
return ((string) headers["__RequestUri"]).Equals(
"/crossdomain.xml", StringComparison.InvariantCultureIgnoreCase);
}
public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack,
object state, IMessage msg, ITransportHeaders headers, Stream stream)
{
}
public Stream GetResponseStream(IServerResponseChannelSinkStack sinkStack,
object state, IMessage msg, ITransportHeaders headers)
{
throw new NotSupportedException();
}
public IServerChannelSink NextChannelSink { get; private set; }
}
```
This can also be used to serve other files together with the web service. I am currently using this method to host my Silverlight application (the consumer of the web service) without a separate http server. | I dont know much about the deploymnets in MONO. I would suggest a different approach if you didnt find any better approaches for your question.
Instead of directly calling the webservice from silverlight app.. you can invoke a javascript method from your managed silverlight code using
```
string sJson = HtmlPage.Window.Invoke("JSMethod", new string[] { strInParam }) as string;
```
and fire a AJAX request (from JS method) to your server and will internally make a call to the webservice deployed in MONO (from server) and return a JSON formatted result.
I have implemented this approach in my projects and its working fine..
just an alternative.. | How can I expose a .Net 2.0 Webservice to a Silverlight client? | [
"",
"c#",
"silverlight",
"web-services",
".net-2.0",
"mono",
""
] |
I want to reload a page so that it does not cause the effects of a full-page refresh, like displaying "Loading..." on the page's tab.
Here's the code I have so far. My theory was that I could overwrite the `body` section with a `<frame>`-wrapped version of the updated site, gotten via `GM_xmlhttpRequest`.
## reloader.js
```
setInterval(reload, 10000);
function reload() {
GM_xmlhttpRequest({method: 'GET',
url: location.href,
onload: function(responseDetails) {
document.body.innerHTML =
'<frame>\n'
+ responseDetails.responseText
+ '</frame>\n';
}});
}
```
When testing with Firebug on stackoverflow.com, I found that this script updates the `body` *as if I had performed a full-page refresh*, without the side effects. Yay! Mysteriously, the `<frame>` tags are nowhere to be found.
## Questions
What I have right now does a good job of reloading the page, but I have two questions:
1. How do I stay logged in after a reload? Specifically, what do I need to do to keep me logged in to Stack Overflow?
2. Can someone explain *why* my script works? Why are there no `<frame>` tags within the `body`?
## Updates
I've incorporated elements from Cleiton, Havenard, and Henrik's answers so far. I tried sending cookies via the `header: { 'Cookie': document.cookie }` entry in the data sent through `GM_xmlhttpRequest`. This sent some, but not all of the cookies. It turns out that if I turn on third party cookies in the Firefox then I'll get the necessary extra cookies (`.ASPXAUTH`, `ASP.NET_SessionId`, and `user`), but this is a [*bad idea*](http://www.grc.com/cookies.htm). | ```
document.body.innerHTML =
responseDetails.responseText.match(/<body>([\s\S]*)<\/body>/i)[1];
```
Update: For <body> with properties:
```
document.body.innerHTML =
responseDetails.responseText.match(/<body[^>]*>([\s\S]*)<\/body>/i)[1];
``` | @Andrew Keeton,
First install [fiddler](http://www.fiddlertool.com/) in your machine and see if http requests made by GM\_xmlhttpRequest are being sent with *all* cookies. if isnt go to about:config option "network.cookie.cookieBehavior" and set it to 0, do another test. if it works. you will be in trouble because there isnt a safe way to perform this change using greasemonkey and you will have to use @Henrik tricky. | How do I "quietly" reload a page from a Greasemonkey script? | [
"",
"javascript",
"html",
"ajax",
"greasemonkey",
""
] |
I've heard so much about buffer overflows and believe I understand the problem but I still don't see an example of say
```
char buffer[16];
//code that will over write that buffer and launch notepad.exe
``` | First, you need a program that will launch other programs. A program that executes OS `exec` in some form or other. This is highly OS and language-specific.
Second, your program that launches other programs must read from some external source into a buffer.
Third, you must then examine the running program -- as layed out in memory by the compiler -- to see how the input buffer and the other variables used for step 1 (launching other programs) exist.
Fourth, you must concoct an input that will actually overrun the buffer and set the other variables.
So. Part 1 and 2 is a program that looks something like this in C.
```
#include <someOSstuff>
char buffer[16];
char *program_to_run= "something.exe";
void main( char *args[] ) {
gets( buffer );
exec( program_to_run );
}
```
Part 3 requires some analysis of what the `buffer` and the `program_to_run` look like, but you'll find that it's probably just
```
\x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 \x00 s o m e t h i n g . e x e \x00
```
Part 4, your input, then has to be
```
1234567890123456notepad.exe\x00
```
So it will fill `buffer` and write over `program_to_run`. | "Smashing The Stack For Fun And Profit" is the best HowTo/FAQ on the subject.
See: <http://insecure.org/stf/smashstack.html>
Here is a snip of some actual shellcode:
```
char shellcode[] =
"\xeb\x1f\x5e\x89\x76\x08\x31\xc0\x88\x46\x07\x89\x46\x0c\xb0\x0b"
"\x89\xf3\x8d\x4e\x08\x8d\x56\x0c\xcd\x80\x31\xdb\x89\xd8\x40\xcd"
"\x80\xe8\xdc\xff\xff\xff/bin/sh";
char large_string[128];
void main() {
char buffer[96];
int i;
long *long_ptr = (long *) large_string;
for (i = 0; i < 32; i++)
*(long_ptr + i) = (int) buffer;
for (i = 0; i < strlen(shellcode); i++)
large_string[i] = shellcode[i];
strcpy(buffer,large_string);
}
``` | Can you give an example of a buffer overflow? | [
"",
"c++",
"c",
"security",
"buffer-overflow",
""
] |
I have two tables: authorizations and settlements. 'Settlements' contains a forign key reference to authorizations.
A settlement can also have a status (ERROR, ACCEPTED, etc).
Given this data:
```
Authorizations Settlements
id id | auth_id | status
----- ---------------------------
1 1 1 ERROR
2 2 1 ACCEPTED
```
I'm trying to write a SQL query to find all authorizations that don't have an ACCEPTED settlement record. I've tried a LEFT OUTER JOIN, but it returns too many rows. For example:
`SELECT * FROM authorizations a
LEFT OUTER JOIN settlements s ON a.id = s.auth_id
WHERE s.status is null OR s.status != 'ACCEPTED'`
The problem with this is that it will still return an authorization record if it has more than one settlement record, and one of those is ACCEPTED. Or, if there is more than one ERROR record, the authorization will be returned twice.
How can I only fetch *single* authorization records that don't have a corresponding settlement record with a status of "ACCEPTED"? Is it possible with straight SQL, or will I have to filter the results in my code? | ```
SELECT *
FROM authorizations a
WHERE NOT EXISTS
(
SELECT NULL
FROM Settlements s
WHERE s.auth_id = a.id
AND s.status = 'ACCEPTED'
)
``` | Try
```
SELECT a.* FROM authorizations a
LEFT OUTER JOIN (SELECT S.* from settlements s1
WHERE s1.status = 'ACCEPTED')
ON a.id = s.auth_id
WHERE s.auth_id is null
```
This picks out all the records which are accepted and then takes the authorizations which are not inthat group. | Filtering LEFT JOIN results | [
"",
"sql",
"left-join",
""
] |
I am running into a bit of difficulty using the threadpool class and an array of ManualResetEvents. Below is a simple example of what I am doing. The problem is that in the DoWork method I am getting null references to the resetEvent[param as int] object.
Can't seem to figure what I'm doing wrong.
(edit: got the code block working)
```
private static volatile ManualResetEvent[] resetEvents = new ManualResetEvent[NumThreads];
public void UpdateServerData()
{
for (int i = 0; i < NumThreads ; i++)
{
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), (object) i);
}
WaitHandle.WaitAll(resetEvents);
}
private void DoWork(object param)
{
//do some random work
resetEvents[(int)param].Set();
}
```
EDIT: I have tried inserting a System.Threading.Thread.MemoryBarrier(); after each .Set() however i still get a null reference exception. | Pretty much I found the issue was in
```
for (int i = 0; i < NumThreads ; i++)
{
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), resetEvents[i]);
}
```
Instead of declaring a new ManualResetEvent I simply called Reset(). The issue seemed to have been that that although I would use MemoryBarrier or locks, the physical memory wouldn't be updated yet so it would point to null. | You cannot use the `as` keyword to cast to int (since `int` is not a reference type). Use `(int)param` instead:
```
private void DoWork(object param)
{
//do some random work
resetEvents[(int)param].Set();
}
```
Another approach that I feel is cleaner is to pass the wait handle to the method instead:
```
public void UpdateServerData()
{
for (int i = 0; i < NumThreads ; i++)
{
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), resetEvents[i]);
}
WaitHandle.WaitAll(resetEvents);
}
private void DoWork(object param)
{
//do some random work
(param as ManualResetEvent).Set();
}
```
That way the worker method has no knowledge about how the wait handle is managed on the outside; and it also cannot reach wait handles for other threads by mistake. | C# Threadpool Synchronization Inquiry | [
"",
"c#",
"thread-safety",
""
] |
I'm looking for a javascript drop-down for a date range that allows the user to select start and end dates from a single form field, similar to what exists in the Google Analytics UI.
I've found a lot of pre-existing javascript for two separate form fields, or for using a calendar to choose a single date, but nothing that accomplishes what the Google Analytics date range selector does. Does anyone know of a good pre-built tool that does this, or am I stuck building it myself? | There are ExtJs extensions that allow date ranges to be selected.
<http://extjs.com/forum/showthread.php?t=22473>
<http://extjs.com/forum/showthread.php?t=20597> | Perhaps you could check out [jQuery](http://jquery.com), and the UI library which provides the DatePicker control:
<http://jqueryui.com/demos/datepicker/> | Does anyone know of a good pre-existing javascript date range drop-down? | [
"",
"javascript",
"date",
"drop-down-menu",
"date-range",
""
] |
I have a simple `textbox` in which users enter number.
Does jQuery have a `isDigit` function that will allow me to show an alert box if users enter something other than digits?
The field can have decimal points as well. | I would suggest using regexes:
```
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
```
Or with a single regex as per @Platinum Azure's suggestion:
```
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
``` | Forget regular expressions. JavaScript has a builtin function for this: `isNaN()`:
```
isNaN(123) // false
isNaN(-1.23) // false
isNaN(5-2) // false
isNaN(0) // false
isNaN("100") // false
isNaN("Hello") // true
isNaN("2005/12/12") // true
```
Just call it like so:
```
if (isNaN( $("#whatever").val() )) {
// It isn't a number
} else {
// It is a number
}
``` | checking if number entered is a digit in jquery | [
"",
"javascript",
"jquery",
"validation",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.