Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a table in database that is having unique id's.
I have a page where one particular id is shown and link is given for next and previous id's.
I have to get those prev and next id's by one single mysql query .All i have is that particular id on whose data we are currently working on.
id's are not consecutive numbers as sometimes some id's get deleted also.(for eg. 1,2,3,7,9,10,15 etc)
So how can i get these two previous and next id's in one single query???? | ```
SELECT
(SELECT id FROM YourTable WHERE id < YourId ORDER BY id DESC LIMIT 1) AS prev,
(SELECT id FROM YourTable WHERE id > YourId ORDER BY id ASC LIMIT 1) AS next
;
```
Replace YourId with the actual id and replace YourTable with valid table name. If any of the values will be `NULL` then there is no next/prev element to the given. | ```
SELECT *
FROM (
SELECT *
FROM mytable
WHERE id >= @current
ORDER BY
id
LIMIT 2
) q1
UNION ALL
SELECT *
FROM (
SELECT *
FROM mytable
WHERE id < @current
ORDER BY
id DESC
LIMIT 1
) q2
ORDER BY
id
``` | previous - next query in mysql | [
"",
"php",
"mysql",
""
] |
PHP has a [uniqid()](https://www.php.net/manual/en/function.uniqid.php) function which generates a UUID of sorts.
In the usage examples, it shows the following:
`$token = md5(uniqid());`
But in the comments, [someone says this](https://www.php.net/manual/en/function.uniqid.php#91126):
> Generating an MD5 from a unique ID is
> naive and reduces much of the value of
> unique IDs, as well as providing
> significant (attackable) stricture on
> the MD5 domain. That's a deeply
> broken thing to do. The correct
> approach is to use the unique ID on
> its own; it's already geared for
> non-collision.
Why is this true, if so? If an MD5 hash is (almost) unique for a unique ID, then what is wrong from md5'ing a uniqid? | A UUID is 128 bits wide and has uniqueness inherent to the way it is generated. A MD5 hash is 128 bits wide and doesn't guarantee uniquess, only a low probablity of collision. The MD5 hash is no smaller than the UUID so it doesn't help with storage.
If you know the hash is from a UUID it is much easier to attack because the domain of valid UUIDs is actually fairly predictable if you know anything about the machine geneerating them.
If you needed to provide a secure token then you would need to use a [cryptographically secure random number generator.](http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator)(1) UUIDs are not designed to be cryptographically secure, only guaranteed unique. A monotonically increasing sequence bounded by unique machine identifiers (typically a MAC) and time is still a perfectly valid UUID but highly predictable if you can reverse engineer a single UUID from the sequence of tokens.
1. The defining characteristic of a cryptographically secure PRNG is that the result of a given iteration does not contain enough information to infer the value of the next iteration - i.e. there is some hidden state in the generator that is not revealed in the number and cannot be inferred by examining a sequence of numbers from the PRNG.
If you get into number theory you can find ways to guess the internal state of some PRNGs from a sequence of generated values. [Mersenne Twister](http://en.wikipedia.org/wiki/Mersenne_twister) is an example of such a generator. It has hidden state that it used to get its long period but it is not cryptographically secure - you can take a fairly small sequence of numbers and use that to infer the internal state. Once you've done this you can use it to attack a cryptographic mechanism that depends on keeping that sequence a secret. | Note that **`uniqid()` does not return a [UUID](http://en.wikipedia.org/wiki/UUID)**, but a "unique" string based on the current time:
```
$ php -r 'echo uniqid("prefix_", true);'
prefix_4a8aaada61b0f0.86531181
```
If you do that multiple times, you will get very similar output strings and everyone who is familiar with `uniqid()` will recognize the source algorithm. That way it is pretty easy to predict the next IDs that will be generated.
The advantage of md5()-ing the output, along with an application-specific salt string or random number, is a way harder to guess string:
```
$ php -r 'echo md5(uniqid("prefix_", true));'
3dbb5221b203888fc0f41f5ef960f51b
```
Unlike plain `uniqid()`, this produces very different outputs every microsecond. Furthermore it does not reveil your "prefix salt" string, nor that you are using `uniqid()` under the hood. Without knowing the salt, it is very hard (consider it impossible) to guess the next ID.
In summary, I would disagree with the commentor's opinion and would always prefer the `md5()`-ed output over plain `uniqid()`. | Why is MD5'ing a UUID not a good idea? | [
"",
"php",
"cryptography",
"md5",
""
] |
I have a custom class that inherits from **BindingList(T)** that I am binding to a **DataGrid**.
However, the **DataGrid** is being populated from the top down and I want it populated from the bottom up. So the bottom item is index 0 rather then the top item.
How can I change my **BindingList(T)** so that the **DataGrid** reads it in reverse? | [This](http://www.codeproject.com/KB/linq/bindinglist_sortable.aspx) article on [CodeProject.com](http://www.codeproject.com) about implementing sortable BindingList might help you.
It has a nice generic wrapper for binding list that makes it sortable:
```
public class MySortableBindingList<T> : BindingList<T> {
// reference to the list provided at the time of instantiation
List<T> originalList;
ListSortDirection sortDirection;
PropertyDescriptor sortProperty;
// function that refereshes the contents
// of the base classes collection of elements
Action<MySortableBindingList<T>, List<T>>
populateBaseList = (a, b) => a.ResetItems(b);
// a cache of functions that perform the sorting
// for a given type, property, and sort direction
static Dictionary<string, Func<List<T>, IEnumerable<T>>>
cachedOrderByExpressions = new Dictionary<string, Func<List<T>,
IEnumerable<T>>>();
public MySortableBindingList() {
originalList = new List<T>();
}
public MySortableBindingList(IEnumerable<T> enumerable) {
originalList = enumerable.ToList();
populateBaseList(this, originalList);
}
public MySortableBindingList(List<T> list) {
originalList = list;
populateBaseList(this, originalList);
}
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction) {
/*
Look for an appropriate sort method in the cache if not found .
Call CreateOrderByMethod to create one.
Apply it to the original list.
Notify any bound controls that the sort has been applied.
*/
sortProperty = prop;
var orderByMethodName = sortDirection ==
ListSortDirection.Ascending ? "OrderBy" : "OrderByDescending";
var cacheKey = typeof(T).GUID + prop.Name + orderByMethodName;
if (!cachedOrderByExpressions.ContainsKey(cacheKey)) {
CreateOrderByMethod(prop, orderByMethodName, cacheKey);
}
ResetItems(cachedOrderByExpressions[cacheKey](originalList).ToList());
ResetBindings();
sortDirection = sortDirection == ListSortDirection.Ascending ?
ListSortDirection.Descending : ListSortDirection.Ascending;
}
private void CreateOrderByMethod(PropertyDescriptor prop,
string orderByMethodName, string cacheKey) {
/*
Create a generic method implementation for IEnumerable<T>.
Cache it.
*/
var sourceParameter = Expression.Parameter(typeof(List<T>), "source");
var lambdaParameter = Expression.Parameter(typeof(T), "lambdaParameter");
var accesedMember = typeof(T).GetProperty(prop.Name);
var propertySelectorLambda =
Expression.Lambda(Expression.MakeMemberAccess(lambdaParameter,
accesedMember), lambdaParameter);
var orderByMethod = typeof(Enumerable).GetMethods()
.Where(a => a.Name == orderByMethodName &&
a.GetParameters().Length == 2)
.Single()
.MakeGenericMethod(typeof(T), prop.PropertyType);
var orderByExpression = Expression.Lambda<Func<List<T>, IEnumerable<T>>>(
Expression.Call(orderByMethod,
new Expression[] { sourceParameter,
propertySelectorLambda }),
sourceParameter);
cachedOrderByExpressions.Add(cacheKey, orderByExpression.Compile());
}
protected override void RemoveSortCore() {
ResetItems(originalList);
}
private void ResetItems(List<T> items) {
base.ClearItems();
for (int i = 0; i < items.Count; i++) {
base.InsertItem(i, items[i]);
}
}
protected override bool SupportsSortingCore {
get {
// indeed we do
return true;
}
}
protected override ListSortDirection SortDirectionCore {
get {
return sortDirection;
}
}
protected override PropertyDescriptor SortPropertyCore {
get {
return sortProperty;
}
}
protected override void OnListChanged(ListChangedEventArgs e) {
originalList = base.Items.ToList();
}
}
``` | Its simple, but you could also populate the binding list in reverse order (unless you have another reason for keeping the current order). | Reverse sort a BindingList<T> | [
"",
"c#",
"sorting",
"datagrid",
"bindinglist",
""
] |
I'm currently have an issue, and likely overlooking something very trivial. I have a field in my model that should allow for multiple choices via a checkbox form (it doesn't have to be a checkbox in the admin screen, just in the form area that the end-user will see). Currently I have the field setup like so:
```
# Type of Media
MEDIA_CHOICES = (
('1', 'Magazine'),
('2', 'Radio Station'),
('3', 'Journal'),
('4', 'TV Station'),
('5', 'Newspaper'),
('6', 'Website'),
)
media_choice = models.CharField(max_length=25,
choices=MEDIA_CHOICES)
```
I need to take that and make a checkbox selectable field in a form out of it though. When I create a ModelForm, it wants to do a drop down box. So I naturally overrode that field, and I get my checkbox that I want. However, when the form's submitted, it would appear that nothing useful is saved when I look at the admin screen. The database does however show that I have a number of things selected, which is a positive sign. However, how can I get that to reflect in the admin screen properly?
Edit: FWIW I'll gladly accept documentation links as answers, because it would seem I'm just glossing over something obvious. | In such a case, the easiest way is to put the choices into a separate model and then use a ManyToMany relationship. After that, you simply override the ModelForm's widget for that field to use [forms.CheckboxSelectMultiple](http://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.CheckboxSelectMultiple) and Django will automatically do the right thing. If you insist to use a CharField, you'll probably have to do something like [this snippet](http://www.djangosnippets.org/snippets/1200/).
@ 2. comment: how are you overriding the widget? This is how I do it and it works flawlessly:
```
class SomeModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(SomeModelForm, self).__init__(*args, **kwargs)
self.fields['some_field'].widget = forms.CheckboxSelectMultiple()
``` | I've just started to look into widgets assignment with ModelForms. In a lot of examples I've seen, piquadrat's included, the Form's \_\_ init \_\_ method is overridden.
I find this a little confusing, and just overriding the desired field is more natural for me:
```
class SomeModelForm(forms.ModelForm):
some_field = forms.CharField(choices=MEDIA_CHOICES,
widget=forms.CheckboxSelectMultiple)
class Meta:
model=SomeModel
```
Note: I'm using Django 1.1. | Django ModelForm CheckBox Widget | [
"",
"python",
"django",
"django-models",
"django-forms",
""
] |
in my applicationContext.xml, i put this
```
<bean id="something" class="com.to.theController"/>
```
in `com.to.theController`
i have this method like
```
@Controller
public theController{
@RequestMapping(value="/api/add", method= RequestMethod.GET)
public String apiAddHandler(Model model){
model.addAttribute("api", new Api());
return "apiForm";
}
}
```
when jetty startup, i can see defining beans `[something,...`
but when i go to `http://localhost:8080/api/add` , i get 404 error. what did i miss out? i already debug apiAddHandler method, this method is not called when i call the URL | Make sure Spring is finding your annotations. You should see something like "INFO DefaultAnnotationHandlerMapping:343 - Mapped URL path [/api/add] onto handler [com.example.ExampleController@6f3588ca]" in the logs.
Also, as mentioned already, you need to make sure that you have the correct url mapping in web.xml.
I'd use
```
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
```
to map all urls to the dispatcher servlet if using annotations.
If you want to serve some content outside of the dispatcher servlet add the folowing aswell
```
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.jpg</url-pattern>
</servlet-mapping>
``` | Do you have a `<servlet-mapping>` element in your `web.xml` to map URLs that look like `/api/add` to `DispatcherServlet`?
If not, then it doesn't matter how Spring MVC maps URLs to controllers if the request never makes it to Spring MVC in the first place. | map url to controller | [
"",
"java",
"spring",
"spring-mvc",
""
] |
I have an update service that needs to pull data down from remote, however like Microsoft's BITS I'd like to do this when the user is idle and/or when their network utilisation is low so as to not impact on their experience.
What do I need to do or look at? Can anyone point me in the right direction on where to start with this and get the information I need? | If you cannot use BITS because you want to be cross-platform, you're going to have trouble. Each OS will have different ways to find the current network usage, so you will have to write an interface class with implementations for each supported OS.
In Linux it seems to be the special file `/proc/net/snmp`. In Windows, BSD or OSX I have no idea. The `netstat -s` shell command seems to work on all of them, but the output format is different for each one. | Use official BITS wrapper <http://msdn.microsoft.com/en-us/library/ms997639.aspx> | Download when idle/low network utilization | [
"",
"c#",
".net",
"http",
"optimization",
"download",
""
] |
I have the following class:
```
private class Info{
public String A;
public int B;
Info(){};
public OtherMethod(){};
private PrivMethod(){};
}
```
And I want to create an array of this class, but I want to provide a two dimensional array as an argument to the constructor, ie:
```
Info[] I = new Info({{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
```
Is that possible? If so how would I implement it? If not, what alternatives would you suggest? | Its possible, but not using the syntax you suggested. Java doesn't support creating arrays out of constructors. Try the following:
```
public class Info {
public String a;
public int b;
private Info(Object [] args) {
a = (String) args[0];
b = (Integer) args[1];
}
public static Info[] create(Object[]...args) {
Info[] result = new Info[args.length];
int count = 0;
for (Object[] arg : args) {
result[count++] = new Info(arg);
}
return result;
}
public static void main(String [] args) {
Info[] data = Info.create(new Object[][] {{"StringA", 1}, {"StringB", 2}, {"StringC", 3}});
}
}
``` | What advantage would that have compared to this?
```
Info[] infos = new Info[] {new Info("StringA", 1),
new Info("StringB", 2),
new Info("StringC", 3)
}.
``` | How to implement a class constructor accepting an array of different types as an argument in Java | [
"",
"java",
"arrays",
"constructor",
""
] |
i am building up a string on the server that is getting put into a javascript variable on the client.
what is the best of encoding this to avoid any issues
right now on the server i am doing something like this:
```
html = html.Replace("'", "'");
```
but i assume there is a more elegant fool proof way of doing stuff like this. | You're really better off using the [Microsoft Anti-Cross Site Scripting Library](http://www.microsoft.com/downloads/details.aspx?FamilyId=051ee83c-5ccf-48ed-8463-02f56a6bfc09&displaylang=en) to do this. They provide a JavaScriptEncode method that does what you want:
```
Microsoft.Security.Application.AntiXss.JavaScriptEncode("My 'Quotes' and ""more"".", False)
``` | ```
html = html.Replace("'", "%27");
``` | Encoding apostrophe | [
"",
"asp.net",
"javascript",
"html",
"encoding",
""
] |
Good afternoon all,
**What I'm trying to accomplish**: I'd like to implement an extension to a C++ unit test fixture to detect if the test allocates memory and doesn't free it. My idea was to record allocation levels or free memory levels before and after the test. If they don't match then you're leaking memory.
**What I've tried so far:** I've written a routine to read */proc/self/stat* to get the vm size and resident set size. Resident set size seems like what I need but it's obviously not right. It changes between successive calls to the function with no memory allocation. I believe it's returning the cached memory used not what's allocated. It also changes in 4k increments so it's too coarse to be of any real use.
I can get the stack size by allocating a local and saving it's address. Are there any problems with doing this?
Is there a way to get real free or allocated memory on linux?
Thanks | I'd have to agree with those suggesting Valgrind and similar, but if the run-time overhead is too great, one option may be to use [mallinfo()](http://www.gnu.org/s/libc/manual/html_node/Statistics-of-Malloc.html) call to retrieve statistics on currently allocated memory, and check whether `uordblks` is nonzero.
Note that this will have to be run before global destructors are called - so if you have any allocations that are cleaned up there, this will register a false positive. It also won't tell you *where* the allocation is made - but it's a good first pass to figure out which test cases need work. | Your best bet may actually be to use a tool specifically designed for the job of finding memory leaks. I have personal experience with [Electric Fence](http://perens.com/FreeSoftware/ElectricFence/), which is easy to use and seems to do the job nicely (not sure how well it will handle C++). Also recommended by others is [Dmalloc](http://dmalloc.com/).
For sure though, everyone seems to like [Valgrind](http://valgrind.org/), which can do just about anything and even has front-ends (though anything that has a front-end built for it means that it probably isn't the simplest thing in the world). If the [KDE](http://techbase.kde.org/Development/Tools/Valgrind) folks can recommend it, it must be able to handle just about anything. (I'm not saying anything bad about KDE, just that it is a very large C++ codebase, so if Valgrind can handle KDE software, it must have something going for it. Though I don't have personal experience with it as Electric Fence was always enough for me) | how to find allocated memory in linux | [
"",
"c++",
"linux",
"unit-testing",
""
] |
I tried to read the related questions and didn't find any new tool.
Here is my problem : i generate some PDF files for an insurance from the data in my app. Stuff like, contracts, certificates, bills etc. The insurance guy gives me the templates files as .docs with fields in them and I have to fill in the fields with my data and generate the PDF. Quite a simple problem.
I don't have word, I'm in java swing.
I don't feel like re-creating he word doc in a report system (like BIRT or iReport) because it's long, painful and they often can't even do the same layout as word does.
I tried converting the .doc in .odt (OpenOffice), changing the field in form field, generating the PDF as a PDF form (non-decorated disabled fields, to look like normal text) and filing them with iText, but I get cheap results (I can't choose the font in the fields, width is fixed, I can't properly line up the baseline in the field and in the surrounding text etc.)
Do you have ideas/tools I can use for filling those fields without re-creating the doc file in a template editor ?
This question is quite open, I'm looking for ideas more than you doing my homework. | I've created an entire application (actually it was ported 3 times) to solve just this case, and one of the versions was using OpenOffice, which has .Doc templates (with bookmakrs) the application then acted like a "server" which had its own built in folder watcher, it would process requirest via XML and render out PDF documents using the .doc/.dot templates.
Sadly this was run in a server environment (and caused issues, I never managed to get the headless mode to work)
But at least in theory it works.
Start at looking at the Open Office APIs, you should be able to change font/style/size etc, also why are you using fields when you could use bookmarks instead? this allows you to jump to a predefined cursor (named) and then insert anything (eg tables, pictures, text, etc)
The excellent part is that in terms of styling and modifying the templates, all you need its words/OpenOffice.
Dont know if that helps
**Darknight** | There are free applications for creating pdf forms, would it be possible to teach the insurance guys to use this and provide a pdf form template to your application instead of a word template? I've been involved in an application that used this approach successfully. The workflow for the user became:
1. Create document using any application (word, photoshop, other...)
2. Export or print as pdf
3. Use pdf form editor to add fields in correct places. Use placeholders for contents.
4. Upload to server
The placeholders (like ${context.person.firstname} ) were then replaced on the server, the pdf "flattened" (converts form fields to text) and the filled out pdf returned. We used a defined set of placeholders that the user could choose from and added more when there was a need for it. This was a good tradeoff between the users wanting to use their applications of choise for layout and we wanting to avoid a multitude of formats (and Office)
If I recall correctly we used [Scribus](http://wiki.scribus.net/index.php/Main_Page) as pdf form editor | Doc templates to PDF files in java (looking for tools/libs) | [
"",
"java",
"swing",
"pdf",
""
] |
Hi fellow stackoverflow:ers,
I'm using the [jQuery Datepicker plugin](http://docs.jquery.com/UI/API/1.7.2/Datepicker), together with [Martin Milesich Timepicker](http://milesich.com/timepicker/) plugin. Everything works great, except for the fact that clicking a date in the datepicker, closes the widget, leaving no time to pick the time.
Question: So I'm wondering if there's a way to prevent the widget from closing when clicking a date, and instead force users to click the "Done" button (that shows up when enabling the "showButtonPanel: true" option), or clicking outside of the widget. I don't want my users having to open the widget twice! See the behavior [online at the timepicker demo](http://milesich.com/tpdemo/)
Any help solving this issue, or even pointers in the right direction, is appreciated!
More info:
I'm using the files supplied from Martins download link: <http://milesich.com/tpdemo/timepicker-0.2.0.zip>
* jquery-ui-1.7.2.custom.min.js
* timepicker.js (latest version 0.2.0)
These are the options I'm using:
```
$(document).ready(function(){
$(".datepicker").datepicker({
duration: '',
showTime: true,
constrainInput: false,
stepMinutes: 5,
stepHours: 1,
time24h: true,
dateFormat: "yy-mm-dd",
buttonImage: '/static/images/datepicker.png',
buttonImageOnly: true,
firstDay: 1,
monthNames: ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'],
showOn: 'both',
showButtonPanel: true
});
})
``` | rather than changing the source it's best to use the existing events
```
onSelect: function() {
$(this).data('datepicker').inline = true;
},
onClose: function() {
$(this).data('datepicker').inline = false;
}
``` | For reference, and since people have asked me this through mail. Here's a code chunk that needs to be added to timepicker.js:
```
/**
* Don't hide the date picker when clicking a date
*/
$.datepicker._selectDateOverload = $.datepicker._selectDate;
$.datepicker._selectDate = function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
inst.inline = true;
$.datepicker._selectDateOverload(id, dateStr);
inst.inline = false;
this._updateDatepicker(inst);
}
```
Good luck in getting it working on your site! | jQuery Datepicker: Prevent closing picker when clicking a date | [
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-ui-datepicker",
""
] |
I'm not sure how to make the question clearer but this is bascially the problem:
I have a class that is dervived from another one of my classes.
The base class has an overridden Tostring function (returns 2 strings separated by a colon).
The problem is that my derived class can have an array of strings or just the one string so when I override the ToString function I need to return the base class as well as the array of strings (separated by "\n") in the derived class. Now I'm wondering what would be the best way to do this; should I return an array of strings( if possible) or do I have no choice but to use the Stringbuilder class? If there's another way to do this please tell.. All ideas welcomed no matter how crazy they may be :) | When overriding `ToString` you *have* to return just a string. You can't return any other type. It sounds like you might want something like this:
```
public override ToString()
{
return base.ToString() + "\n" + string.Join("\n", stringArray);
}
```
That's assuming you want to return a string such as:
```
base1:base2
this1
this2
this3
```
where the line separators are `\n`. | What do you mean by "return the base class as well as the array of strings"?
If you meant the ToString() method of the base class you could try:
```
base.ToString() + "\n" + String.Join("\n", theStringArray );
``` | How do I return a compound string in an overridden ToString function? | [
"",
"c#",
".net",
""
] |
What I mean is, when user click a button on a webpage,
a program which has already installed on his computer would be
executed. I also need to pass some command line parameters to the program.
---
We have 2 program, one is a web app, the other is a desktop program.
We want to find a simple way to integrate the 2.
That's why we need to execute the desktop program from a web page. | You can register a protocol to your application so that navigating to a URL beginning with that scheme will launch your application and run a command.
* [Windows](<http://msdn.microsoft.com/en-us/library/aa767914(VS.85).aspx)>
* [Mac OS X](http://developer.apple.com/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCIntro/LSCIntro.html)
* [Gnome](http://people.w3.org/~dom/archives/2005/09/integrating-a-new-uris-scheme-handler-to-gnome-and-firefox/) | This is not possible. If it was, it would be a *huge* security breach.
Imagine being able to let the user click a button on the webpage and as a result format his harddrive with the standard *format* command? I bet you wouldn't want that happening to yourself.
Maybe you can think about exposing a webservice from your webapplication and let the desktopclient look at that webservice? | How to run a executable file from a web page? | [
"",
"javascript",
""
] |
We have a website which we recently migrated to ASP.NET MVC. All of the URLs are now different from the original website. Google still has all of our old URLs, so if anyone finds us in a search, currently they will get a 404.
I have a catchall route that catches bad URLs, including all of the old ones. In a perfect world I would like to do a 301 redirect to the home page for all urls matching this catchall route, and I do have code for this that works properly on my development machine. However, I finally got someone at our ISP (Network Solutions) to tell me that they **block** 301 redirections (the web server returns a 404 instead).
So I think my only remaining option is to just accept any bad URL, and point it to the home page.
Here is my question: I know that the search engines (especially Google) are now penalizing duplicate content. If I just point all bad URLs to the home page, how much is this going to hurt us in the search rankings? Do I have any other technical options? | Honestly, I would suggest that you change ISP's. 301's are an important tool in any webmaster's toolbox, and for them to block that will penalize you terribly. You could easily transfer your domain to another IP address, wait for the DNS propagation, and then do your rollout.
From Google's Webmaster tools:
> Use a 301 Redirect to permanently
> redirect all pages on your old site to
> your new site. This tells search
> engines and users that your site has
> permanently moved. We recommend that
> you move and redirect a section or
> directory first, and then test to make
> sure that your redirects are working
> correctly before moving all your
> content.
>
> Don't do a single redirect directing
> all traffic from your old site to your
> new home page. This will avoid 404
> errors, but it's not a good user
> experience. It's more work, but a
> page-to-page redirect will help
> preserve your site's ranking in Google
> while providing a consistent and
> transparent experience for your users.
> If there won't be a 1:1 match between
> pages on your old site and your new
> site (recommended), try to make sure
> that every page on your old site is at
> least redirected to a new page with
> similar content.
I'm sure that's much easier said then done, but I would never want an ISP that exerted that kind of filter against their clients. | Can you do a 302 redirect at least? I do agree with what womp says though, what ISP would block 301 redirects? Dump them. ISPs are a dime a dozen. | Redirecting Old Urls After Web Site Overhaul | [
"",
"c#",
"asp.net-mvc",
"seo",
"http-status-code-301",
""
] |
Is `with()` part of the native JavaScript library? Which browsers support it? | It's part of the [JavaScript 1.5 specification](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/with). So it must be supported by major browser. | Yes it is part of it. Every browser that supports JavaScript 1.5 supports it (that is all major browsers, or grade A).
However, it is [not recommended](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/) to use the with statement. | JavaScript with() function | [
"",
"javascript",
""
] |
I have a mysql table like below:
```
id name points
1 john 4635
3 tom 7364
4 bob 234
6 harry 9857
```
I basically want to get an individual user rank without selecting all of the users. I only want to select a single user by id and get the users rank which is determined by the number of points they have.
For example, get back tom with the rank 2 selecting by the id 3.
Cheers
Eef | ```
SELECT uo.*,
(
SELECT COUNT(*)
FROM users ui
WHERE (ui.points, ui.id) >= (uo.points, uo.id)
) AS rank
FROM users uo
WHERE id = @id
```
Dense rank:
```
SELECT uo.*,
(
SELECT COUNT(DISTINCT ui.points)
FROM users ui
WHERE ui.points >= uo.points
) AS rank
FROM users uo
WHERE id = @id
``` | Solution by @Quassnoi will fail in case of ties. Here is the solution that will work in case of ties:
```
SELECT *,
IF (@score=ui.points, @rank:=@rank, @rank:=@rank+1) rank,
@score:=ui.points score
FROM users ui,
(SELECT @score:=0, @rank:=0) r
ORDER BY points DESC
``` | MySQL, Get users rank | [
"",
"sql",
"mysql",
"rank",
""
] |
Every time I think I understand about casting and conversions, I find another strange behavior.
```
long l = 123456789L;
float f = l;
System.out.println(f); // outputs 1.23456792E8
```
Given that a `long` has greater bit-depth than a `float`, I would expect that an explicit cast would be required in order for this to compile. And not surprisingly, we see that we have lost precision in the result.
Why is a cast not required here? | The same question could be asked of `long` to `double` - both conversions may lose information.
[Section 5.1.2 of the Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2) says:
> Widening primitive conversions do not
> lose information about the overall
> magnitude of a numeric value. Indeed,
> conversions widening from an integral
> type to another integral type do not
> lose any information at all; the
> numeric value is preserved exactly.
> Conversions widening from float to
> double in strictfp expressions also
> preserve the numeric value exactly;
> however, such conversions that are not
> strictfp may lose information about
> the overall magnitude of the converted
> value.
>
> Conversion of an int or a long value
> to float, or of a long value to
> double, may result in loss of
> precision-that is, the result may lose
> some of the least significant bits of
> the value. In this case, the resulting
> floating-point value will be a
> correctly rounded version of the
> integer value, using IEEE 754
> round-to-nearest mode (§4.2.4).
In other words even though you may lose information, you know that the value will still be in the overall range of the target type.
The choice could certainly have been made to require all implicit conversions to lose no information at all - so `int` and `long` to `float` would have been explicit and `long` to `double` would have been explicit. (`int` to `double` is okay; a `double` has enough precision to accurately represent all `int` values.)
In some cases that would have been useful - in some cases not. Language design is about compromise; you can't win 'em all. I'm not sure what decision I'd have made... | The [Java Language Specification, Chapter 5: Conversion and Promotion](http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#25214) addresses this issue:
> ## 5.1.2 Widening Primitive Conversion
>
> The following 19 specific conversions
> on primitive types are called the
> widening primitive conversions:
>
> * byte to short, int, long, float, or double
> * short to int, long, float, or double
> * char to int, long, float, or double
> * int to long, float, or double
> * long to float or double
> * float to double
>
> Widening primitive conversions do not lose information about the overall magnitude of a numeric value.
>
> ...
>
> Conversion of an int or a long value to float, or of a long value to double, may result in loss of precision-that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value
To put it another way, the JLS distinguishes between a loss of ***magnitude*** and a loss of ***precision***.
`int` to `byte` for example is a (potential) loss of magnitude because you can't store 500 in a `byte`.
`long` to `float` is a potential loss of precision but not magnitude because the value range for floats is larger than that for longs.
So the rule is:
* **Loss of magnitude:** explicit cast required;
* **Loss of precision:** no cast required.
Subtle? Sure. But I hope that clears that up. | Why does Java implicitly (without cast) convert a `long` to a `float`? | [
"",
"java",
"casting",
""
] |
Very often it happens that I have private methods which become very big and contain repeating tasks but these tasks are so specific that it doesn't make sense to make them available to any other code part.
So it would be really great to be able to create 'inner methods' in this case.
Is there any technical (or even philosophical?) limitation that prevents C# from giving us this? Or did I miss something?
*Update from 2016: This is coming and it's called a 'local function'. See marked answer.* | Seems like we're going to get exactly what I wanted with **Local Functions** in **C# 7 / Visual Studio 15**:
<https://github.com/dotnet/roslyn/issues/2930>
```
private int SomeMethodExposedToObjectMembers(int input)
{
int InnerMethod(bool b)
{
// TODO: Change return based on parameter b
return 0;
}
var calculation = 0;
// TODO: Some calculations based on input, store result in calculation
if (calculation > 0) return InnerMethod(true);
return InnerMethod(false);
}
```
Too bad I had to wait more than 7 years for this :-)
See also other answers for earlier versions of C#. | Well, we can have "anonymous methods" defined inside a function (I don't suggest using them to organize a large method):
```
void test() {
Action t = () => Console.WriteLine("hello world"); // C# 3.0+
// Action t = delegate { Console.WriteLine("hello world"); }; // C# 2.0+
t();
}
``` | C#: Why can't we have inner methods / local functions? | [
"",
"c#",
".net",
""
] |
I'm starting out my expedition into Project Euler. And as many others I've figured I need to make a prime number generator. Problem is: PHP doesn't like big numbers. If I use the standard [Sieve of Eratosthenes function](http://rosettacode.org/wiki/Sieve_of_Eratosthenes#PHP), and set the limit to 2 million, it will crash. It doesn't like creating arrays of that size. Understandable.
So now I'm trying to optimize it. One way, I found, was to instead of creating an array with 2 million variable, I only need 1 million (only odd numbers can be prime numbers). But now it's crashing because it exceeds the maximum execution time...
```
function getPrimes($limit) {
$count = 0;
for ($i = 3; $i < $limit; $i += 2) {
$primes[$count++] = $i;
}
for ($n = 3; $n < $limit; $n += 2) {
//array will be half the size of $limit
for ($i = 1; $i < $limit/2; $i++) {
if ($primes[$i] % $n === 0 && $primes[$i] !== $n) {
$primes[$i] = 0;
}
}
}
return $primes;
}
```
The function works, but as I said, it's a bit slow...any suggestions?
One thing I've found to make it a bit faster is to switch the loop around.
```
foreach ($primes as $value) {
//$limitSq is the sqrt of the limit, as that is as high as I have to go
for ($n = 3; $n = $limitSq; $n += 2) {
if ($value !== $n && $value % $n === 0) {
$primes[$count] = 0;
$n = $limitSq; //breaking the inner loop
}
}
$count++;
}
```
And in addition setting the time and memory limit (thanks Greg), I've finally managed to get an answer. phjew. | From [Algorithmist's proposed solution](http://www.algorithmist.com/index.php/SPOJ_PRIME1)
> This is a modification of the standard
> Sieve of Eratosthenes. It would be
> highly inefficient, using up far too
> much memory and time, to run the
> standard sieve all the way up to n.
> **However, no composite number less than
> or equal to n will have a factor
> greater than sqrt{n},
> so we only need to know all primes up
> to this limit**, which is no greater
> than 31622 (square root of 10^9). This
> is accomplished with a sieve. **Then,
> for each query, we sieve through only
> the range given, using our
> pre-computed table of primes to
> eliminate composite numbers**.
This problem has also appeared on UVA's and Sphere's online judges. [Here's how it's enunciated on Sphere.](https://www.spoj.pl/problems/PRIME1/) | Without knowing much about the algorithm:
1. You're recalculating `$limit/2` each time around the $i loop
2. Your if statement will be evaluated in order, so think about (or test) whether it would be faster to test `$primes[$i] !== $n` first.
Side note, you can use [`set_time_limit()`](http://php.net/set_time_limit) to give it longer to run and give it more memory using
```
ini_set('memory_limit', '128M');
```
Assuming your setup allows this, of course - on a shared host you may be restricted. | prime generator optimization | [
"",
"php",
"math",
"optimization",
""
] |
There's a ton and and a half of questions and even more answers here concerning people looking for bug trackers. However all of them (that I found) seem to be about web based solutions. Since I'm working on a local project where I don't want to set up a web / DB server, and I don't want to use a hosted tracker either, I'm looking for something that runs locally.
* very preferably open-source
* pure Python or (at least) Windows executable
* no need for a database server (sqlite is obviously fine)
* Doesn't have to be fancy, just the basic bug / issue tracking functionality; just a little bit more than my current TODO text file or an Excel table.
Any suggestions? | Trac might be a bit too over engineered, but you could still run it locally via tracd on localhost.
It's:
* opensource.
* pure Python
* uses sqlite
But as I said, might be too complex for your use case.
Link: <http://trac.edgewall.org> | I'm surprised nobody has mentioned [Roundup](http://roundup.sourceforge.net/).
It meets all your criteria, including not requiring a web-based interface (as per your specification, and unlike the accepted answer which suggested Trac).
Roundup is:
* Open source
* Pure Python
* Supports SQLite
* Not fancy, focuses on solid bug tracking
And as a significant point of differentiation, it has command-line and email interfaces in addition to a web interface.
It's very easy to get started - I suggest you take it for a spin. | Simple non-web based bug tracker | [
"",
"python",
"windows",
"bug-tracking",
"non-web",
""
] |
I am using a console application to call web service methods and I am stepping through the code using the debugger in vs2008.
Sometimes I need to stop and think about things, and compare values. Not talking hours, just a few minutes, at this point the web service times out, how can I avoid this, so that the web service does not time out at all.
Thank you | Ok, now a serious answer, found at:
<http://bytes.com/groups/net-web-services/628561-increase-default-webservice-timeout-globally>
1. Increase the [`Timeout`](http://msdn.microsoft.com/en-us/library/47096yt2.aspx) property of the web-service-proxy.
```
MyWebServ obj = new MyWebServ();
obj.Timeout = -1; // -1 for forever otherwise in milliseconds
```
2. Increase the timeout value in http-runtime tag in web-config of ASP.NET
project./app.config if the web consumer application is Windows.
3. Increase the timeout value in http-runtime tag in web-config of Web Services
project. | You can turn the timeout off by stopping the application pool from recycling:
In the IIS console, go to the app pool properties and set "Ping Enabled" to false
(hope this helps! - is my first answer on here) | How can I avoid timeout errors while debugging a web service in visual studio 2008 | [
"",
"c#",
"web-services",
""
] |
I am trying to add a reCAPTCHA to my site, but keep getting `incorrect-captcha-sol` error when I submit the answer.
Can anyone tell me if I am correct in doing the following?
I have a generic index.php, which includes contact.php. In contact.php I have inserted the following code:
```
require_once('recaptchalib.php');
$publickey = "XXXX";
$privatekey = "XXXX";
//the response from reCAPTCHA
$resp = null;
//the error code from reCAPTCHA, if any
$error = null;
if ($_POST['submit']) {
$message = $_POST['message_txt'];
$name = $_POST['name_txt'];
$email = $_POST['email_txt'];
$emailBody = $message;
$to = 'xx';
$from = $name.' <'.$email.'>';
$subject = 'XX Website Enquiry';
$headers = 'From: '.$from;
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
echo 'captcha correct';
if (mail($to,$subject,$emailBody,$headers)) {
//echo 'mail sent';
$confirmation = 'sent';
}
else {
//echo 'mail not sent';
$confirmation = 'error';
}
} else {
# set the error code so that we can display it. You could also use
# die ("reCAPTCHA failed"), but using the error message is
# more user friendly
$error = $resp->error;
echo $error;
}
}
```
In my html I inserted the CAPTCHA like this:
```
<form name="contactForm" method="post" action="index.php?id=contact&action=submit#contact">
<tr><td>Name</td><td><div align="right">
<input type="text" name="name_txt" class="input">
</div></td></tr>
<tr><td>Email</td><td><div align="right">
<input type="text" name="email_txt" class="input">
</div></td></tr>
<tr><td height="10"></td></tr>
<tr><td colspan="2">Message</td></tr>
<tr><td colspan="2"><textarea name="message_txt" class="textarea" style="width:200px; height:100px"></textarea></td></tr>
<tr><td colspan="2"><?php echo recaptcha_get_html($publickey, $error); ?></td></tr>
<tr><td colspan="2" style="padding-top:10px;"><input type="image" src="images/header_06.gif" name="submit" value="submit"></td></tr>
</form>
```
I cannot see that I am doing anything wrong, but would appreciate any help. | I have solved this, it is one of the most unusual things I have come across, my syntax was previously:
```
<table>
<form>
<tr><td></td></tr>
</form>
</table>
```
I changed it to this:
```
<form>
<table>
<tr><td></td></tr>
</table>
</form>
```
Because of this switch, suddenly the `recaptcha_response_field` and `recaptcha_challenge_field` are posting values back to the form.
I cannot think why this because all MY form variables got posted back before the switch.
Thanks all for the pointers. | Are You doing this from Your **Localhost**?
I solve this problem by adding `localhost` to the allowed domain for doing a verification in google reCaptcha settings
[](https://i.stack.imgur.com/tMZF5.png) | Google reCAPTCHA - keep getting `incorrect-captcha-sol` | [
"",
"php",
"html",
"recaptcha",
""
] |
Imagine I have the following situation:
File1.php
```
<?php
include("Function.php");
log("test");
?>
```
Function.php
```
<?php
function log($msg)
{
echo "";
}
?>
```
I want to change the log function so that it would produce the following:
> test (file: File1.php, line number: 3)
So, any way to get the file name and the line number of the code that executed the current function in PHP?
**EDIT for backlog usage comments:**
When I use backlog in my object oriented way of programming I have the following situation.
Index.php
```
<?php
include("Logger.static.php");
include("TestClass.class.php");
new TestClass();
?>
```
TestClass.class.php
```
<?php
class TestClass
{
function __construct()
{
Logger::log("this is a test log message");
}
}
?>
```
Logger.static.php
```
<?php
class Logger
{
static public function log($msg)
{
$bt = debug_backtrace();
$caller = array_shift($bt);
echo $caller['file'];
echo $caller['line'];
}
}
?>
```
This example will return as file "Index.php" and as line number 4, this is where the class is initiated. However, it is supposed to return the file TestClass.class.php and line number 6. Any idea how to fix this? | You can use debug\_backtrace().
<https://www.php.net/manual/en/function.debug-backtrace.php>
So, in your log function, you would be able to retrieve the filename and line number from which the log function was called.
I'm using this approach in my logging classes and it has significantly reduced the amount of code required to get meaningful log data. Another benefit would be readability. Magic constants tend to get quite ugly when mixed with strings.
Here's a quick example:
```
function log($msg)
{
$bt = debug_backtrace();
$caller = array_shift($bt);
// echo $caller['file'];
// echo $caller['line'];
// do your logging stuff here.
}
``` | [debug\_backtrace()](http://php.net/debug_backtrace) can be used to trace back through the call stack. It can be slow though, so be careful with it if you're doing a lot of logging.
If you're using PHP 5.3, you could take advantage of [late static binding](http://www.php.net/lsb) and have a base class method of `log()`, and your child classes could call it but still maintain static references to `__FILE__` and `__LINE__`.
A final option would be just pass `__FILE__` and `__LINE__` in as parameters when you call your `log()` function. | Get code line and file that's executing the current function in PHP? | [
"",
"php",
""
] |
I have an input for users where they are supposed to enter their phone number. The problem is that some people write their phone number with hyphens and spaces in them. I want to put the input trough a filter to remove such things and store only digits in my database.
I figured that I could do some str\_replace() for the whitespaces and special chars.
However I think that a better approach would be to pick out just the digits instead of removing everything else. I think that I have heard the term "whitelisting" about this.
Could you please point me in the direction of solving this in PHP?
**Example**: I want the input "0333 452-123-4" to result in "03334521234"
Thanks! | This is a non-trivial problem because there are lots of colloquialisms and regional differences. Please refer to [What is the best way for converting phone numbers into international format (E.164) using Java?](https://stackoverflow.com/questions/187216/what-is-the-best-way-for-converting-phone-numbers-into-international-format-e-16) It's Java but the same rules apply.
I would say that unless you need something more fully-featured, keep it simple. Create a list of valid regular expressions and check the input against each until you find a match.
If you want it *really* simple, simply remove non-digits:
```
$phone = preg_replace('![^\d]+!', '', $phone);
```
By the way, just picking out the digits is, by definition, the same as removing everything else. If you mean something different you may want to rephrase that. | ```
$number = filter_var(str_replace(array("+","-"), '', $number), FILTER_SANITIZE_NUMBER_INT);
```
`Filter_Var` removes everything but pluses and minuses, and str\_replace gets rid of those.
or you could use preg\_replace
```
$number = preg_replace('/[^0-9]/', '', $number);
``` | Whitelist in php | [
"",
"php",
"user-input",
"whitelist",
""
] |
How do I read an entire `InputStream` into a byte array? | You can use Apache [Commons IO](http://commons.apache.org/io/) to handle this and similar tasks.
The `IOUtils` type has a static method to read an `InputStream` and return a `byte[]`.
```
InputStream is;
byte[] bytes = IOUtils.toByteArray(is);
```
Internally this creates a `ByteArrayOutputStream` and copies the bytes to the output, then calls `toByteArray()`. It handles large files by copying the bytes in blocks of 4KiB. | You need to read each byte from your `InputStream` and write it to a `ByteArrayOutputStream`.
You can then retrieve the underlying byte array by calling `toByteArray()`:
```
InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
return buffer.toByteArray();
``` | Convert InputStream to byte array in Java | [
"",
"java",
"arrays",
"inputstream",
""
] |
I have read 3 posts on SO about how to do this, but its not working for some reason.
On the page index.php, i have this script:
```
<script type="text/javascript">
function update() {
$.get("index.php", function(data) {
$("#uploadcount").html(data);
window.setTimeout(update, 5000);
});
}
</script>
```
and then this div, also in index.php
```
<div id=uploadcount>
<?
$result = mysql_query("SELECT * FROM mydb");
$num_rows = mysql_num_rows($result);
echo "<h1>$num_rows</h1><h2>rows</h2>";
?>
</div>
```
The php is displaying the row count fine, but it wont refresh the number.
(i have latest jquery build included in head of index.php) | found a solution that works great
```
<script type="text/javascript">
$(document).ready(function() {
setInterval(function()
{
$('#uploadcount').fadeOut("fast").load('uploadcount.php').fadeIn("slow");
}, 10000);
});
</script>
<div id="uploadcount">
<? include("uploadcount.php");?>
</div>
```
Thanks all to helped. | Try enclosing your div ID in double quotes:
```
<div id="uploadcount">
```
Also, put your jQuery within a document.ready block, and the call to setTimeout should not be inside the $.get method:
```
<script type="text/javascript">
$(document).ready(function() {
function update() {
$.get("index.php", function(data) {
$("#uploadcount").html(data);
});
}
window.setTimeout(update, 5000);
});
</script>
```
If you want to selectively retrieve something from a document, you can use [$.load](http://docs.jquery.com/Ajax/load) with a selector, e.g.:
```
$("#uploadcount").load("index.php #uploadcount");
```
<http://docs.jquery.com/Ajax/load>
That only works with jQuery 1.2 and above. | problem refreshing div containing php code using jquery | [
"",
"php",
"jquery",
""
] |
I am looking for an open source Java project containing two reasonably complete test suites: a suite of *integration tests* **and** a suite of *unit tests*, for the **same** code.
Note that I am only interested in *developer tests*, written with JUnit or TestNG.
I ask this because I often see people saying that having both unit and integration tests is necessary. But so far I don't know of any codebase with both kinds of test coverage.
Does anyone know of any such project? | Have a look at [tapestry](http://tapestry.apache.org/) web-framework. from code-quality perspective one of the best pieces of code i have seen! it uses both unit-tests and integration-tests (selenium driven). they are nicely integrated with maven so you can just run them locally. i would have preferred canoo-webtest (browser independent), but the suites are nice.
but you are right, all a mandating (automated) unit+integration tests, but you hardly see it in practice... though it really pays off! | FitNess should have both. I know that fitness has a very high test coverage and takes pride in clean code. I`m not completely sure if there are integration tests, but since fitNess is an acceptance test framework they probably have every kind of test type in place.
You`ll find the source here <http://fitnesse.org/> under download | Are there any Java open source projects with both integration and unit test suites? | [
"",
"java",
"unit-testing",
"integration-testing",
""
] |
I asked "[How to run a executable file from a web page?](https://stackoverflow.com/questions/1205584/how-to-run-a-executable-file-from-a-web-page)"
Many people told me that's impossible, but my colleague find a piece of JavaScript code that could execute any process. I can not believe ActiveX is so dangerous.
How could this happen? Why this is not forbidden by IE?
```
<SCRIPT language=JavaScript>
function Run(strPath) {
try {
var objShell = new ActiveXObject("wscript.shell");
objShell.Run(strPath);
objShell = null;
}
catch (e){alert('Can not find "'+strPath)
}
}
</SCRIPT>
<BUTTON class=button onclick="Run('notepad')">notepad</BUTTON><br>
<BUTTON class=button onclick="Run('mspaint')">mspaint</BUTTON><br>
<BUTTON class=button onclick="Run('calc')">calc</BUTTON><br>
<BUTTON class=button onclick="Run('format c:')">format c:</BUTTON><br>
``` | While you can do this IE will block it saying that there is an
> ActiveX Control is trying to access
> you computer, click here for options
You can only run these if the end user allows them too and hopefully people are clever enough not to allow it to run. If you do allow it then there is always another alert asking if you really want to run this so there should be enough security around it. | Local files run in a different security environment than remote files, so while that will work if you save the file as an html and open it from your computer, if you upload it on a server and try to run it from there it will not work. | Suprisingly, JavaScript Code could execute any process it want. Why? | [
"",
"javascript",
""
] |
I have an XML document which I'm pretty-printing using `lxml.etree.tostring`
```
print etree.tostring(doc, pretty_print=True)
```
The default level of indentation is 2 spaces, and I'd like to change this to 4 spaces. There isn't any argument for this in the `tostring` function; is there a way to do this easily with lxml? | As said in [this thread](http://codespeak.net/pipermail/lxml-dev/2009-February/004350.html), there is no real way to change the indent of the `lxml.etree.tostring` pretty-print.
But, you can:
* add a XSLT transform to change the indent
* add whitespace to the tree, with something like in the [cElementTree](http://effbot.org/zone/element-lib.htm) library
code:
```
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
indent(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
``` | Since version 4.5, [you can set indent size](https://lxml.de/tutorial.html#serialisation) using `indent()` function.
```
etree.indent(root, space=" ")
print(etree.tostring(root))
``` | Changing the default indentation of etree.tostring in lxml | [
"",
"python",
"lxml",
"pretty-print",
""
] |
Hey, what's the easiest way to use a file-based database with LINQ in C#? It would be best if I could use it without installing extra components.
EDIT: I want to use it for a file index. Not the whole file system, but the database should be not too slow and not too big. | I'd recommend MS SQL Server Compact Edition. Its embedable, small footprint, good performance and you can use Linq2Sql to query it easily. Also it integrates well with Visual Studio IDE and SQL Management Studio. | Are you opposed to using XML?
That's basically what XML is (or, rather, is a major use of XML), and [Linq to XML](http://msdn.microsoft.com/en-us/library/bb387098.aspx) is very powerful. | Simple, linq-able, file based database | [
"",
"c#",
"database",
"linq",
""
] |
In a recent question, someone asked if they could make a time just using the hour, minute, and AM/PM parts of a standard time format. This led to my question, what is needed to create a time using strtotime?
* Do you need to have a date? If one is not provided, what date does it choose?
* Do you need to have a time? What is the default?
* Do you need to have a year? Default?
* Month? Default?
* Day? Default?
I guess this is more of, what are the defaults for strtotime, but I'm curious to know. | 1. No; today.
2. No; noon.
3. No; this year.
4. No; the current month.
5. No; the current day.
I don't know what happens if the current day is unavailable in a specified month (e.g. it's the 31st and you do `strtotime('February')`. Someone who has a server instance available where they can safely manipulate the system time could research that. | See
<http://www.gnu.org/software/tar/manual/html_node/Date-input-formats.html#SEC114>
and
<https://www.php.net/manual/en/function.strtotime.php>
The default time when no time is supplied is "00:00:00" (midnight). | What is required by strtotime to make a string/What are the defaults? | [
"",
"php",
"time",
""
] |
Let's say there is a simple test code
```
typedef struct
{
int first;
int second;
int third;
} type_t;
#define ADDRESS 0x12345678
#define REGISTER ((type_t*)ADDRESS)
const int data = (int)(®ISTER->second)*2;
int main(void)
{
volatile int data_copy;
data_copy = data;
while(1) {};
}
```
Which is compiled in CodeSourcery G++ (gcc 4.3.2) for bare metal ARM. It also has a very standard linker script.
When compiled in C (as main.c) the object "data" goes into Flash, as expected. When compiled in C++ (as main.cpp) this object goes into RAM, and additional code is added which does nothing more than copy the value from Flash to RAM (the value is already calculated, just copy!). So the compiler can calculate the address, but somehow doesn't want to "just
use it". The root of the problem is the multiplication of the address - without "\*2" multiplication both versions work as expected - "data" is placed in Flash. Also - when "data" is declared as:
```
const int data = (int)(REGISTER)*2;
```
also everything is fine.
All files for C and C++ compilation are identical, the only difference is the call to compiler - g++ for main.cpp, gcc for main.c (with differences in the level of warnings, and c++ has RTTI and exceptions disabled).
Is there any easy and elegant way to overcome this "C++ problem"? I do require such operations for creating const arrays of addresses of bits in bitband region of Cortex-M3. Is this a bug, or maybe that is some strange limitation of the C++ compiler?
I know that I can create data objects in "C" files and just "extern"-include them in C++, but that's not very elegant [;
Thank you for all help! | The right solution is using the [offsetof()](http://www.cplusplus.com/reference/clibrary/cstddef/offsetof/) macro from the stddef.h header.
Basically this:
```
const int data = (int)(®ISTER->second)*2;
```
has to be replaced with
```
#include <stddef.h>
const int data = (int)(REGISTER + offsetof(type_t,second))*2;
```
And then the object is placed in Flash both for C and C++. | You have several problems. Why are you taking an address, converting it to an integer, and multiplying by 2? You should never by multiplying addresses, or storing addresses as ints. The only arithmetic you should ever do with pointers is to subtract them (to obtain an offset), or to add a pointer with an offset to get another pointer.
In C++, the rules for global value initialization are a little more lax than in C. In C, values are required to be initialized to compile-time constants; as a result, the compiler can place `const` global values in read-only memory. In C++, values can be initialized to expressions which aren't necessarily compile-time constants, and the compiler is permitted to generate code at runtime to calculate the initial value. This initialization code is called before entry into `main()`, akin to constructors for global objects.
Since you're working with constants addresses, and you know how big an `int` is on your platform (I'm assuming 32 bits), you should just do something like this:
Next, your use of the `volatile` keyword is completely wrong. `volatile` says to the compiler not to save a variable in a register -- it should be reloaded from memory each time it is read, and it should be fully written to memory every time it is written. Declaring the local variable `data_copy` as `volatile` is practically useless, unless you expect another thread or a signal handler to start modifying it unexpectedly (highly doubtful). Further, `data_copy` is just a copy of the address, not the contents of the register you're trying to read.
What you *should* be doing is declaring `REGISTER` as a pointer to a volatile -- that is one of the express purposes of `volatile`, for accessing memory-mapped registers. Here's what your code should look like:
```
#define REGISTER (*(volatile type_t *)ADDRESS)
#define DATA (*(const volatile int *)((ADDRESS+4)*2))
```
This makes it so that when you do things like this:
```
REGISTER.first = 1;
REGISTER.first = 2;
int x = REGISTER.second;
int y = DATA;
```
It always does the proper thing: a write of 1 to 0x12345678, a write of 2 to 0x12345678, a read from 0x1234567c, and a read from 0x2468acf8. The `volatile` keyword ensures that those reads and writes always happen, and they don't get optimized away: the compiler will not remove the first write to `REGISTER.first`, which would be redundant if it were a regular variable.
**EDIT**
In response to your comment, see Andrew Medico's response to your comment -- you're really multiplying the *difference* between two pointers by 2, which is ok. Just be careful about your data types. I also never mentioned anything about a kernel.
You can get gcc to put variables in a specific data section with the [`section` attribute](http://gcc.gnu.org/onlinedocs/gcc/Variable-Attributes.html#index-g_t_0040code_007bsection_007d-variable-attribute-2413):
```
const volatile int *data __attribute__((section("FLASH")) = /* whatever */;
```
Use the proper section name. If you're not sure what that is, take the object file generated by the C compiler (which you said puts it in the proper section), run `nm` on it, and see what section the C compiler put it in. | GCC C++ (ARM) and const pointer to struct field | [
"",
"c++",
"c",
"embedded",
"arm",
"codesourcery",
""
] |
How can I redirect in PHP with this setup below without getting header output errors, I understand that nothing can be printed to the browser before a header is set, I am looking for a solution, not an explanation of why it happens please.
```
<?PHP
// include header
include ('header.inc.php');
// In my body section file if this is a page that requires a user be logged in then
// I run a function validlogin($url-of-page-we-are-on); inside of that file
//the function is below, it outputs a redirect to login page if not logged in
// include body of page we want
include ('SOME-FILE-HERE.php');
// include footer
include ('footer.inc.php');
// here is the function that is in the body pages, it is only called on a page that we require a logged in user so there are hundreds of pages that do have this and a bunch that don't, it's on a page to page basis
function validlogin($url) {
if ($_SESSION['auto_id'] == '') {
$msg = 'Please login';
$_SESSION['sess_login_msg'] = $msg;
$_SESSION['backurl'] = $url;
$temp = '';
header("Location: /");
exit();
}
}
?>
```
I would like to user php's header function and not a meta or javascript redirect
Also maintainning a list of pages that require login or not is not an option here if possible | Can't you just do this:
```
<?php
validlogin($url); // call the function here
include ('header.inc.php');
include ('SOME-FILE-HERE.php');
include ('footer.inc.php');
?>
```
Or, put the include files in every one of the "SOME-FILE-HERE"-type files, if that's possible, so you end up with:
```
<?php
validlogin($url); // call the function here
include ('header.inc.php');
?>
<h1>Page heading</h1>
...page content etc...
<?php
include ('footer.inc.php');
?>
``` | Use ob\_start() in the first line even befor the include. so you can set headers anytime. | How can I redirect in PHP without header errors? | [
"",
"php",
"redirect",
"header",
""
] |
I'm just wondering what kind of queues are lists and dictionaries in C#. Whether they're FIFOs or LIFOs. | Lists and dictionaries are containers that don't support a queue model, that is, they're neither LIFO nor FIFO. Put another way, you're not comparing apples with apples. | In C#, if you want a LIFO (stack) use [System.Collections.Generic.Stack](http://msdn.microsoft.com/en-us/library/3278tedw.aspx), and if you want a FIFO (queue) use [System.Collections.Generic.Queue](http://msdn.microsoft.com/en-us/library/7977ey2c.aspx) | What kind of Queues are lists and dictionaries? | [
"",
"c#",
".net",
""
] |
The `FrameworkElement` object has `DataContextChanged` event. However, there is no `OnDataContextChanged` method that can be overridden.
Any ideas why? | If a method is virtual, then the user has the option to either augment the base functionalty by calling the base class method or replace the base class functionality by failing to call the base class method. For OnEvent() methods, if you don't call the base class method then the event will not be raised (that's the responsibility of the base class method.) If the base class performs some kind of state management inside of the OnEvent method, this means that the derived class can accidentally invalidate the state of the object if the user chooses to omit a call to the base class method. Documentation can specify "please always call the base class method", but there's no way to enforce it.
When I see an event that doesn't have a virtual OnEvent() method, I usually assume the method performs some kind of internal state management and the designers of the class want to guarantee their state management runs. This isn't the case in FrameworkElement, and it's not the only event that doesn't follow the pattern, so I'm curious what the reasoning is.
I dug around in Reflector to see if I could discover a reason. There *is* an OnDataContextChanged() method, but it's a dependency property change handler and doesn't follow the standard event pattern. This is probably the reason for not making it protected virtual. It's non-standard, so it would be confusing. It's static, so you wouldn't be able to override it anyway. Since it's called automatically by the dependency property framework and you are unable to override it, I believe we have the reason why it's private instead of static virtual.
You could use a different pattern to expose the normal event pattern:
```
class FrameworkElement
{
// difference: use DataContextPropertyChanged as the change callback
public static readonly DependencyProperty DataContextProperty = ...
protected virtual void OnDataContextChanged(...)
{
// raise the DataContextChanged event
}
private static void DataContextPropertyChanged(...)
{
((FrameworkElement)d).OnDataContextChanged(...);
}
}
```
My guess why they didn't do this? Usually you call OnEvent() to raise the event. The event is automatically raised when DataContext changes, and it doesn't make sense for you to raise it at any other time. | Good question.
I'm just guessing, but looking in Reflector I'd say it's just laziness, perhaps with a pinch of (unfounded?) performance concerns. `FrameworkElement` has a generic `EventHandlersStore` which is responsible for maintaining event information (delegates) for a whole bunch of events. The add and remove logic in the CLR events (such as `DataContextChanged`) simple call into the `EventHandlersStore` with the appropriate key.
There is a generic `RaiseDependencyPropertyChanged` method that is called to raise all different sorts of events. There is also a private `OnDataContextChanged` method that calls the `RaiseDependencyPropertyChanged` method. However, it is static and registered as part of the d-prop metadata.
So, in short, I see no technical reason not to include an overridable `OnDataContextChanged` method. Just looks like a short-cut in implementation to me.
Is this merely academic, or are you trying to achieve something here? | WPF - Why there is no "OnDataContextChanged" overridable method? | [
"",
"c#",
"wpf",
"datacontext",
""
] |
It's often needed to accomplish the following task: change the state of something, do action, then change the state back to original. For example, in Win32 GDI it's needed to change background color, then do some drawing, then change the color back.
It can be either done directly:
```
COLORREF oldColor = SetBkColor( deviceContext, newColor );
drawStuff( deviceContext );
SetBkColor( deviceContext, oldColor );
```
or via a bracket class that would do the forward change in the constructor and the backward change in the destructor:
```
CBkColorSwitcher switcher( deviceContext, newColor );
drawStuff( deviceContext );
//once control reaches end of block the switcher is destroyed and the change is reverted
```
The advantage of a bracket class is obvious - if an exception is thrown in between the changes the change is reverted correctly. What are the disadvantages? | I'm **nitpicking** here, but:
1. Code size, your code will be bigger because of the exception handler.
2. You need to write a lot of class to handle all sort of switches.
3. Bigger stack.
4. Always preforming code on all exceptions, even if its not need (for example you just want the application to crash) | This is in fact a well known and widely used C++ idiom known as [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization). Win32 APIs are C APIs and their implementation patterns are different. If you are programming in C++, it is better to handle resource allocation and deallocation using the RAII idiom, by writing thin wrappers on the C API or better re-use existing, well-designed C++ replacements. Java programmers can look upon RAII as a replacement for the *finally* clause. | What could be a reason to not use bracket classes in C++? | [
"",
"c++",
"raii",
""
] |
situation: A user inputs a user name and password. now the user enters a user name called Game\_Admin. Thus tries to imitate being a head power of the site and scam others.
At the moment My log in script check for Length Characteristics, and to see if it already exist. My question how do I go about checking to see if a player enters a specific grouping of characters in our example the grouping i am trying to stop duplication of is "Admin". So If the word Admin ever appears whether it is (myAdminaccount ,pizzaAdmin, GreatestAdmin). I am wondering would I use a loop of some sort to search through each user name character by character or is their another easier way?
Than you everyone for your suggestions Indeed there are many ways to go about this situation. I hope this topic can be a good reference for others who decide to use type if check. I am putting them all to the test and weighing out my options but I believe I have found the solution that works best for me :) | I'd suggest when a user signs up, check the username against a blacklist before accepting form submission. If you're using off-the-shelf software it probably supports this.
Test on PHP [strpos()](http://php.net/strpos) when form validation takes place:
```
$badlist = Array(
'admin',
'staff',
'official'
);
foreach($badlist as $badword){
if (strpos(strtolower($_POST['username']), $badword)!==FALSE)
die('fail');
}
```
Hope that helps :) | Have a look at [stristr](https://www.php.net/manual/en/function.stristr.php) for case-insensitive string matching:
```
<?php
$string = 'TehAdmin';
if(stristr($string, 'admin') === FALSE) {
echo '"admin" not found in string';
} else {
echo '"admin" found in string';
}
// outputs: "admin" found in string
?>
```
For extra entertainment, you can use [`str_ireplace`](http://www.php.net/manual/en/function.str-ireplace.php) to replace occurrences of admin with the empty string:
```
<?php
$string = str_ireplace("admin", "", $string);
?>
```
<http://www.php.net/manual/en/function.str-ireplace.php> | Checking a string to see if a specific grouping exist (PHP)? | [
"",
"php",
"mysql",
"string",
""
] |
I am having trouble with a SQL join question.
I have a table `EMPLOYEE` with `EmpID, FirstName, LastName, Email, Phone`
I have another table `OTHERNAME` with 2 fields `"Name" & "OtherName"`.
This table contains lookup values such as `"James", "Jim"; "Thomas", "Tom"; "Steven", "Steve"`.
I want to write a query which will return rows
```
EmpID, FirstName, LastName, Email, Phone, OtherName
where Employee.Firstname = OTHERName.Name
``` | ```
Select e.EmpID, e.FirstName, e.LastName, e.Email, e.Phone, o.OtherName
From Employee e
Left Outer Join OtherName o on e.FirstName = o.Name
```
From your comments it sounds like you actually want an outer join.
(From Comments) An outer join would return all employees, along with an Othername if there is one, otherwise Othername would be a null value which you could handle in code. An inner join limits the results to only employees with a matching record. | try this:
```
SELECT
e.EmpID
CASE
WHEN o.OtherName IS NOT NULL THEN OtherName
ELSE e.FirstName
END AS FirstName
,e.LastName
,e.Email
,e.Phone
,o.OtherName
FROM Employee e
LEFT OUTER JOIN OtherName o ON e.FirstName = o.Name
``` | SQL join related question | [
"",
"sql",
"join",
""
] |
I was wondering if there's any library for asynchronous method calls in [Python](http://en.wikipedia.org/wiki/Python_%28programming_language%29). It would be great if you could do something like
```
@async
def longComputation():
<code>
token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
doSomethingElse()
if token.finished():
result = token.result()
```
Or to call a non-async routine asynchronously
```
def longComputation()
<code>
token = asynccall(longComputation())
```
It would be great to have a more refined strategy as native in the language core. Was this considered? | You can use the [multiprocessing module](http://docs.python.org/library/multiprocessing.html#module-multiprocessing) added in Python 2.6. You can use pools of processes and then get results asynchronously with:
```
apply_async(func[, args[, kwds[, callback]]])
```
E.g.:
```
import time
from multiprocessing import Pool
def postprocess(result):
print("finished: %s" % result)
def f(x):
return x*x
if __name__ == '__main__':
pool = Pool(processes=1) # Start a worker processes.
result = pool.apply_async(f, [10], callback=postprocess) # Evaluate "f(10)" asynchronously calling callback when finished.
print("waiting...")
time.sleep(1)
```
This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this. | Something like:
```
import threading
thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # Will run "foo"
....
thr.is_alive() # Will return whether foo is running currently
....
thr.join() # Will wait till "foo" is done
```
See the documentation at <https://docs.python.org/library/threading.html> for more details. | Asynchronous method call in Python? | [
"",
"python",
"asynchronous",
"python-asyncio",
"coroutine",
""
] |
I'm writing a web application that's supposed to be embedded in other people's websites (kind of a widget). I'm using Google Analytics to track all the people that visit all instances of my script on the embedding websites. The problem is that I don't know how to use it so that it doesn't interfere with those websites' own Google Analytics accounts. I'm storing the tracker variable in a namespace, so I thought that should do it, but I haven't realized that GA stores its settings in cookies (\_\_utma, \_\_utmz etc.), and those cookies are used by both trackers, if there are two of them on the same page... So for example if I use \_setVar to store some kind of user-defined variable in Google Analytics, and the embedding site does the same, we overwrite each other's values...
Of course it would be easiest if Google provided a way to change the name of the cookies to a custom one, but I can't find any way to do it. I thought about using cookie domain or path to force a separate cookie, but this doesn't work, because if I set domain or path to something other than the real domain/path, then the cookie is not readable for the page after reload...
Does anyone know a way to have two trackers on one page and make them use separate cookies so that they don't overwrite each other's settings?
Or, if that's completely impossible - is there any other analytics service with similar functionality as GA in which this is possible? (it would have to have advanced features like event and campaign tracking...) | Now made easy with the new asynchronous tracking code. :)
<https://developers.google.com/analytics/devguides/collection/gajs/#MultipleCommands> | You can install multiple instances of the Google Analytics tracking code on your web pages to send data to multiple properties in your account.
<https://support.google.com/analytics/answer/1032400?hl=en>
Or you can get creative and do the following per Google's instructions. <https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced#multipletrackers>
```
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-XXXX-Y', 'auto');
ga('create', 'UA-XXXX-Y', 'auto', {'name': 'newTracker'});
ga('send', 'pageview');
ga('newTracker.send', 'pageview');
</script>
``` | google analytics - multiple trackers on one page (cookie conflict) | [
"",
"javascript",
"cookies",
"google-analytics",
"widget",
""
] |
My unit tests are in a separate directory tree from my integration tests, but with the same package structure. My integration tests need external resources (e.g. a server) to be available, but my unit tests are properly independent of each other and the environment.
In IntelliJ-IDEA (v7) I have defined a JUnit Run/Debug Configuration to run all the tests in the top-level package, and this of course picks up my integration tests which fail.
I want to define a run-junit configuration that runs all my unit tests. Any ideas? | The answer is to create a test suite that contains only those tests underneath the unit test folder and run that instead. There is a junit-addon which does just this called [DirectorySuiteBuilder](http://junit-addons.sourceforge.net/junitx/util/DirectorySuiteBuilder.html) but I only found this after I had pretty much re-invented the wheel.
And it's already been asked here!
```
import junit.framework.JUnit4TestAdapter;
import junit.framework.TestSuite;
import java.io.File;
import java.io.IOException;
public class DirectoryTestSuite {
static final String rootPath = "proj\\src\\test\\java\\";
static final ClassLoader classLoader = DirectoryTestSuite.class.getClassLoader();
public static TestSuite suite() throws IOException, ClassNotFoundException {
final TestSuite testSuite = new TestSuite();
findTests(testSuite, new File(rootPath));
return testSuite;
}
private static void findTests(final TestSuite testSuite, final File folder) throws IOException, ClassNotFoundException {
for (final String fileName : folder.list()) {
final File file = new File( folder.getPath() + "/" +fileName);
if (file.isDirectory()) {
findTests(testSuite, file);
} else if (isTest(file)) {
addTest(testSuite, file);
}
}
}
private static boolean isTest(final File f) {
return f.isFile() && f.getName().endsWith("Test.java");
}
private static void addTest(final TestSuite testSuite, final File f) throws ClassNotFoundException {
final String className = makeClassName(f);
final Class testClass = makeClass(className);
testSuite.addTest(new JUnit4TestAdapter(testClass));
}
private static Class makeClass(final String className) throws ClassNotFoundException {
return (classLoader.loadClass(className));
}
private static String makeClassName(final File f) {
return f.getPath().replace(rootPath, "").replace("\\", ".").replace(".java", "");
}
}
``` | IntelliJ IDEA CE 10.5 has a (new?) option to run all tests inside a configured directory:
 | Run all tests in a source tree, not a package | [
"",
"java",
"unit-testing",
"junit",
"intellij-idea",
""
] |
My mouse wheel does not work when putting a `ListBox` in a `ScrollViewer`.
Does the `ListBox` somehow "steal" this event?
```
<ScrollViewer VerticalScrollBarVisibility="Auto" Style="{StaticResource myStyle}">
<ListBox>
<ListBoxItem>Test 1</ListBoxItem>
<ListBoxItem>Test 2</ListBoxItem>
<ListBoxItem>Test 3</ListBoxItem>
<ListBoxItem>Test 4</ListBoxItem>
<ListBoxItem>Test 5</ListBoxItem>
<ListBoxItem>Test 6</ListBoxItem>
<ListBoxItem>Test 7</ListBoxItem>
</ListBox>
</ScrollViewer>
```
Edit: as requested by Joel, added the reason why I did this..
I did this because I don't like what the `ListBox`'s internal `ScrollViewer` does with my layout. I have a background image, and on top of that a `ListBox` as shown here:
[alt text http://robbertdam.nl/share/1.png](http://robbertdam.nl/share/1.png)
Now when the scrollbar appears, the following happens:
[alt text http://robbertdam.nl/share/2.png](http://robbertdam.nl/share/2.png)
I've created a Style for a `ScrollViewer` that shows the scroll bar *on top* of the `ListBox` item's content. In the `ListBox` item's datatemplate I've reserved some space for the scrollbar to appear.
Thanks,
Robbert Dam | Firstly, I think you need to elaborate on what your limitations are and what you're trying to achieve. Without that, I can only explain why what you're doing isn't working. Somebody may even have a better idea about how to get the result you're after.
If you put `ListBox` inside a `ScrollViewer`, then the [control template](http://msdn.microsoft.com/en-us/library/aa970773.aspx) for `ListBox` still has its own `ScrollViewer` inside. When the mouse cursor is over the `ListBox` and you scroll the mousewheel, that event bubbles up until it reaches the `ScrollViewer` that's part of `ListBox`. That one handles it by scrolling and marks the event as handled, so then the `ScrollViewer` you put the `ListBox` inside of ignores the event.
If you make the `ListBox` taller and narrower than the outer `ScrollViewer`, and give it enough items so that the `ListBox` itself can scroll the items, you'll see 2 vertical scroll bars: 1 in the `ListBox`, and 1 outside the `ListBox` for your outer `ScrollViewer`. When the mouse cursor is inside the `ListBox`, the `ListBox` will scroll the items with its internal `ScrollViewer`, and its `Border` will stay in place. When the mouse cursor is outside the `ListBox` and inside the outer `ScrollViewer`, that `ScrollViewer` will scroll its contents -- the `ListBox` -- which you can verify by noting that the `ListBox`'s `Border` changes position.
If you want an outer `ScrollViewer` to scroll the entire `ListBox` control (including the `Border` and not just the items), you'll need to re-style the `ListBox` so that it does not have an internal `ScrollViewer`, but you'll also need to make sure it automatically gets bigger according to its items.
I don't recommend this approach for a couple reasons. It might make sense if there are other controls inside the `ScrollViewer` along with the `ListBox`, but your sample does not indicate that. Also, if you're going to have a lot of items in the `ListBox`, you'll be creating `ListBoxItem`s for every single one, eliminating any advantage that the default, non-re-styled `ListBox` gives you due to the default `VirtualizingStackPanel`.
Please let us know what your actual requirements are.
---
**Edit:** Ok, now I have a little better idea, with the addition of those images. The effect you're getting is that when there are enough items to scroll and the scrollbar appears, the available area has to shrink a bit horizontally because the `ScrollViewer`'s template uses a `Grid`. These seem to be your options, in order of lesser-to-better:
1. Re-style the `ListBox` to not have a `ScrollViewer` and use your re-styled `ScrollViewer` outside the `ListBox`. You'd then also have to force the `ListBox` to also be tall enough to show every item in that same `Style`, and now you've lost UI virtualization. If you're going to be showing hundreds of items in the list, you *definitely* don't want to lose that.
2. Re-style the `ListBox` and set the `ControlTemplate` to use a `ScrollViewer` with the style you already created for it that puts the scrollbar over the content rather than in a separate column. This one's ok (`ListBox` gets to limit its height and use a `VirtualizingStackPanel`, yay), but as you said, it necessitates awareness of that in your `DataTemplate`.
3. Re-style the `ScrollViewer` to leave space for vertical scrollbar even when it is not visible. Here's what this option looks like:
By default, `ScrollViewer` uses 2 columns in a `Grid` equivalent to this:
```
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
```
So the `Width` of the scrollbar's column is 0 when the scrollbar is not visible since `Width="Auto"`. To leave space for the scrollbar even when it is hidden, we bind the `Width` of that column to the `Width` of the vertical scroll bar:
```
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition
Width="{Binding ElementName=PART_VerticalScrollBar, Path=Width}" />
</Grid.ColumnDefinitions>
```
So now the `ControlTemplate` in the custom `Style` for `ScrollViewer` might look like this:
```
<ControlTemplate
TargetType="{x:Type ScrollViewer}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition
Width="{Binding ElementName=PART_VerticalScrollBar, Path=Width}" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition
Height="Auto" />
</Grid.RowDefinitions>
<ScrollContentPresenter />
<ScrollBar
Grid.Column="1"
Name="PART_VerticalScrollBar"
Value="{TemplateBinding VerticalOffset}"
Maximum="{TemplateBinding ScrollableHeight}"
ViewportSize="{TemplateBinding ViewportHeight}"
Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}" />
<ScrollBar
Name="PART_HorizontalScrollBar"
Orientation="Horizontal"
Grid.Row="1"
Value="{TemplateBinding HorizontalOffset}"
Maximum="{TemplateBinding ScrollableWidth}"
ViewportSize="{TemplateBinding ViewportWidth}"
Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}" />
</Grid>
</ControlTemplate>
```
You could even make the content column a fixed size and the scrollbar column `Width="*"`, which might work better in the long run if your image is not stretched. Now the `DataTemplate` does not have to compenstate for the width of a scrollbar, as it gets a consistent area to use whether the scrollbar is visible or not.
You'll probably want to check out the rest of the [example `ControlTemplate` for `ScrollViewer`](http://msdn.microsoft.com/en-us/library/aa970847.aspx), but those examples are not the default styles. *Note that the example puts the vertical scrollbar on the left! Also note the comment at the bottom about `ContentScrollPresenter`.* | I was dealing with the same issue. I set the *ListBox.ItemsPanel* Property, without any *ScrollViewer*:
```
<ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
<ListBox>
<ListBox.Template>
<ControlTemplate TargetType="ItemsControl">
<Border>
<ItemsPresenter />
</Border>
</ControlTemplate>
</ListBox.Template>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<\ListBox>
<\ScrollViewer>
```
Hope this helps. | Putting ListBox in ScrollViewer: mouse wheel does not work | [
"",
"c#",
"wpf",
"xaml",
"listbox",
"scrollviewer",
""
] |
I am interested, if it is possible to have collection with same elements in .Net configuration.
Like this, for example:
```
<RetrySettings>
<RetryTurn PeriodBeforeRetry="0:05:00"/>
<RetryTurn PeriodBeforeRetry="0:10:00"/>
<RetryTurn PeriodBeforeRetry="0:30:00"/>
<RetryTurn PeriodBeforeRetry="1:00:00"/>
<RetryTurn PeriodBeforeRetry="4:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
<RetryTurn PeriodBeforeRetry="8:00:00"/>
</RetrySettings>
```
without adding annoying `id="someUniqueId"` attributes to each `RetryTurn` member?
I don't see how to make this, using custom collection, derived from `ConfigurationElementCollection`... Any possible solution for this? | Finally I found the workaround.
In `RetryTurn` class define internal `Guid` property `UniqueId` and initialize it with new `Guid` value in default constructor:
```
public class RetryTurnElement : ConfigurationElement
{
public RetryTurnElement()
{
UniqueId = Guid.NewGuid();
}
internal Guid UniqueId { get; set; }
...
}
```
In `RetryTurnCollection` class override `GetElementKey` method like this:
```
public class RetryTurnCollection : ConfigurationElementCollection
{
protected override object GetElementKey(ConfigurationElement element)
{
return ((RetryTurnElement)element).UniqueId;
}
...
}
``` | Have you tried
```
public class RetryTurnCollection : ConfigurationElementCollection
{
protected override object GetElementKey(ConfigurationElement element)
{
return element;
}
...
}
``` | Collection with equal elements in .Net configuration section | [
"",
"c#",
".net",
"configuration",
"collections",
""
] |
Why I get the following warning for the following code :)
Code:
```
_stprintf(m_szFileNamePath,_T("%s"),strFileName);
```
> warning C4996: '\_swprintf': swprintf has been changed to conform with the ISO C standard, adding an extra character count parameter. To use traditional Microsoft swprintf, set \_CRT\_NON\_CONFORMING\_SWPRINTFS.
I know \_strprintf is a macro which if \_UNICODE is defined will evaluate to \_swprintf else it will be sprintf.
Now what is this \_swprintf. There is a function swprintf, but why is \_stprintf evaluating to \_swprintf instead of swprintf.
What is the difference b/w the \_xxx and xxx functions?
**EDIT:**
Okay there are two definitions for the UNICODE version of \_stprintf, which one is included?
The one in tchar.h or strsafe.h? | <http://msdn.microsoft.com/en-us/library/ybk95axf%28VS.80%29.aspx>
> swprintf is a wide-character version of sprintf; the pointer arguments to swprintf are wide-character strings. Detection of encoding errors in swprintf may differ from that in sprintf. swprintf and fwprintf behave identically except that swprintf writes output to a string rather than to a destination of type FILE, and swprintf requires the count parameter to specify the maximum number of characters to be written. The versions of these functions with the \_l suffix are identical except that they use the locale parameter passed in instead of the current thread locale.
>
> In Visual C++ 2005, swprintf conforms to the ISO C Standard, which requires the second parameter, count, of type size\_t. To force the old nonstandard behavior, define \_CRT\_NON\_CONFORMING\_SWPRINTFS. In a future version, the old behavior may be removed, so code should be changed to use the new conformant behavior. | Maybe this?
```
_stprintf(m_szFileNamePath, 256, _T("%s"), strFileName);
``` | Microsoft _stprintf warning | [
"",
"c++",
"visual-c++",
"printf",
""
] |
i am having problems integrating ITK - Insight Toolkit into another image processing pipeline. ITK itself is a medical image processing toolkit and uses cmake as build system. My image pipeline project uses cmake as well. According to the user manual of ITK it is favorable to use the "UseITK.cmake" file in the build (out of source) directory of ITK. You can do that by adding the following lines the CMakeList.txt of your own project.
```
# 'SET(ITK_DIR ...)' if 'FIND_PACKAGE(ITK REQUIRED)' fails
FIND_PACKAGE(ITK REQUIRED)
INCLUDE(${ITK_USE_FILE})
```
My problem is, this approach points to the current installtion of ITK, but i have to integrate itk completly into my project, without dependencies outside my project.
Is there a build option in the cmake build system of itk, which dumps/delivers all the header and lib files into a build directory, so i can place them into my project on my own.
I have a lib and header include structure i do not want to break. I already tried to to manually copy the lib and header files into my project but it didn't work out.
I am new to itk and cmake so this question might sound vague. I hope you guys can help me anyway.
Thanks in advance!
Best regards,
zhengtonic | I don't know if you're still having the problem, but here's an easy way:
Build the ITK project, and then "make install" (or build the INSTALL.vcproj project in VS), and it will write to a directory you pass as CMAKE\_INSTALL\_PREFIX while configuring your project. This directory will contain /bin, /lib and /include. You can import those into your project directly. | Using CMAKE\_INSTALL\_PREFIX to point to you base directory is the best solution.
When you issue "make install" all the headers/configurationfiles/libraries will be copied over. | Integrate ITK (Insight Toolkit) into own project | [
"",
"c++",
"image-processing",
"integration",
"cmake",
"itk",
""
] |
Is it possible to use SHA256CryptoServiceProvider and related SHA2 providers on Windows XP? I know the providers use the cryptography services that are included in Vista and above is it possible to install these services in XP from Microsoft?
**EDIT:** I should've provided more information the documentation on the MSDN is wrong in regards to this being supported in Windows XP. See <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=355031> where this is acknowledged and accepted by Microsoft as by design. However there is no work around listed anywhere (that I saw) so I wasn't sure if it's possible to install the services this requires to work properly or if it's like tilting at windwills trying to install IIS 6 or 7 on WinXP. | It seems that MSDN documentation is right in the sense that it *should* be supported in XP SP3 by design, and if it is not, it's only because of a **bug** in .NET 3.5.
Both AesCryptoServiceProvider and SHA256CryptoServiceProvider use the same cryptograhics service named "Microsoft Enhanced RSA and AES Cryptographic Provider". Under XP, the name of the service is slightly different: **"Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)"**. The constructor of AesCryptoServiceProvider performs a simple check:
```
string providerName = "Microsoft Enhanced RSA and AES Cryptographic Provider";
if(Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor == 1)
{
providerName = "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)";
}
```
The constructors of SHAxxxCryptoServiceProvider classes do **not** check the (Prototype) name, and this is why they fail in XP. If they did, they would succeed.
There is a simple workaround on a given PC. Go to registry key **HKEY\_LOCAL\_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider**, find its subkey named "Microsoft Enhanced RSA and AES Cryptographic Provider (Prototype)", export it to .reg, edit this .reg and delete " (Prototype)" from its name. When you import it back, the original key will be duplicated to the new key without (Prototype), with the same contents. From now on, SHA256CryptoServiceProvider will work on this XPSP3 machine. | I've had success with the following snippet, although I'm not really satisfied with it and nearly posted an SO question concerning the various seemingly haphazard ways to instantiate `SHA512` at the time. This is tested on Windows XP, 7, and possibly Vista (can't remember).
```
using System.Security.Cryptography;
SHA512 hash;
try
{
hash = new SHA512Cng( );
}
catch ( PlatformNotSupportedException )
{
hash = SHA512.Create( );
}
```
I think this should work the same with `SHA256`.
Also, comparing the output of both versions with a unix sha2 utility suggested that they both correctly implement SHA512. | SHA256CryptoServiceProvider and related possible to use on WinXP? | [
"",
"c#",
"security",
"encryption",
"sha256",
""
] |
The standard example for implementing LRU Cache in Java points to the example depot url
<http://www.exampledepot.com/egs/java.util/coll_Cache.html>
How is removeEldestEntry called by default after just adding a new entry in the code snippet below?
```
final int MAX_ENTRIES = 100;
Map cache = new LinkedHashMap(MAX_ENTRIES+1, .75F, true) {
// This method is called just after a new entry has been added
public boolean removeEldestEntry(Map.Entry eldest) {
return size() > MAX_ENTRIES;
}
};
// Add to cache
Object key = "key";
cache.put(key, object);
// Get object
Object o = cache.get(key);
if (o == null && !cache.containsKey(key)) {
// Object not in cache. If null is not a possible value in the cache,
// the call to cache.contains(key) is not needed
}
// If the cache is to be used by multiple threads,
// the cache must be wrapped with code to synchronize the methods
cache = (Map)Collections.synchronizedMap(cache);
``` | In this example, the `LinkedHashMap` is being extended with an ["anonymous inner class"](http://java.sun.com/docs/books/tutorial/uiswing/events/generalrules.html#innerClasses).
The `removeEldestEntry` method is overriding the super-class's version, which always returns `false` (indicating the eldest entry should not be removed). The overriding version returns `true` if the size of the map exceeds the limit, indicating that the oldest entry should be removed. | Per the [Java API for `LinkedHashMap`](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html):
> The `removeEldestEntry(Map.Entry)` method may be overridden to impose a policy for removing stale mappings automatically when new mappings are added to the map.
Specifically:
> This method is invoked by `put` and `putAll` after inserting a new entry into the map.
Also note:
> This method typically does not modify the map in any way, instead allowing the map to modify itself as directed by its return value. It is permitted for this method to modify the map directly, but if it does so, it must return false (indicating that the map should not attempt any further modification). The effects of returning true after modifying the map from within this method are unspecified. | Question about LRU Cache implementation in Java | [
"",
"java",
"caching",
"lru",
""
] |
I want some variables to be global across the project and accessible in every form. How can I do this? | yes you can by using static class.
like this:
```
static class Global
{
private static string _globalVar = "";
public static string GlobalVar
{
get { return _globalVar; }
set { _globalVar = value; }
}
}
```
and for using any where you can write:
```
GlobalClass.GlobalVar = "any string value"
``` | The consensus here is to put the global variables in a static class as static members. When you create a new Windows Forms application, it usually comes with a Program class (Program.cs), which is a static class and serves as the main entry point of the application. It lives for the the whole lifetime of the app, so I think it is best to put the global variables there instead of creating a new one.
```
static class Program
{
public static string globalString = "This is a global string.";
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
```
And use it as such:
```
public partial class Form1 : Form
{
public Form1()
{
Program.globalString = "Accessible in Form1.";
InitializeComponent();
}
}
``` | C# - Winforms - Global Variables | [
"",
"c#",
"winforms",
"global-variables",
""
] |
Is there an easy way to take a dynamic decimal value and create a validation regular expression that can handle this?
For example, I know that `/1[0-9]{1}[0-9]{1}/` should match anything from 100-199, so what would be the best way to programmatically create a similar structure given any decimal number?
I was thinking that I could just loop through each digit and build one from there, but I have no idea how I would go about that. | Ranges are difficult to handle correctly with regular expressions. REs are a tool for text-based analysis or pattern matching, not semantic analysis. The best that you can probably do safely is to recognize a string that is a number with a certain number of digits. You can build REs for the maximum or minimum number of digits for a range using a base 10 logarithm. For example, the match a number between *a* and *b* where *b* > *a*, construct the RE by:
```
re = "[1-9][0-9]{"
re += str(log10(a)-1)
re += "-"
re += str(log10(b)-1)
re += "}"
```
**Note**: the example is in no particular programming language. Sorry, C# not really spoken here.
There are some boundary point issues, but the basic idea is to construct an RE like `[1-9][0-9]{1}` for anything between 100 and 999 and then if the string matches the expression, convert to an integer and do the range analysis in value space instead of lexical space.
With all of that said... I would go with Mehrdad's solution and use something provided by the language like `decimal.TryParse` and then range check the result. | ^[-]?\d+(.\d+)?$
will validate a number with an optional decimal point and / or minus sign at the front | Regular expression to match a decimal value range | [
"",
"c#",
"regex",
"validation",
""
] |
I know this has a really simple explanation, but I've been spoiled by not having to use pointers for a while.
Why can't I do something like this in c++
```
int* b;
foo(b);
```
and initialize the array through...
```
void Something::foo(int* a)
{
a = new int[4];
}
```
after calling foo(b), b is still null. why is this? | Pointers are passed to the function *by value*. Essentially, this means that the pointer value (but not the pointee!) is copied. What you modify is only the copy of the original pointer.
There are two solutions, both using an additional layer of indirection:
1. Either you use a reference:
```
void f(int*& a) {
a = new int[4];
}
```
2. Or you pass in a pointer-to-pointer (less conventional for out parameters as in your case):
```
void f(int** pa) {
*pa = new int[4];
}
```
And call the function like this:
```
f(&a);
```
**Personally, I dislike both styles**: parameters are for function *input*, output should be handled by the return value. So far, I've yet to see a compelling reason to deviate from this rule in C++. So, my advise is: use the following code instead.
```
int* create_array() {
return new int[4];
}
``` | You pass parameter to foo by value. Change to
```
foo(int*& a)
``` | Why can I not initialize an array by passing a pointer to a function? | [
"",
"c++",
"pointers",
""
] |
I want to do something like:
```
foo = {
'foo': 1,
'zip': 2,
'zam': 3,
'bar': 4
}
if ("foo", "bar") in foo:
#do stuff
```
How do I check whether both `foo` and `bar` are in dict `foo`? | Well, you could do this:
```
>>> if all(k in foo for k in ("foo","bar")):
... print "They're there!"
...
They're there!
``` | ```
if {"foo", "bar"} <= myDict.keys(): ...
```
If you're still on Python 2, you can do
```
if {"foo", "bar"} <= myDict.viewkeys(): ...
```
If you're still on a *really* old Python <= 2.6, you can call `set` on the dict, but it'll iterate over the whole dict to build the set, and that's slow:
```
if set(("foo", "bar")) <= set(myDict): ...
``` | How do I check that multiple keys are in a dict in a single pass? | [
"",
"python",
"dictionary",
""
] |
I'm new to Javascript and Mootools and am having a bit of trouble understanding some things, especially since the documentation on Mootools is, shall we say, lacking at best.
My question is regarding the $ selector.
Why is it that I can chain some properties to it, and not others?
For example why does
```
$('results').style.border = "1px solid #000000";
```
work, but
```
$('results').innerHTML = "foo";
```
does not?
Thanks in advance. | The first example is not really an example of "chaining".
`style` is a DOM-standard object representing the CSS style of an element. It has nothing to do with MooTools - it's just standard dot notation for accessing properties of objects.
"Chaining" is when the result of an operation on an object returns the object itself after the operation, allowing you to do stuff like this:
```
$('id').show().move_left(200).fadeOut();
```
Lastly, that second example ought to work. You should post the actual source. | Triptych's answer is great. I just want to help you get more moo out of mootools.
```
$('results').setStyle('border','1px solid #000');
$('results').set('html','foo');
// all together now
$('results').setStyle('border','1px solid #000').set('html','foo');
```
You don't want to use innerHTML anymore if you're grabbing elements with $ (or using any framework, really).
Functions return something when they are called. Most methods (functions) in mootools return the thing it alters (like $('results')), so you can chain another function onto it.
Your examples aren't chaining. They are simply selecting properties of your object, not calling methods.
---
Mootools documentation is fantastic. You're just not familiar with the language enough yet. Mootools is considered to have a steeper learning curve, so that might be part of the problem.
I was like you, new to both mootools and javascript generally. After trudging through for a while I figured mootools out, and, unknowingly, learned javascript at the same time. The docs were integral to that. | Understanding $ in Mootools | [
"",
"javascript",
"mootools",
""
] |
I'm new to Django (and Python) and I have been trying to work out a few things myself, before jumping into using other people's apps. I'm having trouble understanding where things 'fit' in the Django (or Python's) way of doing things. What I'm trying to work out is how to resize an image, once it's been uploaded. I have my model setup nicely and plugged into the admin, and the image uploads fine to the directory:
```
from django.db import models
# This is to list all the countries
# For starters though, this will be just United Kingdom (GB)
class Country(models.Model):
name = models.CharField(max_length=120, help_text="Full name of country")
code = models.CharField(max_length=2, help_text="This is the ISO 3166 2-letter country code (see: http://www.theodora.com/country_digraphs.html)")
flag = models.ImageField(upload_to="images/uploaded/country/", max_length=150, help_text="The flag image of the country.", blank=True)
class Meta:
verbose_name_plural = "Countries"
def __unicode__(self):
return self.name
```
The thing I'm now having trouble with is taking that file and making a new file into a thumbnail. Like I say, I'd like to know how to do it without using others' apps (for now). I have got this code from DjangoSnippets:
```
from PIL import Image
import os.path
import StringIO
def thumbnail(filename, size=(50, 50), output_filename=None):
image = Image.open(filename)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
# get the thumbnail data in memory.
if not output_filename:
output_filename = get_default_thumbnail_filename(filename)
image.save(output_filename, image.format)
return output_filename
def thumbnail_string(buf, size=(50, 50)):
f = StringIO.StringIO(buf)
image = Image.open(f)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
image = image.resize(size, Image.ANTIALIAS)
o = StringIO.StringIO()
image.save(o, "JPEG")
return o.getvalue()
def get_default_thumbnail_filename(filename):
path, ext = os.path.splitext(filename)
return path + '.thumb.jpg'
```
...but this has ultimately confused me... As I don't know how this 'fits in' to my Django app? And really, is it the best solution for simply making a thumbnail of an image that has been successfully uploaded? Can anyone possibly show me a good, solid, decent way that a beginner like me can learn to do this properly? As in, knowing where to put that sort of code (models.py? forms.py? ...) and how it would work in context? ... I just need a bit of help understanding and working this problem out.
Thank you! | If it's OK for you, there is a Django application ready, doing exactly what you want:
<https://github.com/sorl/sorl-thumbnail> | This is what I use in my models to save a new thumbnail if the uploaded image has changed. It's based of another DjangoSnippet but it I can't remember who wrote the orginal - if you know please add a comment so that I can credit them.
```
from PIL import Image
from django.db import models
from django.contrib.auth.models import User
import os
import settings
class Photo_Ex(models.Model):
user = models.ForeignKey(User, blank=True, null=True)
photo = models.ImageField(upload_to='photos')
thumbnail = models.ImageField(upload_to='profile_thumb', blank=True,
null=True, editable=False)
def save(self, *args, **kwargs):
size = (256,256)
if not self.id and not self.photo:
return
try:
old_obj = Photo_Ex.objects.get(pk=self.pk)
old_path = old_obj.photo.path
except:
pass
thumb_update = False
if self.thumbnail:
try:
statinfo1 = os.stat(self.photo.path)
statinfo2 = os.stat(self.thumbnail.path)
if statinfo1 > statinfo2:
thumb_update = True
except:
thumb_update = True
pw = self.photo.width
ph = self.photo.height
nw = size[0]
nh = size[1]
if self.photo and not self.thumbnail or thumb_update:
# only do this if the image needs resizing
if (pw, ph) != (nw, nh):
filename = str(self.photo.path)
image = Image.open(filename)
pr = float(pw) / float(ph)
nr = float(nw) / float(nh)
if image.mode not in ('L', 'RGB'):
image = image.convert('RGB')
if pr > nr:
# photo aspect is wider than destination ratio
tw = int(round(nh * pr))
image = image.resize((tw, nh), Image.ANTIALIAS)
l = int(round(( tw - nw ) / 2.0))
image = image.crop((l, 0, l + nw, nh))
elif pr < nr:
# photo aspect is taller than destination ratio
th = int(round(nw / pr))
image = image.resize((nw, th), Image.ANTIALIAS)
t = int(round(( th - nh ) / 2.0))
image = image.crop((0, t, nw, t + nh))
else:
# photo aspect matches the destination ratio
image = image.resize(size, Image.ANTIALIAS)
image.save(self.get_thumbnail_path())
(a, b) = os.path.split(self.photo.name)
self.thumbnail = a + '/thumbs/' + b
super(Photo_Ex, self).save()
try:
os.remove(old_path)
os.remove(self.get_old_thumbnail_path(old_path))
except:
pass
def get_thumbnail_path(self):
(head, tail) = os.path.split(self.photo.path)
if not os.path.isdir(head + '/thumbs'):
os.mkdir(head + '/thumbs')
return head + '/thumbs/' + tail
def get_old_thumbnail_path(self, old_photo_path):
(head, tail) = os.path.split(old_photo_path)
return head + '/thumbs/' + tail
``` | Image resizing with django? | [
"",
"python",
"django",
"image",
"python-imaging-library",
""
] |
I have tried to do it without success.
**Is it possible ?** | The way to do this is to set the `EnableHeadersVisualStyles` flag for the data grid view to `False`, and set the background colour via the `ColumnHeadersDefaultCellStyle.BackColor` property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):
```
_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;
```
If you do not set the `EnableHeadersVisualStyles` flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is [here](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.enableheadersvisualstyles.aspx?ppud=4). | ```
dataGridView1.EnableHeadersVisualStyles = false;
dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
``` | How to change the color of winform DataGridview header? | [
"",
"c#",
".net",
"winforms",
"datagridview",
""
] |
Is there a standard way to simulate a table creation in a database by using SQL? I don't want the table to be created, just check if it could be created.
One way would be to create it and then delete it again.
Any other way? | Most major servers support transactional DDL, so you can do something along these lines:
```
begin transaction
create table Foo ...
rollback transaction
```
Theoretically, in case of error it should be reported back to client, but table will not be created altogether. | Depends on the SQL DBMS you're interested in. For example Postgres supports transactional DDL and the following will work:
```
START TRANSACTION;
CREATE TABLE ... ();
<check for error here>
ROLLBACK;
``` | Simulate a table creation with SQL | [
"",
"sql",
"database",
"ddl",
""
] |
I am wondering how do I disable javascript when using selenium so I can test server side validation.
I found this article but I don't know what to really do. Like I make this javascript file then what?
<http://thom.org.uk/2006/03/12/disabling-javascript-from-selenium/> | ## Edit
In the meantime better alternatives did arise, please see the other answers e.g. <https://stackoverflow.com/a/7492504/47573> .
## Original answer
Other possibilities would be:
* Write your application to support disabling JavaScript (yes, the **web** application).
Sounds crazy? Isn't. In our development process we're doing exactly this, implementing features without JS until all are there, then spice up with JS. We usually provide a hook within all templates which can control from a single point to basically which JS off/on from the web application itself. And, yes, the application is hardly recognizable without JS enabled, but it's the best way to ensure things work properly. We even write Selenium tests for it, for both versions; NOJS and JS. The NOJS are so quickly implemented that they don't matter compared to what it takes to write sophisticated JS tests ...
* Modify the appropriate browser profile to have JS disabled. I.e. for FF you can tell Selenium which profile to use; you can load this profile normally, disable JS in about:config and feed this profile as default profile to Selenium RC. | This is a way to do it if you use WebDriver with FireFox:
```
FirefoxProfile p = new FirefoxProfile();
p.setPreference("javascript.enabled", false);
driver = new FirefoxDriver(p);
``` | How to disable Javascript when using Selenium? | [
"",
"javascript",
"selenium",
"firefox",
""
] |
the situation is like this i have a control and it has event Render in the definition of the control, to this event is attached handler i am looking for a way to show some kind of message if in some class that uses this control another handler is attached to this event
Best Regards,
Iordan | This does not strike me as a good approach. When using events, the control should typically not be dependent on the number of event handlers attached. It should work regardless of whether there are 0 or 27 event handlers reacting on the event. If you want to have a mechanism where you have more control you should probably consider using a delegate instead.
If you for some reason are restricted to use the event model and want to have control over the assignment of event handlers, one approach might be to inherit the original class, creating an event in that class with the same name and signature as in the base class (using the `new` keyword so that the original event is hidden), and keep track of how event handlers are attached and detached:
```
public class BaseClass
{
public event EventHandler SomeEvent;
}
public class MyClass : BaseClass
{
private int _refCount = 0;
public new event EventHandler SomeEvent
{
add
{
if (_refCount > 0)
{
// handler already attached
}
base.SomeEvent += value;
_refCount++;
}
remove
{
base.SomeEvent -= value;
_refCount--;
}
}
}
``` | dont expose the event publicly. expose it as a property. this will give you control when external classes are attaching handlers
class MyClass
{
private EventHandler \_myEvent;
```
public event EventHandler MyEvent
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
_myEvent = (EventHandler)Delegate.Combine(_myEvent, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
_myEvent = (EventHandler)Delegate.Remove(_myEvent, value);
}
}
...
```
}
more info on this here
<http://msdn.microsoft.com/en-us/magazine/cc163533.aspx> | Avoid attaching event again | [
"",
"c#",
"winforms",
"events",
""
] |
I have a C/C++ program that might be hanging when it runs out of memory. We discovered this by running many copies at the same time. I want to debug the program without completely destroying performance on the development machine. Is there a way to limit the memory available so that a new or malloc will return a NULL pointer after, say, 500K of memory has been requested? | Try turning the question on its head and asking how to limit the amount of memory an OS will allow your process to use.
Try looking into <http://ss64.com/bash/ulimit.html>
Try say:
ulimit -v
Here is another link that's a little old but gives a little more back ground:
<http://www.network-theory.co.uk/docs/gccintro/gccintro_77.html> | One way is to write a wrapper around malloc().
```
static unsigned int requested =0;
void* my_malloc(size_tamount){
if (requested + amount < LIMIT){
requested+=amount;
return malloc(amount);
}
return NULL
}
```
Your could use a #define to overload your malloc.
As GMan states, you could overload new / delete operators as well (for the C++ case).
Not sure if that's the best way, or what you are looking for | How do I force a program to appear to run out of memory? | [
"",
"c++",
"linux",
"debugging",
"memory-management",
""
] |
Today I came a cross an article by [Eric Lippert](http://blogs.msdn.com/ericlippert) where he was trying to clear the myth between the operators precedence and the order of evaluation. At the end there were two code snippets that got me confused, here is the first snippet:
```
int[] arr = {0};
int value = arr[arr[0]++];
```
Now when I think about the value of the variable value, I simply calculate it to be one. Here's how I thought it's working.
1. First declare arr as an array of int
with one item inside of it; this
item's value is 0.
2. Second get the value of arr[0] --0 in
this case.
3. Third get the value of arr[the value
of step 2] (which is still 0) --gets
arr[0] again --still 0.
4. Fourth assign the value of step 3
(0) to the variable value. --value =
0 now
5. Add to the value of step 2 1 --Now
arr[0] = 1.
Apparently this is wrong. I tried to search the c# specs for some explicit statement about when the increment is actually happening, but didn't find any.
The second snippet is from a comment of Eric's [blog post](http://blogs.msdn.com/ericlippert/archive/2009/08/10/precedence-vs-order-redux.aspx) on the topic:
```
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
```
Now here's how I think this program will execute --after declaring the array and assigning 1 to i. [plz bear with me]
1. Get data[i] --1
2. Add to the value of step 1 the value
5 --6
3. Assign to data[i] (which is still 1)
the value of step 2 --data[i] = 6
4. Increment i -- i = 2
According to my understanding, this array now should contain the values {11, **27**, 33}. However, when I looped to print the array values I got: {11, 38, 33}. This means that the **post** increment happened before dereferencing the array!
How come? Isn't this post increment supposed to be post? i.e. happen after everything else.
What am I missing guys? | The postincrement operation occurs as part of evaluating the overall expression. It's a side effect which occurs after the value is evaluated but before any other expressions are evaluated.
In other words, for any expression E, E++ (if legal) represents something like (pseudo-code):
```
T tmp = E;
E += 1;
return tmp;
```
That's *all* part of evaluating E++, before anything else is evaluated.
See section 7.5.9 of the C# 3.0 spec for more details.
---
Additionally, for assignment operations where the LHS is classified as a variable (as in this case), the LHS is evaluated *before* the RHS is evaluated.
So in your example:
```
int[] data = { 11, 22, 33 };
int i = 1;
data[i++] = data[i] + 5;
```
is equivalent to:
```
int[] data = { 11, 22, 33 };
int i = 1;
// Work out what the LHS is going to mean...
int index = i;
i++;
// We're going to assign to data[index], i.e. data[1]. Now i=2.
// Now evaluate the RHS
int rhs = data[i] + 5; // rhs = data[2] + 5 == 38
// Now assign:
data[index] = rhs;
```
The relevant bit of the specification for this is section 7.16.1 (C# 3.0 spec). | For the first snippet, the sequence is:
1. Declare arr as you described:
2. Retrieve the value of arr[0], which is 0
3. Increment the value of arr[0] to 1.
4. Retrieve the value of arr[(result of #2)] which is arr[0], which (per #3) is 1.
5. Store that result in `value`.
6. value = 1
For the second snippet, the evaluation is still left-to-right.
1. Where are we storing the result? In data[i++], which is data[1], but now i = 2
2. What are we adding? data[i] + 5, which is now data[2] + 5, which is 38.
The missing piece is that "post" doesn't mean "after EVERYTHING else." It just means "immediately after I retrieve the current value of that variable." A post increment happening "in the middle of" a line of code is completely normal. | int[] arr={0}; int value = arr[arr[0]++]; Value = 1? | [
"",
"c#",
"operator-precedence",
""
] |
I'd like to create a small IF procedure that will check if Twitter is available (unlike now, for example), and will return true or false.
Help :) | ```
function urlExists($url=NULL)
{
if($url == NULL) return false;
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $httpcode >= 200 && $httpcode < 300;
}
```
This was grabbed from [this post](http://www.wrichards.com/blog/2009/05/php-check-if-a-url-exists-with-curl/) on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly. | Here's one:
<http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=8&txtCodeId=1786>
Another:
```
function ping($host, $port, $timeout) {
$tB = microtime(true);
$fP = fSockOpen($host, $port, $errno, $errstr, $timeout);
if (!$fP) { return "down"; }
$tA = microtime(true);
return round((($tA - $tB) * 1000), 0)." ms";
}
//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("www.google.com", 80, 10);
``` | Ping site and return result in PHP | [
"",
"php",
"ping",
""
] |
OK, this is a little unusual, because ANY Java EE container can do the simple things I want to do (XML processing, JPA, Hibernate, SOAP/REST web services, etc). This is for personal use, more to gain skills than to accomplish essential functionality. I have my own Linux server (Ubuntu Jaunty x86\_64) with business class internet, so I can install pretty much anything.
I use Tomcat a lot now, however, I ran into a few situations lately job hunting where they were looking for experience in a specific Java EE container (which defeats the whole purpose of having a standard), and of course not the same one each time.
So what I'm looking for is a Java EE server that:
1. Is in demand in the marketplace right now
2. Is free (or- Is not too horrendous (disk space, time) to install and to deploy applications on
- Runs on Ubuntu x86\_64
I've been able to glean some information [via Indeed's keyword search](http://www.indeed.com/jobtrends?q=tomcat%2C+weblogic%2C+websphere%2C+jetty%2C+glassfish%2C+jboss&l=), and that tells me to stay away from Jetty/Glassfish, even though they fit "lightweight" and "free". I also see [from this SO post](https://stackoverflow.com/questions/252082/what-would-be-the-best-way-to-match-up-two-object-instances-between-two-different) that WebSphere is a steaming pantload of bloatware that's hard to deploy/configure, but I don't know if that's accurate or current. I like Tomcat (completely FOSS, smallish, easy to deploy, plenty of docs/users), but it's less in demand than some of the bigger boys.
So what would you recommend I install? Thanks in advance. | Far too often, I've seen servers like JBoss and WebSphere (I've worked with them for the last 5 years now) rush to market with broken implementations. Unfortunantely, the part that is broken might be very small, but it will be just what you will be breaking your head on.
Oracle Weblogic just kicked the hell out of me with a broken implementation of MDBs (annotations).
If you want a server that is the most Java EE 5 compliant, will give you the least heartache and pretty much production-worthy, go for Glassfish and yes... use Netbeans as your dev IDE. | My personal recommendation is [JBoss](http://www.jboss.org/). Not only is this a solid server, but there are other JBoss Platforms and Frameworks that easily integrate into JBoss. One example is JBoss ESB. | Which Java EE server should I use? | [
"",
"java",
"jakarta-ee",
""
] |
My main HTML page does the following:
```
var popup = window.open(...);
// Wait for popup to load
popup.onload = function() { do_something(); };
popup.location = "new-page.html";
```
I'd like `do_something` to be called when `new-page.html` is finished loading. But what I currently have doesn't work -- `do_something` is never called.
How can I make this work?
I only care about getting this to work in Firefox 3.5, if that makes things easier. | you could use window.opener.<functionName> and put your notification code within that function on the parent page | Have you tried using the opener object?
<http://www.webreference.com/js/tutorial1/opener.html> | How can I notify the parent page when a popup has finished a load which the parent initated? | [
"",
"javascript",
"html",
"dom-events",
""
] |
Does GreaseMonkey have something built in so you can store data per-site or per-page? For example, say you wanted to tweak StackOverflow.com so you can add a note to each of the questions in your favorites list and sort on that note. Does GreaseMonkey have something built-in to store those notes? Or perhaps can the scripts self-modify, such that you just define an array or object and keep the data there? | Yes - [GM\_setValue](http://wiki.greasespot.net/GM_setValue).
> This method allows user script authors to persist simple values across page-loads.
> Strings, booleans, and integers are currently the only allowed data types | The values are restricted to the simple datatypes: string, boolean and integer. The values will be stored in Firefox preferences (located in about:config) which is not designed for storing huge amounts of data.
<http://wiki.greasespot.net/GM_setValue>
If GM\_setValue doesn't cut it the linked question/answers shows other great possibilities: [alternatives to GM\_setValue](https://stackoverflow.com/questions/2562972/storing-data-when-using-greasemonkey) | Storing data in Greasemonkey scripts | [
"",
"javascript",
"greasemonkey",
""
] |
I would like to crop and resize my image. Here is my code:
```
Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg");
// Crop and resize the image.
Rectangle destination = new Rectangle(0, 0, 200, 120);
Graphics graphic = Graphics.FromImage(image);
graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
```
Now I assume that my resulting cropped/resized image is stored in the *graphics* object. The question is - how do I save it to a file? | The `Graphics` object that you get from `Graphics.FromImage` is a drawing surface for the image. So you can simply save the image object when you are done.
```
string fileName = AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg");
using (Image image = Image.FromFile(fileName)
{
using (Graphics graphic = Graphics.FromImage(image))
{
// Crop and resize the image.
Rectangle destination = new Rectangle(0, 0, 200, 120);
graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
}
image.Save(fileName);
}
```
Beware though that doing this repeatedly on a jpg image may not be a good thing; the image is re-encoded each time and since jpg uses a destructive compression method you will lose some image quality each time. I wouldn't worry about that if this is a once-per-image operation though. | No, the `Graphics` object doesn't contain any image data, it's used to draw on a canvas, which usually is the screen or a `Bitmap` object.
So, you need to create a `Bitmap` object with the correct size to draw on, and create the `Graphics` object for that bitmap. Then you can save it. Remember that object implementing `IDisposable` should be disposed, for example using the `using` clause:
```
using (Image image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle.jpg")) {
// Create bitmap
using (Bitmap newImage = new Bitmap(200, 120)) {
// Crop and resize the image.
Rectangle destination = new Rectangle(0, 0, 200, 120);
using (Graphics graphic = Graphics.FromImage(newImage)) {
graphic.DrawImage(image, destination, int.Parse(X1.Value), int.Parse(Y1.Value), int.Parse(Width.Value), int.Parse(Height.Value), GraphicsUnit.Pixel);
}
newImage.Save(AppDomain.CurrentDomain.BaseDirectory + "Cropper/tests/castle_icon.jpg", ImageFormat.Jpeg);
}
}
``` | Graphics object to image file | [
"",
"c#",
"asp.net",
"system.drawing",
""
] |
I'm using uploadify, and i can't set sessions in my php files, my script looks like this:
```
$("#uploadify").uploadify({
'uploader' : '/extra/flash/uploadify.swf',
'script' : '/admin/uploads/artistsphotos',
'scriptData' : {'PHPSESSID' : '<?= session_id(); ?>'},
'cancelImg' : '/images/cancel.png',
'folder' : '/img/artists',
'queueID' : 'fileQueue',
'auto' : false,
'multi' : true,
'onComplete' : function(a, b, c, d, e){
},
'onAllComplete': function(event,data){
$bla = $('#art').find(':selected',this);
$fi = $bla.val();
$.ajax({
type: "POST",
url: "/admin/uploads/artistsphotosupload",
data: "artist="+$fi,
success: function(msg){
console.log(msg);
}
});
}
});
```
And in php if i try:
```
$_SESSION['name'] = 'something';
```
I can't access it in another file.and i have session\_start(); activated
Any solutions? | Usually the session ID won't be read from POST.
You could do this:
```
$_COOKIE['PHPSESSID'] = $_POST['PHPSESSID'];
session_start();
``` | you cannot solve this because uploadify has own session ID which is created by flash player. In other words the flash player access the uploadify script as a new user and gets a new session. The only way you can solve this is to pass current page session\_id through post to the uploadify script. | Sessions and uploadify | [
"",
"php",
"jquery",
"session",
"uploadify",
""
] |
I am trying to return a 401 error code from a webapp to trigger a basic authentication process, but tomcat is hijacking the response to display its status report page.
Is there a way to prevent tomcat from doing this and let the error code go all the way to the browser?
UPDATE
My mistake: I forgot the WWW-Authenticate header | Setting the response status to 401 will only tell the browser "forbidden", and tomcat will display the error page. It will not in itself trigger the authentication process.
To trigger auth, you need to add another header to the response:
```
httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"MyApp\"");
```
where "MyApp" is the name of your desired HTTP auth realm. Add that header, and the browser will popup an auth dialog and retry the request.
You should be aware that tomcat will still have sent the error page along with the headers, it's just that the browser won't display it as long as the response contains the auth header. | Unhappy with the default error pages that come with Tomcat ? You can define your own custom error pages in your web.xml file. In the example shown below, we define 2 web pages -- server\_error.html and file\_not\_found.html -- which will be displayed when the server encounters an error 500 or an error 404 respectively.
```
<error-page>
<error-code>500</error-code>
<location>/server_error.html</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/file_not_found.html</location>
</error-page>
```
You should bear in mind, however, that the order of the tags for the web.xml file is very important. If the order in your web.xml file is incorrect, Tomcat will output errors on startup
source: <http://linux-sxs.org/internet_serving/c581.html> | Avoiding tomcat status report | [
"",
"java",
"tomcat",
"tomcat6",
""
] |
I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn't there, the program should create a new file instead of throwing an exception. | ```
System.IO.File.WriteAllText (@"D:\path.txt", contents);
```
* If the file exists, this overwrites it.
* If the file does not exist, this creates it.
* Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception. | Use the [`File.WriteAllText`](http://msdn.microsoft.com/en-us/library/ms143375.aspx) method. It creates the file if it doesn't exist and overwrites it if it exists. | Write string to text file and ensure it always overwrites the existing content. | [
"",
"c#",
"file",
"text",
""
] |
Hi suppose these 2 methods:
```
private List<IObjectProvider> GetProviderForType(Type type)
{
List<IObjectProvider> returnValue = new List<IObjectProvider>();
foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders)
{
if ((provider.Key.IsAssignableFrom(type) ||
type.IsAssignableFrom(provider.Key)) &&
provider.Value.SupportsType(type))
{
returnValue.Add(provider.Value);
}
}
return returnValue;
}
private IEnumerable<IObjectProvider> GetProviderForType1(Type type)
{
foreach (KeyValuePair<Type, IObjectProvider> provider in _objectProviders)
if ((provider.Key.IsAssignableFrom(type) ||
type.IsAssignableFrom(provider.Key)) &&
provider.Value.SupportsType(type))
yield return provider.Value;
}
```
Which one is quicker? When I look at the first method, I see that the memory is allocated for List, what in my opinion it's not needed. The **IEnumerable** method seems to be quicker to me.
For instance, suppose you call
```
int a = GetProviderForType(myType).Count;
int b = GetProviderForType1(myType).Count();
```
Now, another issue is, is there a performance difference between these 2 above?
What do you think? | In this particular case, using the `IEnumerable<T>` form will be more efficient, because you *only* need to know the count. There's no point in storing the data, resizing buffers etc if you don't need to.
If you needed to use the results again for any reason, the `List<T>` form would be more efficient.
Note that both the `Count()` extension method and the `Count` property will be efficient for `List<T>` as the implementation of `Count()` checks to see if the target sequence implements `ICollection<T>` and uses the `Count` property if so.
Another option which should be even *more* efficient (though only just) would be to call the overload of `Count` which takes a delegate:
```
private int GetProviderCount(Type type)
{
return _objectProviders.Count(provider =>
(provider.Key.IsAssignableFrom(type)
|| type.IsAssignableFrom(provider.Key))
&& provider.Value.SupportsType(type));
}
```
That will avoid the extra level of indirections incurred by the `Where` and `Select` clauses.
(As Marc says, for small amounts of data the performance differences will probably be negligible anyway.) | An important part of this question is "how big is the data"? How many rows...
For small amounts of data, list is fine - it will take negligible time to allocate a big enough list, and it won't resize many times (none, if you can tell it how big to be in advance).
However, this doesn't scale to huge data volumes; it seems unlikely that your provider supports thousands of interfaces, so I wouldn't say it is **necessary** to go to this model - but it won't hurt hugely.
Of course, you can use LINQ, too:
```
return from provider in _objectProviders
where provider.Key.IsAssignableFrom(type) ...
select provider.Value;
```
This is also the deferred `yield` approach under the covers... | C# List<T> vs IEnumerable<T> performance question | [
"",
"c#",
"performance",
"list",
"ienumerable",
""
] |
Imagine I'm making a simple Word Processor with Java Swing. I've got a set of Actions written to perform text justification. On the MenuBar I've got a menu:
```
View
Left Justify
Center Jusitfy
Right Justify
```
This consists of JRadioButtonMenuItems and a ButtonGroup to ensure only one item is selected at any one time.
Also, imagine I've got an equivalent toolbar consisting of JToggleButtons and again a ButtonGroup to ensure only only button can be active at any one time.
The "Left Justify" JRadioButtonMenu and JToggleButton are initialised using the same Action, and so on with the other items.
My question is this: what is the best method for syncronizing the two groups? If I click "Right Justify" icon on the toolbar, I want the group in the Menu to be updated accordingly, and vice versa. | I after a lot of searching I found information [here](http://weblogs.java.net/blog/zixle/archive/2005/11/changes_to_acti.html). Basically, you can add this to your action's actionPerformed method:
```
action.putValue(Action.SELECTED_KEY, Boolean.TRUE);
```
And this will do all the work for you!
Unfortunately the official Sun tutorials don't cover this aspect (or at least I didn't spot it), hence the difficulty in spotting such a simple approach to resolving my problem. | [Observer pattern](http://en.wikipedia.org/wiki/Observer_pattern) my friend. The menu bar observe the toolbar, and the toolbar observe the menu bar. They will both be observer and observable. Each one has his own listener which, on a change event, notify the observer (the other one) with the new value in parameter.
One of the great advantage of the observer pattern is that there is very low coupling, so you don't need a lot of refactoring to implement the linking, to modify it or to remove it in the future. | Sync JMenu ButtonGroups with JToolbar ButtonGroups | [
"",
"java",
"swing",
"menu",
"toolbar",
"action",
""
] |
I've written a sharepoint application that needs to change web.config
I have a feature that is supposed to make all these configurations. The code for that feature is like this:
```
SPSite site = properties.Feature.Parent as SPSite;
List<SPWebConfigModification> modifications = new List<SPWebConfigModification>();
modifications.AddRange(CustomErrorsModeConfig.Modifications);
webConfigModificationHelper.AddWebConfigModifications(site.WebApplication, modifications);
```
CustomErrorsModeConfig.Modifications property contains this code:
```
public static SPWebConfigModification[] Modifications = {
new SPWebConfigModification()
{
Owner = WebConfigModificationOwner,
Name = "mode",
Type = SPWebConfigModification.SPWebConfigModificationType.EnsureAttribute,
Path = "system.web/customErrors",
Sequence = 0,
Value = "Off"
}
};
```
Then finally the webConfigModificationHelper.AddWebConfigModifications method:
```
foreach (SPWebConfigModification modification in modifications)
{
webApp.WebConfigModifications.Add(modification);
}
webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
webApp.Update();
```
The problem is that I keep getting this error:
```
Name cannot begin with the ''' character, hexadecimal value 0x27. Line 1, position 1453
```
Could this be a problem with the web.config before I try to apply my changes ?
Could the SPWebConfigModification property be incorrectly defined ?
Is there some glitch in my code that leads to this error ?
Might there be some property I am missing (e.g. web.AllowUnsafeUpdates) ?
Some sharepoint site configuration ?
I've been trying to solve this issue for some time now with no luck :( Any ideas ? | I can recommend using [stsadmwebconfig](http://stsadmwebconfig.codeplex.com/) for making changes to web.config files. I've implemented this in many features and it has always been a pain, especially while developing. Using this tool makes it a lot easier. | Ive seen this before when the file format is not correctly set between the file and the declaration.
Open the web.config file into a advanced text editor (Notepad++ or Visual Studio) and manually force the file type to match what is specified. Usually its going to be UTF-8.
For more info:
<http://www.dumpsterdoggy.com/tutorials/?xmlexception-name-cannot-begin-with> | Sharepoint web.config changes using SPWebConfigModification | [
"",
"c#",
"sharepoint",
"web-config",
""
] |
I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this? | Neater still, instead of the `typical href="#"` or `href="javascript:void"` or `href="whatever"`, I think this makes much more sense:
```
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
<a href="no-javascript.html" title="Get some foo!" id="foo">Show me some foo</a>
```
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of `href="#"`, visiting the same page in the case of `href=""`) is eliminated. | The simplest answer of all is...
```
<a href="javascript:alert('You clicked!')">My link</a>
```
Or to answer the question of calling a javascript function:
```
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
<a href="javascript:myFunction('You clicked!')">My link</a>
``` | call javascript function on hyperlink click | [
"",
"javascript",
"hyperlink",
""
] |
I have to remove a selected item in an editorgrid. First the store is loaded and the user can choose to add or delete blank rows to this grid which they can then edit. The problem is not with removing initial records loaded from the store. The problem comes in when I add an additional row, edit it and then choose to remove it (user may decide he doesn't need this row after all).
It seems that when I would like to save changes using store.getModifiedRecords, it still sees the row that was deleted and so processes it as well. Here is the button remove:
```
442
443 text:'Remove',
444 tooltip:'Remove attribute',
445 iconCls:'silk-table_delete',
446 handler: function() {
447 var selectedItem = attributeEditor.getSelectionModel().getSelected();
448
449 // Check if we have selected item
450 if (selectedItem) {
451 // Get selected item value
452 var attribute = selectedItem.get('Name');
453
454 // Remove selected
455 attributeStore.remove(selectedItem);
456
457 // Add to our removed attributes hash
458 if (id) {
459 RemovedAttributes.push(attribute);
460 }
461 } else {
462 wispUserFormWindow.getEl().mask();
463
464 // Display error
465 Ext.Msg.show({
466 title: "Nothing selected",
467 msg: "No attribute selected",
468 icon: Ext.MessageBox.ERROR,
469 buttons: Ext.Msg.CANCEL,
470 modal: false,
471 fn: function() {
472 wispUserFormWindow.getEl().unmask();
473 }
474 });
475 }
476 }
477 }
``` | This is how the store.getModifiedRecords() works. The modified records records are stored in a array called modified in store object. When you remove an item from the store it is not removed by default.
Here is the actual remove() from store
```
remove : function(record){
var index = this.data.indexOf(record);
this.data.removeAt(index);
if(this.pruneModifiedRecords){
this.modified.remove(record);
}
if(this.snapshot){
this.snapshot.remove(record);
}
this.fireEvent("remove", this, record, index);
}
```
This means that the item is removed from the modified list only if you specify the pruneModifiedRecords option value as true. This value is false by default as mentioned in the Store API.
If you want the newly added item to be removed from the modified list you have to set the value of pruneModifiedRecords as true when creating the store
Ex:
```
var stote = new Ext.data.SimpleStore({
fields: [],
data: [],
pruneModifiedRecords: true
})
``` | ```
store.load();
//remove function will delete specific record.
store.remove(store.findRecord("item_id","1"));
store.sync();
```
i think the following link can help you with easy way how to handle store
<http://www.aswedo.net/sencha-touch/sencha-touch-adding-records-reading-data-and-deleting-records-to-store/> | Extjs - Remove newly added selected item from store | [
"",
"javascript",
"extjs",
"grid",
""
] |
I am parsing an xml file using php simplexml\_load\_file() and then inserting the desired data in a mysql ISAM table. The problem is that the code works "most" of the times, with 500 internal server errors here and there. The XML file that I am trying to process is big (around 50 MB), and it yields around 25000 rows in the mysql table when it works. When I get the error, the script inserts anything from a few rows to a few thousand rows.
Anyway, here is the code, I would appreciate it if someone has any insight into this, or has an alternative way, I don't know, maybe batch processing or something like that.
```
<?php
include ("myconnection.php");
mysql_query("DELETE FROM mytable") or die(mysql_error());
echo "data deleted, now insert: <br /><br />";
//the url for the feed:
$feed = 'cachy/copy.xml';
echo "myfeed: ".$feed;
echo "<br />";
// Load the feed
$xml = simplexml_load_file($feed);
if ($xml != null)
{
echo "<br />Success! feed available!<br /><br />";
}
else
{
echo "<br />Couldn't fetch the content<br /><br />";
die;
}
//die;
//ini_set("memory_limit","256M");
//set_time_limit(120);
function clean($input)
{
$input = trim($input);
$input = htmlentities($input, ENT_QUOTES);
$input = mysql_escape_string($input);
$input = EscapeShellCmd($input);
return $input;
}
//insert data from feed
foreach($xml->xpath('//product') as $products)
{
$product_name = clean($products->product_name);
mysql_unbuffered_query("INSERT INTO mytable (onsaledate, onsaletime, eventdate, eventtime, buyat_short_deeplink_url, product_name, level1, level2, VenueName, VenueDMAID)VALUES (\"$products->OnsaleDate\",\"$products->OnsaleTime\",\"$products->EventDate\",\"$products->EventTime\",\"$products->buyat_short_deeplink_url\",\"$product_name\",\"$products->level1\",\"$products->level2\",\"$products->VenueName\",\"$products->VenueDMAID\")") or die(mysql_error());
}
mysql_close($myConnection);
echo "records inserted my man!";
die;
```
Thanks in advance for your help! | What error do you get?
Also, it will run *much* faster if you:
1. Replace `DELETE FROM table` with `TRUNCATE table` (assuming you can re-use IDs)
2. Insert multiple rows at once, like this
INSERT INTO table (col1, col2) VALUES
(val1, val2),
(val1a, val1b),
... | Looks like your php is not showing all errors. Try adding this:
```
error_reporting(E_ALL);
```
This should print all errors.
Xslt (@Greg) is a good option. | parsing xml and insert data in mysql table | [
"",
"php",
"mysql",
"xml",
""
] |
Imagine table t1 have 2 cols:
```
col1 col2
--------------
test 900 1
test 901 2
test 902 3
user 901 4
test 909 5
```
I want to find just one row by 2 params (name, code) where name its (test, user ..etc) and code - (901, 902, null, .. etc).
There could not be more than one row of the same (Code,name) - I Mean there Are no 2 rows that have "test 901" in Col1.
Code:
```
declare
name varchar2(30);
code varchar(10);
col_val varchar2(30);
col2_val numeric;
begin
name:= 'test';
code := '900';
select col1, col2 into col_val, col2_val
from t1
where
( REGEXP_LIKE(col1, name||'\s+'||code) -- (3)
or (
not REGEXP_LIKE(col1, name||'\s+'||code) -- (1)
and REGEXP_LIKE(col1, name) -- (2)
)
)
order by col1;
DBMS_OUTPUT.PUT_LINE('val:'||col_val||' id:'||col2_val);
end;
```
1) for test values name:= 'test' code := '900' the result should be "val:test 900 id:1" - It's OK.
2) BUT for name:= 'test' code := **'909'** the result should be "val:test 909 **id:5**", but I got "val:test 900 id:1" ( the first row with Name='Test' ) - It's NOT want I want.
3) and in case name:= 'test' code := **'999'** the result should be "val:test 900 id:1" (there are NO 999 code, so I need just any row that have Name='test' inside).
The main question is WHY oracle Ignores (1) clause for 2) example?
Perhaps I'm doing something wrong - so it would be great if You could show my mistake! | This condition:
```
(REGEXP_LIKE(col1, :name || '\s+' || :code)
OR (NOT REGEXP_LIKE(col1, :name || '\s+' || :code) AND REGEXP_LIKE(col1, :name))
```
will match all rows in your example.
When searching for `test 909`, you are matching `'test 909' OR (NOT 'test 909' AND 'test')`. This will match every row starting from `'test'` (either per first condition or per second).
Since you are using `rownum = 1`, the first column matched in returned, in your case `'test 900'`
If you want a fallback match (return `'test 909'` if it exists, any `'test'` otherwise), use this:
```
SELECT *
FROM (
SELECT *
FROM t1
WHERE REGEXP_LIKE(col1, name || '\s+' || code)
UNION ALL
SELECT *
FROM t1
WHERE REGEXP_LIKE(col1, name)
)
WHERE rownum = 1
```
, or, if you don't like `UNION`s:
```
SELECT *
FROM (
SELECT *
FROM t1
WHERE REGEXP_LIKE(col1, name)
ORDER BY
CASE WHEN REGEXP_LIKE(col1, name || '\s+' || code) THEN 0 ELSE 1 END
)
WHERE rownum = 1
```
The latter one, though, is less efficient, since it has to sort. | You cannot combine ROWNUM and ORDER BY like this, because the ROWNUM is the row number *before* it gets sorted.
You need to get more verbose and write something like
```
select a.* from (
select * from table order by col1 ) a
where rownum = 1;
```
Check the documentation for ROWNUM and paging. | "Smart" where clause for filtering values (Oracle 10g) | [
"",
"sql",
"oracle",
""
] |
I have a Picture box inside a Groupbox in my form with the Picture of a radar set as the background picture. My intention is to dynamically load tiny Jpeg images within the radar area (overlaid) at runtime but I am unsure as to the best way to achieve this.
All crazy ideas welcomed (but I would prefer sane easy to do ones).
Thank you all. | It depends a lot on what your "radar" needs to look like, but almost certainly you'll need to implement the Paint event handler, and draw the contents of the radar display yourself. A picture box will only get you so far ("not very").
GDI+ is very easy to use to draw circles, lines, text, and images, and will give you complete control over how your display looks. | As for actual example:
```
// Among others
using System.Collections.Generic;
using System.Drawing;
using System.IO;
class TinyPic {
public readonly Image Picture;
public readonly Rectangle Bounds;
public TinyPic(Image picture, int x, int y) {
Picture = picture;
Bounds = new Rectangle(x, y, picture.Width, picture.Height);
}
}
class MyForm : Form {
Dictionary<String, TinyPic> tinyPics = new Dictionary<String, TinyPic>();
public MyForm(){
InitializeComponent(); // assuming Panel myRadarBox
// with your background is there somewhere;
myRadarBox.Paint += new PaintEventHandler(OnPaintRadar);
}
void OnPaintRadar(Object sender, PaintEventArgs e){
foreach(var item in tinyPics){
TinyPic tp = item.Value;
e.Graphics.DrawImageUnscaled(tp.Picture, tp.Bounds.Location);
}
}
void AddPic(String path, int x, int y){
if ( File.Exists(path) ){
var tp = new TinyPic(Image.FromFile(path), x, y);
tinyPics[path] = tp;
myRadarBox.Invalidate(tp.Bounds);
}
}
void RemovePic(String path){
TinyPic tp;
if ( tinyPics.TryGetValue(path, out tp) ){
tinyPics.Remove(path);
tp.Picture.Dispose();
myRadarBox.Invalidate(tp.Bounds);
}
}
}
```
This of course is very basic, assumes image source is path and doesn't take care of many intricate things, but that's the quick and dirty jist of it which you can certainly build on. | What would be the best way to simulate Radar in C#? | [
"",
"c#",
".net",
"winforms",
"graphics",
""
] |
I need to provide synchronization to some members of a structure.
If the structure is something like this
```
struct SharedStruct {
int Value1;
int Value2;
}
```
and I have a global variable
```
SharedStruct obj;
```
I want that the write from a processor
```
obj.Value1 = 5; // Processor B
```
to be immediately visible to the other processors, so that when I test the value
```
if(obj.Value1 == 5) { DoSmth(); } // Processor A
else DoSmthElse();
```
to get the new value, not some old value from the cache.
First I though that if I use **volatile** when writing/reading the values, it is enough. But I read that volatile can't solve this kind o issues.
The members are guaranteed to be properly aligned on 2/4/8 byte boundaries, and writes should be atomic in this case, but I'm not sure how the cache could interfere with this.
Using memory barriers (mfence, sfence, etc.) would be enough ? Or some interlocked operations are required ?
Or maybe something like
```
lock mov addr, REGISTER
```
?
The easiest would obviously be some locking mechanism, but speed is critical and can't afford locks :(
**Edit**
Maybe I should clarify a bit. The value is set only once (behaves like a flag). All the other threads need just to read it. That's why I think that it may be a way to force the read of this new value without using locks.
Thanks in advance! | All the other answers here seem to hand wave about the complexities of updating shared variables using mutexes, etc. It is true that you want the update to be atomic.
And you could use various OS primitives to ensure that, and that would be good
programming style.
However, on most modern processors (certainly the x86), writes of small, aligned scalar values *is* atomic and immediately visible to other processors due to cache coherency.
So in this special case, you don't need all the synchronizing junk; the hardware does the
atomic operation for you. Certainly this is safe with 4 byte values (e.g., "int" in 32 bit C compilers).
So you could just initialize Value1 with an uninteresting value (say 0) before you start the parallel threads, and simply write other values there. If the question is exiting the loop on a fixed value (e.g., if value1 == 5) this will be perfectly safe.
If you insist on capturing the *first* value written, this won't work. But if you have a parallel set of threads, and *any* value written other than the uninteresting one will do, this is also fine. | There Ain't No Such Thing As A Free Lunch. If your data is being accessed from multiple threads, and it is necessary that updates are immediately visible by those other threads, then you have to protect the shared struct by a mutex, or a readers/writers lock, or some similar mechanism.
Performance is a valid concern when synchronizing code, but it is trumped by correctness. Generally speaking, aim for correctness first and then profile your code. Worrying about performance when you haven't yet nailed down correctness is premature optimization. | Synchronizing access to variable | [
"",
"c++",
"multithreading",
"memory",
"multicore",
"parallel-processing",
""
] |
Let's say I have this :
```
def a(dict):
locals().update(dict)
print size
def b():
size = 20
f(locals())
```
What do I have to do to access the `size` variable directly from the `a` function? I know of :
```
size = dict["size"]
```
but I think there should be a more direct way. I tried using `locals().update(dict)` but it didn't work. Is there a betteer way ? | The Python compiler optimizes access to local variables by recognizing at compile time whether the barenames a function is accessing are local (i.e., barenames assigned or otherwise bound within the function). So if you code:
```
def lv1(d):
locals().update(d)
print zap
```
the compiler "knows" that barename `zap` is NOT local (not assigned in function `lv1`) and so it compiles code to access it as a global instead -- whatever `d` contains won't matter.
If you prefer slow and bloated code, you can defeat the optimization by using an `exec` inside the function -- when the compiler sees the keyword `exec`, it KNOWS you're trying to make your code as slow, bloated and buggy as possible, and so it cooperates by not optimizing in any way, just about.
So, the following code works as you desire:
```
def lv1(d):
exec ""
locals().update(d)
print zap
lv1({'zap': 23})
```
it emits `23` as you want.
I hope it's clear from the above "deadpan humor" that the technique is not recommended, but I'd better spell it out very explicitly: for the dubious syntactic pleasure of writing `print zap` in lieu of `print locals()['zap']`, you ARE paying a hefty price in terms of performance. Still, like all sorts of dangerous tools that can be useful in rare use cases for really experienced guru-level programmers who really truly know what they're doing and why, `exec` is there, available for you to use (or mis-use) at your whim: Python does NOT stand in your way!-) | You can use closures to access the scope of another function:
```
def b():
def a():
print size
size = 20
a()
```
The trick is to stack functions which belongs together in each other. This way the inner function a can access the local variables of the outer function b.
But I don't know what you're really up to so I'm not sure if this helps. | How can I pass my locals and access the variables directly from another function? | [
"",
"python",
"variables",
"function",
"language-features",
""
] |
While investigating Ruby I came across this to create a simple Struct-like class:
```
Person = Struct.new(:forname, :surname)
person1 = Person.new('John', 'Doe')
puts person1 #<struct Person forname="John", surname="Doe">
```
Which raised a few Python questions for me. I have written a [VERY] basic clone of this mechanism in Python:
```
def Struct(*args):
class NewStruct:
def __init__(self):
for arg in args:
self.__dict__[arg] = None
return NewStruct
>>> Person = Struct('forename', 'surname')
>>> person1 = Person()
>>> person2 = Person()
>>> person1.forename, person1.surname = 'John','Doe'
>>> person2.forename, person2.surname = 'Foo','Bar'
>>> person1.forename
'John'
>>> person2.forename
'Foo'
```
1. Is there already a similar mechanism in Python to handle this? (I usually just use dictionaries).
2. How would I get the `Struct()` function to create the correct `__init__()` arguments. (in this case I would like to perform `person1 = Person('John', 'Doe')` Named Arguments if possible: `person1 = Person(surname='Doe', forename='John')`
I Would like, as a matter of interest, to have Question 2 answered even if there is a better Python mechanism to do this. | An update of ThomasH's variant:
```
def Struct(*args, **kwargs):
def init(self, *iargs, **ikwargs):
for k,v in kwargs.items():
setattr(self, k, v)
for i in range(len(iargs)):
setattr(self, args[i], iargs[i])
for k,v in ikwargs.items():
setattr(self, k, v)
name = kwargs.pop("name", "MyStruct")
kwargs.update(dict((k, None) for k in args))
return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()})
```
This allows parameters (and named parameters) passed into `__init__()` (without any validation - seems crude):
```
>>> Person = Struct('fname', 'age')
>>> person1 = Person('Kevin', 25)
>>> person2 = Person(age=42, fname='Terry')
>>> person1.age += 10
>>> person2.age -= 10
>>> person1.fname, person1.age, person2.fname, person2.age
('Kevin', 35, 'Terry', 32)
>>>
```
## Update
Having a look into how [`namedtuple()`](http://docs.python.org/library/collections.html#collections.namedtuple) does this in [collections.py](http://svn.python.org/view/python/trunk/Lib/collections.py?view=markup). The class is created and expanded as a string and evaluated. Also has support for pickling and so on, etc. | If you're using Python 2.6, try the standard library [namedtuple](http://docs.python.org/library/collections.html#collections.namedtuple) class.
```
>>> from collections import namedtuple
>>> Person = namedtuple('Person', ('forename', 'surname'))
>>> person1 = Person('John', 'Doe')
>>> person2 = Person(forename='Adam', surname='Monroe')
>>> person1.forename
'John'
>>> person2.surname
'Monroe'
```
**Edit:** As per comments, there is a [backport for earlier versions of Python](http://code.activestate.com/recipes/500261/) | Class factory to produce simple struct-like classes? | [
"",
"python",
"struct",
"class-factory",
""
] |
I have a problem in my current Zend Framework application.
In my Bootstrap I register these routes:
```
protected function _initRouter()
{
$this->bootstrap("FrontController");
$frontController = $this->getResource("FrontController");
$route = new Zend_Controller_Router_Route(
":module/:id",
array(
"controller" => "index",
"action" => "index"
),
array("id" => "\d+")
);
$frontController->getRouter()->addRoute('shortcutOne', $route);
$route = new Zend_Controller_Router_Route(
":module/:controller/:id",
array("action" => "index"),
array("id" => "\d+")
);
$frontController->getRouter()->addRoute('shortcutTwo', $route);
$route = new Zend_Controller_Router_Route(
":module/:controller/:action/:id",
null,
array("id" => "\d+", "action" => "\w+")
);
$frontController->getRouter()->addRoute('shortcutThree', $route);
}
```
Now later I added Zend\_Navigation to my project. I have several modules, that register navigation elements in the module bootstrap:
```
<?php
class Contact_Bootstrap extends Zend_Application_Module_Bootstrap
{
protected function _initNavigation()
{
$layout = $this->getApplication()->getResource("layout");
$view = $layout->getView();
$config = new Zend_Config_Xml(dirname(__FILE__)."/config/navigation.xml", "nav");
$view->navigation()->addPage($config);
}
}
```
When I open the app in my browser everything works fine. That means I can see the navigation and click on its links to view the specified page. But when I hit a page that uses the :module/:action/:id route, the Navigation Helper throws a Zend\_Controller\_Router\_Route exception:
> Fatal error: Zend\_Controller\_Router\_Exception: id is not specified in C:\Entwicklung\kt\trunk\src\library\Zend\View\Helper\Navigation\HelperAbstract.php on line 519
Did anyone of you experience this error too? It would be great if you could help me or give me advise. Also if you need more information on my setup etc., just tell me.
Thank you! | I found the solution myself.
This problem was caused due to a not-so-beneficial behavior of the Zend\_Navigation elements. In their getHref() method they use the URL helper. This helper creates the URL the navigation entry has to link to, taking in the arguments specified for the navigation element (module, controller, action, etc.)
Now, the problem is that, if you have created a custom route in your bootstrap just as I did, for example
```
":module/:controller/:id"
```
You run into the problem that when this route is being used, the URL helper uses that route to generate the link for the navigation entry. However, I did not pass on an additional "id" parameter, so I got the exception.
So one solution is to pass an additional parameter for each Zend\_Navigation\_Page\_Mvc instance "route" which is set to "default".
Another solution, which I didn't try yet, is to let the new custom route just re-map itself onto the default route, like:
```
":module/:controller/:action/id/$id"
```
But I don't know if you have the ability with Zend Framework to do that. | ```
$route = new Zend_Controller_Router_Route(
"info/:id",
array(
"controller" => "index",
"action" => "index"
),
array("id" => "\d+")
);
```
changed to
```
$route = new Zend_Controller_Router_Route(
"info/:id",
array(
"controller" => "index",
"action" => "index",
"id" => "default"
)
);
```
worked for me, but probably isn't the best way to go | Zend_Controller_Router_Exception: "xyz" is not specified | [
"",
"php",
"exception",
"zend-framework",
""
] |
I just read an article somewhere. They are using session\_id store the login and logout time for every successful logged in user in a temporary table. Which means, the table would be deleted once the session destroyed. So why are they creating the tables??
Is there any use of the temporary tables? And why must use session\_id??
What are the others uses of session\_id in login and logout temporary table?? (I just cant figured out the connection and use of the session\_id, login and logout time in temporary tables.) | Instead of using a second table why not use the users table to store this information?
Users table:
```
CREATE TABLE `Users` (
`Id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`Username` VARCHAR(32) NOT NULL,
`Password` CHAR(32) NOT NULL,
`Login` TIMESTAMP DEFAULT 0,
`Logout` TIMESTAMP DEFAULT 0,
PRIMARY KEY (`Id`),
UNIQUE KEY (`Username`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1
```
Now when the user logs in store his id in a $\_SESSION variable and update the login timestamp:
```
UPDATE `Users` SET `Login` = NOW() WHERE `Id` = id_stored_in_session;
```
and then when he logs out use the same command from above but on `Logout` | "A TEMPORARY table is visible only to the current connection, and is dropped automatically when the connection is closed." *([original](http://dev.mysql.com/doc/refman/5.1/en/create-table.html))*
So temporary tables definitely is a no-go. I'll vote for Cris' solution. | PHP, login and logout time in temporary table? | [
"",
"php",
"authentication",
"session",
"logout",
""
] |
I am new to [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) and am trying to create some data points from a table to graph. The three fields of importance in this table are the id, the time and the value. I am writing a query to get the average value over a set time for a chosen id. The LINQ I have written follows:
```
var value = (from t in _table
where t.Id == id
&& t.Time >= intervalStartTime
&& t.Time <= intervalEndTime
select t.Value).Average();
```
However this crashes at runtime with:
> "The null value cannot be assigned to
> a member with type System.Decimal
> which is a non-nullable value type.."
At certain intervals there is no data so the SQL LINQ generates returns null, which I would liked to be COALESCED to 0 but instead crashes the application. Is there a way to write this LINQ query to be able to handle this properly?
The table definition to make things clearer:
```
[Serializable]
[Table(Name = "ExampleTable")]
public class ExampleTable
{
[Column(Name = "Id")]
public int Id { get; set; }
[Column(Name = "Time")]
public DateTime Time { get; set; }
[Column(Name = "Value")]
public int Value{ get; set; }
}
``` | I think you want
```
var value = (from t in _table
where t.Id == id
&& t.Time >= intervalStartTime
&& t.Time <= intervalEndTime
select (int?)t.Value).Average()
```
This way, you get a `double?` back, whereas without the `(int?)` cast you need to get a `double` back, which cannot be `null`.
This is because of the signatures
```
double Enumerable.Average(IEnumerable<int> source)
double? Enumerable.Average(IEnumerable<int?> source)
```
Now, to get an average of 0 instead of null, you need to place the coalescing operator at the end
```
var value = (from t in _table
where t.Id == id
&& t.Time >= intervalStartTime
&& t.Time <= intervalEndTime
select (int?)t.Value).Average() ?? 0.0;
```
---
IMHO this is a pretty awful design of the `Enumerable`/`Queryable` class; why can't `Average(IEnumerable<int>)` return `double?`, why only for `Average(IEnumerable<int?>)`? | Okay, how about this:
```
var value = (from t in _table
where t.Id == id
&& t.Time >= intervalStartTime
&& t.Time <= intervalEndTime
select t.Value).DefaultIfEmpty().Average()
```
I believe that's *logically* what you want - changing {} to {0}, so making all averages achievable. I don't know if it'll do what you want in terms of SQL though. | Handling null results with the LINQ Average() method | [
"",
"c#",
".net",
"linq",
""
] |
Does static methods and class are good for scalability ? I think so static class/method improves scalability of application and instance methods doesn't scales much. So is it good programming practice to write static method where ever it is possible ? | It depends on *WHY* the method is static. If it's static because it truly does not need context, then it will probably scale very well compared to something of similar complexity that is not static because it requires context.
However, if it is static merely because you cannot retain the needed context and must still pass it in, or because of some artificial goal of having more static methods, then I would suspect that it will actually scale LESS than the comparable method as non-static.
In fact I think that ASP Classic proved this point. | > Does static methods and class are good
> for scalability?
One has little to do with the other.
> I think so static class/method
> improves scalability of application
> and instance methods doesn't scales
> much.
Wrong. Why do you think so?
> So is it good programming practice to
> write static method where ever it is
> possible?
No. In fact, it is very bad practice because it abandons the maintainability advantages of object-oriented programming. | Are static methods good for scalability? | [
"",
"java",
"performance",
"scalability",
"static-methods",
""
] |
Is there a better way to write the below, other then using a switch or if/else statement? Like is this a situation where a PHP's varaiable variable ( $$var ) could come to use?
If so how would you write this code?
```
$type = 2;
switch ($type) {
case 1:
$type = 'gif';
break;
case 2:
$type = 'jpg';
break;
case 3:
$type = 'png';
break;
default:
$type = 'jpg';
break;
}
``` | ```
$types = array(1 => 'gif', 2 => 'jpg', 3 => 'png', 4 => 'jpg');
```
...
```
array_key_exists($type, $types) ? $types[$type] : 'jpg';
``` | I’d use an array:
```
$types = array(
1 => 'gif',
2 => 'jpg',
3 => 'png'
);
if (isset($types[$type])) {
$type = $types[$type];
} else {
$type = 'jpg';
}
``` | How would you do this php code? | [
"",
"php",
""
] |
I have a DOM element with an ID similar to:
```
something[500]
```
which was built by my Ruby on Rails application. I need to be able to get this element via jQuery so that I can traverse my way up the DOM to delete the parent of it's parent, which has a variable ID that I don't have access to beforehand.
Does anyone know how I could go about this? The following code doesn't seem to be working:
```
alert($("#something["+id+"]").parent().parent().attr("id"));
```
Upon further inspection, the following:
```
$("#something["+id+"]")
```
returns an object, but when I run ".html()" or ".text()" on it, the result is always null or just an empty string. | You need to escape the square brackets so that they are not counted as attribute selectors. Try this:
```
alert($("#something\\["+id+"\\]").parent().parent().attr("id"));
```
[See Special Characters In Selectors](http://docs.jquery.com/Selectors), specifically the second paragraph:
> To use any of the meta-characters (such as ``` !"#$%&'()*+,./:;<=>?@[\]^``{|}~ ```) as a literal part of a name, it must be escaped with with two backslashes: `\\`. For example, an element with `id="foo.bar"`, can use the selector `$("#foo\\.bar")`. The W3C CSS specification contains the [complete set of rules regarding valid CSS selectors](https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier). Also useful is the blog entry by Mathias Bynens on [CSS character escape sequences for identifiers](https://mathiasbynens.be/notes/css-escapes). | You can also do
```
$('[id="something['+id+']"]')
``` | Find DOM element by ID when ID contains square brackets? | [
"",
"javascript",
"jquery",
"ruby-on-rails",
"dom",
""
] |
My problem is in regards to calling a server-side event (e.g. DeleteClicked) from dynamically generated html/javascript on the client. I have an existing page on my website that is deeply rooted in .net. The page lifecycle is pretty complex and there are dozens of events that can be fired from the page.
We want to start taking advantage of some JQuery functionality and add additional links and buttons after the page has already loaded. For example, we would like to display a little hover-over graphics on certain images. The little hover-over graphics would provide functionality like delete, edit, etc. I would like to tie the click events on these client-side creations to server-side events without having to thrash (or bypass) the whole page lifecycle.
So far the only solution I can think of is to implant hidden asp.net controls throughout the page have the client-side code manually force a click() on the hidden control. Unfortunately I don't think this is acceptable as I won't necessarily know all of the events that may need to get called at the time I load the page. I'm also not a fan of sending down tons of markup to the client that isn't necessarily needed.
Does my question make sense? Any help would be greatly appreciated! | I'm doing some cleanup on old questions that are stuck open and the best solution here is ASP.NET MVC -- a much better framework for this kind of thing! For those of you forced to use Web Forms I'm sorry I don't have a better solution. For those of you who have the option of trying new things, I strongly suggest MVC! | If you really want to embrace this, you should look at it in a slightly different way.
1. All the logic that performs the
"Delete" should be in a class that
can be re-used
2. Your ASPX page can
then call that class to perform the
delete wherever that occurs now
3. Your jQuery can call a web service
using an AJAX request and the web
service can reference the same class
as your ASPX page.
Not only do you get code-re-use by doing things this way, but it means you can test your code without using the UI too. | Dynamically Added Client Script/HTML Calling Server-Side Event | [
"",
".net",
"asp.net",
"javascript",
"jquery",
"ajax",
""
] |
I need to create an interval Timer that is set to run once a week automatically. I don't want it to start based on user input, but I want it to be created when the application is deployed to the server. Every example that I have seen has another class starting the timer. I don't want to use a message driven bean to create the timer because the audit should just query a database for a given time period and is not based off of actions which send messages.
I have included an example of a Timer. In the example below, the timer should fire every 10 minutes. As a test I want the timer to fire every 10 minutes so I can test the timer.
```
@Stateless
public class TimerTest implements
TimerTestLocal, TimerTestRemote{
@Resource
private TimerService timerService;
private Logger log = Logger.getLogger(TimerTest.class);
private long interval = 1000 * 60 * 10;
private static String TIMER_NAME = "AuditTimer";
public void scheduleTimer() throws NamingException {
// TODO Auto-generated method stub
Calendar cal = Calendar.getInstance();
//cal.set(Calendar.HOUR_OF_DAY, 23);//run at 11pm
//cal.set(Calendar.MINUTE, 00);
//cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm");
log.debug("schedule for: " + sdf.format(cal.getTime()));
timerService.createTimer(cal.getTime(), interval, TIMER_NAME);
}
public void cancelTimer() {
for(Object obj : timerService.getTimers())
{
Timer timer = (Timer)obj;
if(timer.getInfo().equals(TIMER_NAME))
timer.cancel();
}
}
@Timeout
public void timerEvent(Timer timer) {
log.debug("timer fired");
}
}
```
So is there any way that I can start this timer when the application is deployed? I don't think it's a good idea to put the creation of the Timer in a @PostConstruct method because of class loaders on in the server. | The way that I've done timers in the past is to create a context listener in the web.xml to configure the timer.
That way you can ensure that it is started with the container, and shut down cleanly when the app is taken down. | If your project can use jee6 / ejb3.1 there is a much better solution to this problem.
<http://docs.oracle.com/javaee/6/tutorial/doc/bnboy.html>
```
@javax.ejb.Schedule(minute="*/10", hour="*")
public void automaticTimeout() {
logger.info("Automatic timeout occured");
}
```
By using the new @Schedule annotation you have extensive control about when and how often a timeout method will be called. The big upside: you no longer have to start the timer "from outside".
Oracle writes:
> Automatic timers are created by the EJB container when an enterprise
> bean that contains methods annotated with the @Schedule or @Schedules
> annotations is deployed. An enterprise bean can have multiple
> automatic timeout methods, unlike a programmatic timer, which allows
> only one method annotated with the @Timeout annotation in the
> enterprise bean class. | How to start an EJB Timer on deployment? | [
"",
"java",
"jakarta-ee",
"jboss",
"ejb-3.0",
""
] |
I am interested is NVarchar(MAX) a good data type is I want to store short unicode strings which are 1-50 characters long, but most of them (more than 90%) are 5-10 characters long?
The column will not be used in comparison and ordering queries. It might be added to index as included column. Expected rows count - more than 10M.
Any recommendations? Thank you in advance! | Why would you use nvarchar(MAX) for such short strings? If you know the maximum length is 50 characters, make it nvarchar(50).
Also, I do not believe an nvarchar(MAX) column can be included in an index as it would break the 900 byte limit. | NVARCHAR(MAX) (which I believe is the same as NTEXT in the earlier versions of SQL server) is intended for storing long text values of variable and potentially unlimited length.
If you know the values won't exceed N characters, you should use NVARCHAR(N). | NVarchar(MAX) for short strings | [
"",
"sql",
"database",
"nvarchar",
""
] |
I had read in some design book that immutable class improves scalability and its good practice to write immutable class wherever possible. But I think so immutable class increase object proliferation. So is it good of going immutable class or better go for static class (A class with all the methods static) for improve scalability ? | Immutable classes do promote object proliferation, but if you want safety, mutable objects will promote *more* object proliferation because you have to return copies rather than the original to prevent the user from changing the object you return.
As for using classes with all static methods, that's not really an option in most cases where immutability could be used. Take this example from an RPG:
```
public class Weapon
{
final private int attackBonus;
final private int accuracyBonus;
final private int range;
public Weapon(int attackBonus, int accuracyBonus, int range)
{
this.attackBonus = attackBonus;
this.accuracyBonus = accuracyBonus;
this.range = range;
}
public int getAttackBonus() { return this.attackBonus; }
public int getAccuracyBonus() { return this.accuracyBonus; }
public int getRange() { return this.range; }
}
```
How exactly would you implement this with a class that contains only static methods? | The main benefit of [immutable](http://en.wikipedia.org/wiki/Immutable_object) classes however is that you can expose internal data members that are immutable because the caller can't modify them. This is a huge problem with, say, `java.util.Date`. It's mutable so you can't return it directly from a method. This means you end up doing all sorts of [defensive copying](http://www.javapractices.com/topic/TopicAction.do?Id=15). That increases object proliferation.
The other major benefit is that immutable objects do not have [synchronization](http://en.wikipedia.org/wiki/Synchronization_(computer_science)#Process_synchronization) issues, by definition. That's where the [scalability](http://en.wikipedia.org/wiki/Scalability) issues come in. Writing [multithreaded](http://en.wikipedia.org/wiki/Thread_(computer_science)) code is hard. Immutable objects are a good way of (mostly) circumventing the problem.
As for "static classes", by your comment I take it to mean classes with [factory methods](http://en.wikipedia.org/wiki/Factory_method_pattern), which is how it's usually described. That's an unrelated pattern. Both mutable and immutable classes can either have public constructors or private constructors with static factory methods. That has no impact on the (im)mutability of the class since a mutable class is one whose state can be changed after creation whereas an immutable class's state cannot be changed after instantiation.
Static factory methods can have other benefits however. The idea is to encapsulate object creation. | Mutable or immutable class? | [
"",
"java",
"scalability",
"immutability",
""
] |
In an access table I have a column which has the "Required" property set to "True". I need a query which would change it to "False". I tried the following without success:
```
ALTER TABLE [MyTbl] ALTER COLUMN [MyCol] VARCHAR(30) NULL;
``` | Jet SQL, the underlying SQL engine in Access does not allow you to modify the null property on columns. The work around for doing this is to:
1. Create a new temporary column (B) which allows nulls.
2. Copy the data from the old column (A) to the new column (B).
3. Drop the old column (A).
4. Create a new column (C) with the same name as the old column (A). Make sure the new column (C) has the correct null constraint.
5. Copy the data back from the temporary new column (B) to the newly added column (C).
6. Drop Column B. | Access (Jet/ACE) DDL will allow you to change a field's `Required` property from False to True. Here is an example in the Access Immediate window:
```
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required
False
CurrentDb.Execute "ALTER TABLE [MyTbl] ALTER COLUMN [MyCol] VARCHAR(30) NOT NULL;"
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required
True
```
However, you want the opposite --- change `Required` from True to False. Access DDL will not do that. In this example, the requested field size is applied, but the `Required` property is unchanged. And Access does not throw an error:
```
CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required = True
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required
True
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Size
10
CurrentDb.Execute "ALTER TABLE [MyTbl] ALTER COLUMN [MyCol] VARCHAR(30) NULL;"
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required
True
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Size
30
```
And if you exclude any mention of Null in the DDL statement, `Required` is still unchanged:
```
CurrentDb.Execute "ALTER TABLE [MyTbl] ALTER COLUMN [MyCol] VARCHAR(30);"
? CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required
True
```
For an alternative, you can use a mix of Access DDL and DML as @tschaible and @hawbsl demonstrated. However that approach seems like too much effort to me. I would prefer the approach @Caltor suggested. If that is practical for you, it might even be as simple as this ...
```
CurrentDb.TableDefs("MyTbl").Fields("MyCol").Required = False
``` | How to use DDL to change the "Required" property of a column in Access? | [
"",
"sql",
"ms-access",
""
] |
Currently I am working on web based application. I want to know what are the key factors a designer should take care while designing scalable web based application ? | That's a fairly vague and broad question and something you could write books about. How far do you take it? At some point the performance of SQL JOINs breaks down and you have to implement some sharding/partitioning strategy. Is that the level you mean?
General principles are:
* Cache and version all static content (images, CSS, Javascript);
* Put such content on another domain to stop needless cookie traffic;
* GZip/deflate everything;
* Only execute required Javascript;
* Never do with Javascript what you can do on the serverside (eg style table rows with CSS rather than using fancy jQuery odd/even tricks, which can be a real time killer);
* Keep external HTTP requests to a minimum. That means very few CSS, Javascript and image files. That may mean implementing some form of CSS spriting and/or combining CSS or JS files;
* Use serverside caching where necessary but only after you find there's a problem. Memory is an expensive but often effective tradeoff for more performance;
* Test and tune all database queries;
* Minimize redirects. | Having a good read of [highscalability.com](http://highscalability.com/) should give you some ideas. I highly recommend the Amazon articles. | Key factors for designing scalable web based application | [
"",
"java",
"scalability",
"web-applications",
""
] |
I'm trying to create an EJB factory class, which works like this: You have a method which takes as argument a class of an EJB, then it checks whether the EJB has a remote interface (if not throw an exception) and if it does, it returns the concerning EJB.
The code below does exactly this. However the object it returns is of the type of the remote interface of the concerning bean and not of the bean itself. How can I change this? Is there a way to tell Java that the generic type T is of the same type as the class passed to the methods.
```
import java.util.Properties;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.naming.*;
public class EJBFactory
{
private InitialContext ctx;
public EJBFactory() throws NamingException {
ctx = new InitialContext();
}
public EJBFactory(String host, String port) throws NamingException {
Properties props = new Properties();
props.setProperty("org.omg.CORBA.ORBInitialHost", host);
props.setProperty("org.omg.CORBA.ORBInitialPort", port);
ctx = new InitialContext(props);
}
.
// To improve: The object returned should be of the type ejbClass
// instead of the remote interface, which it implements
public <T> T createEJB(Class ejbClass) throws NamingException
{
Class remoteInterface = null;
for(Class interface_: ejbClass.getInterfaces()) {
if(interface_.isAnnotationPresent(Remote.class))
remoteInterface = interface_;
}
if(remoteInterface == null)
throw new IllegalArgumentException(
"EJB Requires a remote interface");
// Get the stateless annotation, then get the jndiName
Stateless stateless =
(Stateless)ejbClass.getAnnotation(Stateless.class);
String jndiName = stateless.mappedName();
T ejbObj = (T) ctx.lookup(jndiName);
return ejbObj;
}
```
}
Example of a unit test which uses the Factory.
```
import junit.framework.TestCase;
public class SimpleEJBTest extends TestCase
{
TestRemote testBean;
@Override
protected void setUp() throws Exception {
super.setUp();
EJBFactory ejbFactory = new EJBFactory();
testBean = ejbFactory.createEJB(TestBean.class);
}
public void testSayHello() {
assertEquals("Hello", testBean.sayHello());
}
}
```
Note: The example works with Glassfish, I didn't test it with any other app server. | Clients of EJBs interact with them through the local/ remote interface that the EJBs implement. Client applications never have direct access to an actual session bean class instance. This is done to make instance pooling possible, where the container can reuse EJB instances to service different requests.
I'm not sure why you need to access the actual bean's object (since obviously I dont know your requirement). But if you still need to create an instance of that you can do it as follows using reflection `Class.forName(className).newInstance();` Again the instance that you create like this is not an EJB. It is just a POJO thats all.
**EDIT** - after your comment regarding junit testing: When you access business methods from a JavaSE as follows, you are actually calling the methods in the EJB - just that you interact thru the interface. So if you want to test any business methods you can still do it from an object got thru a JNDI lookup in a Junit test.
```
//MyGreatBean implements MyGreat. MyGreat has @Remote, MyGreatBean has @Stateless
ref = jndiContext.lookup("MyGreatBean/remote");
MyGreat bean = (MyGreat) ref;
String retValue = bean.businessMethod();
assertEquals("Success", retValue);
```
From an earlier comment, I get a feeling you want to check what kind of annotations have been added to the actual EJB class - if you want to do that kind of checking without actually running the business methods, you can create an instance using Class.forName... like I mentioned above. When you create an instance like this you can only call methods that don't do any "Java EE" stuff. For example you can call a method in the EJB class that is as follows
```
public String someMethod(){
return "I am a POJO but I look like an EJB";
}
``` | I do not think that you can get the EJB object. You can only get the interface. The createEJB should be called with the interface and it returns the interface. | EJB Factory Class | [
"",
"java",
"jakarta-ee",
"glassfish",
"ejb-3.0",
"ejb",
""
] |
Is there any way to easily test C++ classes in java way.
In java you can add static function main and run it directly from IDE
```
class Foo{
...
public static void main(String args[])
{
System.out.println("Test class foo here");
}
}
```
is it possible to do it in Visual C++ ?
Of course you can create another project, but it is bad solution(you sould create project, and then add it to solution or run another copy of Visual Studio)
Another way is to modify main() function, or CWinApp::InitInstance() but if you change file
Foo.h, VS will rebuild all files from project, depending on it (we just want to test Foo.h & Foo.cpp)
The best way i founded is to create another project (console), add Foo.h and Foo.cpp to it, add public static function run() to my class Foo and run it from main() function in console project like this
```
//unitTester.cpp
include "Foo.h"
int main(...){
Foo::run();
return 0;
}
```
in such way i can test my class Foo separately (without recompiling the big project) | When I feel like writing unit tests, I usually add another project that links in the test code + the classes being tested. The test code I write using the [Boost Test Library](http://www.boost.org/doc/libs/release/libs/test/), which [nicely integrates with Visual Studio](http://www.boost.org/doc/libs/1_39_0/libs/test/doc/html/utf/usage-recommendations/dot-net-specific.html). I make my actual project dependent on the test project. The test project runs its executable as a post-build step. Therefore, as long as the tests fail, I cannot even build the main project. | The workaround I use is to use a #define to decide what mode the app is in.
I usually have a def.h file, which would have
```
#define TEST
```
Then on the main file you write,
```
#ifdef TEST
// test code
#else
// main code
#endif
```
This condition check can be done in several places too if for testing you need to change things in several places. If this testing code needs changes in several files also, all you have to do is to include def.h in those source files.
Hope this helps | Visual C++ class testing | [
"",
"c++",
"debugging",
"visual-c++",
"class",
""
] |
I am starting a project with jQuery.
What pitfalls/errors/misconceptions/abuses/misuses did you have in your jQuery project? | Being unaware of the performance hit and overusing selectors instead of assigning them to local variables. For example:-
```
$('#button').click(function() {
$('#label').method();
$('#label').method2();
$('#label').css('background-color', 'red');
});
```
Rather than:-
```
$('#button').click(function() {
var $label = $('#label');
$label.method();
$label.method2();
$label.css('background-color', 'red');
});
```
Or [even better with chaining](http://www.tvidesign.co.uk/blog/improve-your-jquery-25-excellent-tips.aspx#tip10):-
```
$('#button').click(function() {
$("#label").method().method2().css("background-color", "red");
});
```
I found [this](http://www.youtube.com/watch?v=mHtdZgou0qU) the enlightening moment when I realized how the call stacks work.
Edit: incorporated suggestions in comments. | Understand how to use context. Normally, a jQuery selector will search the whole doc:
```
// This will search whole doc for elements with class myClass
$('.myClass');
```
But you can speed things up by searching within a context:
```
var ct = $('#myContainer');
// This will search for elements with class myClass within the myContainer child elements
$('.myClass', ct);
``` | jQuery pitfalls to avoid | [
"",
"javascript",
"jquery",
""
] |
Most concise way to check whether a list is empty or contains only None?
I understand that I can test:
```
if MyList:
pass
```
and:
```
if not MyList:
pass
```
but what if the list has an item (or multiple items), but those item/s are None:
```
MyList = [None, None, None]
if ???:
pass
``` | One way is to use [`all`](http://docs.python.org/3.1/library/functions.html#all) and a list comprehension:
```
if all(e is None for e in myList):
print('all empty or None')
```
This works for empty lists as well. More generally, to test whether the list only contains things that evaluate to `False`, you can use [`any`](http://docs.python.org/3.1/library/functions.html#any):
```
if not any(myList):
print('all empty or evaluating to False')
``` | You can use the `all()` function to test is all elements are None:
```
a = []
b = [None, None, None]
all(e is None for e in a) # True
all(e is None for e in b) # True
``` | Most concise way to check whether a list is empty or contains only None? | [
"",
"python",
"list",
"types",
""
] |
I need to convert a string like this:
```
tag, tag2, longer tag, tag3
```
to:
```
tag, tag2, longer-tag, tag3
```
To make this short, I need to replace spaces not preceded by commas with hyphens, and **I need to do this in Javascript**. | I think this should work
```
var re = new RegExp("([^,\s])\s+" "g");
var result = tagString.replace(re, "$1-");
```
Edit: Updated after Blixt's observation. | `mystring.replace(/([^,])\s+/i "$1-");` There's a better way to do it, but I can't ever remember the syntax | Regex for matching spaces not preceded by commas | [
"",
"javascript",
"regex",
""
] |
I have a Windows Mobile application developed with Visual Studio 2008 and C# (Smart Device Project). When I run the application there's a start menu bar visible on the top and keyboard bar on the bottom. How can I make my application run in full-screen mode?
If possible I would like to have a solution that will allow me to turn full-screen mode on and off on runtime (after clicking some form button for example). | Getting rid of the keyboard/menu bar at the bottom is easy: just remove the MainMenu control from each of your forms.
Getting rid of the start menu (aka task bar) at the top of the screen is more difficult, and requires using the Windows API. [This link](http://social.msdn.microsoft.com/forums/en-US/vssmartdevicesvbcs/thread/4421ceb3-3648-4985-acd9-28a10478083f) shows how to do it.
There is a simpler way to make your application full-screen (sorry, it's early and I don't remember it right now), but the simpler method has an ugly side effect where the task bar momentarily reappears when you switch to another form in your application, which kind of kills the desired kiosk effect. Using the API as above to hide the task bar prevents this from happening.
However, there is a danger to this approach: if your application exits or crashes without having un-hidden the task bar, your user will have no way of unhiding it, and it will remain invisible until the device is reset. | Check Microsoft's [example](http://msdn.microsoft.com/en-us/library/aa458780.aspx).
While example is for Windows Mobile 2003, you can pick syntax of SHFullScreen call from there. Here is already extracted call with [example](http://www.pinvoke.net/default.aspx/aygshell/SHFullScreen.html). | Windows Mobile application in full-screen mode | [
"",
"c#",
"visual-studio-2008",
"windows-mobile",
"fullscreen",
""
] |
Does anyone have experiences with both in the real world? How do they compare in terms of performance (memory usage, speed, etc)? Stability?
Does JBoss Seam work well on Glassfish? | A number of things from my own experience:
1. GlassFish has much better administration console
(JBoss has three consoles, each of them far from being ideal).
2. Hot deployment is more reliable on GlassFish
3. JMS works better on GlassFish - this applies to GF vs. JBoss 4.X.
As far as I see the JMS implementation was drastically modified in
JBoss 5.X, so maybe this claim is no longer true
4. WebServices are working better on GlassFish,
I had a number of issues with more advanced configuration on JBoss
5. GlassFish has more super-high-end entrprise add-ons, like HA-Database, that stores
user session on a cluster in Database, not in memory, so the full failover is
possible, whatever disaster would happen
6. JBoss is more much popular, there are a lot of administrators, developers, who know it,
so it is easier to find someone, who can develop on JBoss, there are also more
resources in the net. Sometimes this is more important, then technical superiority of
one solution over another.
7. GlassFish is friendlier for developers. Redeployment of the web application on GF 3
lasts more or less one second - in oreder to achieve this kind of speed
of redeployment for JBoss I need JRebel. In addition, if someone is using NetBeans,
there is a number of smart wizards, that are very helpful.
8. The future of GlassFish is not certain because of the acquisition of SUN by Oracle.
Right now Oracle claims it will support it, but who knows how this support will
look like and how long will it last. Even though GlassFish is open source, hardly
anyone is ready to develop application server for his/her own needs...
From my point of view GF is easier to administer, is a better solution from purely technological point of view, but it is far less popular and has uncertain future.
I am not connected in any way with RedHat/JBoss or SUN/GlassFish, my company (erudis.pl) is supporting and developing for both servers. | (disclaimer: I work at Sun and I am in the GF team)
I agree that Seam works fine on GlassFish; see <https://blogs.oracle.com/theaquarium/tags/seam>
GFv3 is quite different than JBoss 5; in particular:
* GFv3 is based on OSGi while JBoss 5's kernel is based on JMX.
* GFv3 supports JavaEE 6; JBoss 5 supports Java EE 5.
GFv3 is designed to be very modular; services start on demand, there is an update center repository, etc. GFv3 is significantly smaller than JBoss 5 and will start much faster. JBoss 5.1 GA is listed as 130MB; GFv3Preview is 50MB. GFv3 starts in a couple of seconds; JBoss in tens (you should try the startup for your own platform).
There are other differences, some inherited from GlassFish v2 like the graphical admin console, or the admin CLI.
A more direct comparison for JBoss 5 would be the GlassFish v2 releases, which are based on Java EE 5. The latest release in that family is GFv2.1, with a GFv2.1.1 release scheduled in October (see <https://blogs.oracle.com/theaquarium/entry/schedule_for_glassfish_v2_1>).
Sun also provides patch releases of GlassFish (akin to RedHat's support for JBoss); see <https://blogs.oracle.com/glassfishforbusiness> and sun.com/glassfish. | Real world comparisons of Glassfish and JBoss 5? | [
"",
"java",
"jboss",
"glassfish",
"java-ee-5",
""
] |
In the example code
```
void foo()
{
static Bar b;
...
}
```
compiled with **GCC** is it guaranteed that `b` will be created and initialized in a thread-safe manner ?
In gcc's man page, found the **-fno-threadsafe-statics** command line option:
> Do not emit the extra code to use the
> routines specified in the C++ ABI for
> thread-safe initialization of local
> statics. You can use this option to
> reduce code size slightly in code that
> doesn't need to be thread-safe.
1. Does it mean, that local statics are thread-safe by default with GCC ? So no reason to put explicit guarding e.g. with `pthread_mutex_lock/unlock` ?
2. How to write portable code - how to check if compiler will add its guards ? Or is it better to turn off this feature of GCC ? | 1. No, it means that the **initialization** of local `static`s is thread-safe.
2. You definitely want to leave this feature enabled. Thread-safe initialization of local `static`s is very important. If you need generally thread-safe access to local `static`s then you will need to add the appropriate guards yourself. | We had serious issues with the locking code generated by GCC 3.4 to protect local static initialization. That version used a *global shared mutex* to protect all and any static initialization which lead to a deadlock in our code. We had a local static variable initialized from a result of a function, which started another thread, which created a local static variable. Pseudocode:
```
voif f()
{
static int someValue = complexFunction();
...
}
int complexFunction()
{
start_thread( threadFunc() );
wait_for_some_input_from_new_thread();
return input_from_new_thread;
}
void threadFunc()
{
static SomeClass s();
...
}
```
The only solution was to disable this feature of gcc. If you need your code to be portable , which we did, you can not anyway depend on a feature added in a specific gcc version for thread safety. Supposedly C++0x adds thread-safe local statics, until then this is non-standard magic which makes your code non-portable, so I am advising against it.
If you decide to use it, I suggest you validate that your gcc version does not use a single global mutex for this purpose by writing a sample application. (The difficulty of thread-safety is apparent from the fact that even gcc can not get it right) | Are function static variables thread-safe in GCC? | [
"",
"c++",
"gcc",
"static",
"initialization",
"thread-safety",
""
] |
Is there any way to get the last key press in a console without using Windows messages or the std::cin stream? I've heard that there is a function in the standard library. Solutions should preferably be as portable as possible. Thanks for your help in advance. | There's [conio.h](http://en.wikipedia.org/wiki/Conio.h) but it's not technically standard. On Linux, my first Google hit suggests [termios.h](http://cboard.cprogramming.com/faq-board/27714-faq-there-getch-conio-equivalent-linux-unix.html). | Not really portable but you can access the current key state using GetAsyncKeyState even from console app under windows.
More technical, and equally windows specific, would be to hook the keyboard using SetWindowsHookEx into a call back in your system that simply stores the last key pressed.
But your basic problem: Console + Portability - seems to imply cin is your best bet - what do you need that cin doesn't provide? | Console get key press w/o windows messages c++ | [
"",
"c++",
"console",
"keypress",
""
] |
I am using password based encryption. My initial thought was to use AES to encrypt the file which contains passwords. Turns out password based encryption does not support AES. It uses DES. AFAIK des is not secure. Is PBEWithMD5AndDES secure enough to thrust my data or should i look for another implementation? | It appears from your comments that what you would like to do is to encrypt a file which contains sensitive information, using a password-based encryption scheme, with a password provided by the user at decrypt-time. The sensitive information in this case also happens to be passwords, but that isn't really relevant. (You should probably update the question to make this more clear).
You are doing the right thing, your problem is just that the SunJCE Java cryptography provider doesn't support AES for password-based encryption. You need to use an alternative provider which does: for example, you could use the [Bouncy Castle](http://www.bouncycastle.org/java.html) provider with the algorithm `"PBEWITHSHA256AND128BITAES-CBC-BC"`. (Despite the whimsical name, Bouncy Castle is well-respected).
As for "is DES secure enough for my data", well if the data you're protecting would be worth less than roughly $10,000 to an attacker, then back in 2009 it was probably just secure enough. And in 2014, if your data is worth encrypting at all, the answer is no. | If you have Java 6 available, everything you need is available. Check out this [question](https://stackoverflow.com/questions/992019/java-256bit-aes-encryption) and look at the accepted answer for a code sample. Since you want to encrypt files, the iv that is generated should be prepended to the file you are writing the ciphertext to, so that it is available during the decryption. | Java PBEWithMD5AndDES | [
"",
"java",
"encryption",
"aes",
"des",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.