Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
PHP functions such as 'array\_map' take a callback, which can be a simple function or a class or object method:
```
$array2 = array_map('myFunc', $array);
```
or
```
$array2 = array_map(array($object, 'myMethod'), $array);
```
But is there a syntax to pass a method which is bound within the iteration to the current object (like 'invoke' in Prototype.js)? So that the following could be used:
```
$array2 = array_map('myMethod', $array);
```
with the effect of
```
foreach($array as $obj) $array2[] = $obj->myMethod();
```
Obviously I can use this form, or I can write a wrapper function to make the call, and even do that inline. But since 'myMethod' is already a method it seems to be going round the houses to have to do one of these. | ```
function obj_array_map($method, $arr_of_objects) {
$out = array();
$args = array_slice(func_get_args(), 2);
foreach ($arr_of_objects as $key => $obj) {
$out[$key] = call_user_func_array(Array($obj, $method), $args);
}
return $out;
}
// this code
$a = Array($obj1, $obj2);
obj_array_map('method', $a, 1, 2, 3);
// results in the calls:
$obj1->method(1, 2, 3);
$obj2->method(1, 2, 3);
``` | Not currently. When php 5.3 comes out, you could use the following syntax:
```
$array2 = array_map(function($obj) { return $obj->myMethod(); }, $array);
``` | Is an 'invoke'-style callback possible in PHP5? | [
"",
"php",
"callback",
"invoke",
""
] |
I want to calculate the sum of
```
1/1 + 1/2 + 1/3 + ... + 1/30
```
I run the code unsuccessfully
```
import decimal
import math
var=decimal.Decimal(1/i)
for i in range(1,31):
print(sum(var))
```
I get the error
```
'Decimal' object is not iterable
```
**How can you make the iterable function in Python?** | What you want is this:
```
print(sum(decimal.Decimal(1) / i for i in range(1, 31)))
```
The reason your code doesn't work, is that you try to iterate over *one* `Decimal` instance (through the use of `sum`). Furthermore, your definition of `var` is invalid. Your intention was probably something like this:
```
var = lambda i: decimal.Decimal(str(1.0 / i))
```
(Note the use of `str`, `Decimal` [does not permit](http://docs.python.org/3.0/library/decimal.html) a floating point argument). But even then your loop would not work, because the use of `sum` *inside* the loop is inherently flawed. `sum` should be used *after* the loop has created all fractions that you want to sum. So that would be either of:
```
print(sum(var(i) for i in range(1,31)))
print(sum(map(var, range(1, 31))))
```
For completeness, yet another way to do this is the following:
```
one = decimal.Decimal(1)
unitFractions = (one / i for i in itertools.count(1))
print(sum(itertools.islice(unitFractions, 30)))
```
However, as mentioned by [gs](https://stackoverflow.com/questions/845787/unable-to-make-an-iterable-decimal-function-in-python/845826#845826), the [fractions](http://docs.python.org/library/fractions.html) provides an alternative method that yields a fractional answer:
```
>>> unitFractions = (fractions.Fraction(1, i) for i in itertools.count(1))
>>> print(sum(itertools.islice(unitFractions, 30)))
9304682830147/2329089562800
``` | You write:
```
var=decimal.Decimal(1/i)
```
which is weird since 'i' is not defined at that point. How about:
```
one = decimal.Decimal( "1" )
total = decimal.Decimal( "0" )
for i in range( 1, 31 ):
total += one / decimal.Decimal( "%d" % i )
``` | Unable to make an iterable decimal function in Python | [
"",
"python",
"iteration",
"sum",
""
] |
I'm building a blog that should parse bbcode tags like this:
Input: `<youtube=http://www.youtube.com/watch?v=VIDEO_ID&feature=channel>`
Output:
```
<object width="400" height="245">
<param name="movie" value="http://www.youtube- nocookie.com/v/VIDEO_ID&hl=en&fs=1&rel=0&showinfo=0"></param>
<param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.youtube-nocookie.com/v/VIDEO_ID&hl=en&fs=1&rel=0&showinfo=0" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="400" height="245"></embed>
</object>
```
My function is incredibly simple so far, because I've gotten stuck on the easiest part! Right now, I have a master process function that calls difference process functions. In this case one of them is processYouTubeVideos(). So I call it like so:
```
$str = eregi_replace('\<youtube=([^>]*)\>', processYouTubeVideos("\\1"), $str);
```
processYouTubeVideos() receives the URLs from inside the youtube tag perfectly, but for some reason, when using explode() (or split) the delimiter is never found. Even using test values like "u" or "tube"...
```
function processYouTubeVideos ($str) {
$params = explode("?", $str);
$params = explode("&", $params[1]);
return $params[0];
}
``` | Try:
```
$str = preg_replace('/<youtube=([^>]*)>/e', 'processYouTubeVideos("$1")', $str);
```
The code that you're attempting to run won't work, because the function on the output string will be called on the target pattern rather than the output. That means that you're sending "\1" literarly to the function. Add `var_dump($str);` to the beginning of the function and try running your code again, and you'll see this clearly.
[preg\_replace](https://www.php.net/preg_replace) has a special flag "e" that you can use to execute a function for each time a replacement is made. This works by inserting the subpattern at the marker position ($1) and then running something like `eval()` or `create_function()` on the code to execute it and retrieve the result. This then sent back to `preg_replace()` and the actual replacement is made. | The processYouTubeVideos("\1") function is being run *before* the eregi\_replace.
The following does what I believe you intend:
```
$str = eregi_replace('\<youtube=([^>]*)\>', "\\1", $str);
$str = processYouTubeVideos($str);
```
It performs the replace, and then sends the resulting value to processYouTubeVideos. | Parse bbcode youtube tag in text and replace with html including the video id | [
"",
"php",
"parsing",
"youtube",
"bbcode",
"preg-replace-callback",
""
] |
This is a follow-up questions on a [previous one](https://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io).
Consider this code, which is less toyish than the one in the [previous question](https://stackoverflow.com/questions/849058/is-it-possible-to-speed-up-python-io) (but still much simpler than my real one)
```
import sys
data=[]
for line in open(sys.argv[1]):
data.append(line[-1])
print data[-1]
```
Now, I was expecting a longer run time (my benchmark file is 65150224 lines long), possibly much longer. This was not the case, it runs in ~ 2 minutes on the same hw as before!
Is it data.append() very lightweight? I don't believe so, thus I wrote this fake code to test it:
```
data=[]
counter=0
string="a\n"
for counter in xrange(65150224):
data.append(string[-1])
print data[-1]
```
This runs in 1.5 to 3 minutes (there is strong variability among runs)
Why don't I get 3.5 to 5 minutes in the former program? Obviously data.append() is happening in parallel with the IO.
This is good news!
But how does it work? Is it a documented feature? Is there any requirement on my code that I should follow to make it works as much as possible (besides load-balancing IO and memory/CPU activities)? Or is it just plain buffering/caching in action?
Again, I tagged "linux" this question, because I'm interested only in linux-specific answers. Feel free to give OS-agnostic, or even other-OS answers, if you think it's worth doing. | > Obviously data.append() is happening in parallel with the IO.
I'm afraid not. It *is* possible to parallelize IO and computation in Python, but it doesn't happen magically.
One thing you could do is use `posix_fadvise(2)` to give the OS a hint that you plan to read the file sequentially (`POSIX_FADV_SEQUENTIAL`).
In some rough tests doing "wc -l" on a 600 meg file (an ISO) the performance increased by about 20%. Each test was done immediately after clearing the disk cache.
For a Python interface to fadvise see [python-fadvise](http://chris-lamb.co.uk/projects/python-fadvise/). | How big are the lines in your file? If they're not very long (anything under about 1K probably qualifies) then you're likely seeing performance gains because of input buffering. | Is python automagically parallelizing IO- and CPU- or memory-bound sections? | [
"",
"python",
"linux",
"performance",
"text-files",
""
] |
In a Java program (Java 1.5), I have a BufferedWriter that wraps a Filewriter, and I call write() many many times... The resulting file is pretty big...
Among the lines of this file, some of them are incomplete...
Do I need to call flush each time I write something (but I suspect it would be inefficient) or use another method of BufferedWriter or use another class...?
(Since I've a zillion lines to write, I do want to have something quite efficient.)
What would be the ideal "flushing" moment? (when I reach the capacity of the BufferedWriter)...
Init:
```
try {
analysisOutput = new BufferedWriter(new FileWriter(
"analysisResults", true));
analysisOutput.newLine();
analysisOutput.write("Processing File " + fileName + "\n");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
```
Writing:
```
private void printAfterInfo(String toBeMoved,HashMap<String, Boolean> afterMap, Location location)
throws IOException {
if(afterMap != null) {
for (Map.Entry<String, Boolean> map : afterMap.entrySet()) {
if (toBeMoved == "Condition") {
if (1 <= DEBUG)
System.out.println("###" + toBeMoved + " " + location + " "
+ conditionalDefs.get(conditionalDefs.size() - 1)
+ " After " + map.getKey() + " "
+ map.getValue() + "\n");
analysisOutput.write("###" + toBeMoved + " " + location + " "
+ conditionalDefs.get(conditionalDefs.size() - 1)
+ " After " + map.getKey() + " " + map.getValue()
+ "\n");
} else {
if (1 <= DEBUG)
System.out.println("###" + toBeMoved + " " + location + " "
+ map.getKey() + " After "
+ map.getValue() + "\n");
if (conditionalDefs.size() > 0)
analysisOutput.write("###" + toBeMoved + " " + location + " "
+ conditionalDefs.get(conditionalDefs.size() - 1) + " "
+ map.getKey() + " After " + map.getValue()
+ "\n");
else
analysisOutput.write("###" + toBeMoved + " " + location + " " + map.getKey() + " After " + map.getValue() + "\n");
}
}
}
```
I've just figured out that the lines which are incomplete are those just before "Processing file"... so it occurs when I'm switching from one file that I analyze to another...
Closing:
```
dispatch(unit);
try {
if (analysisOutput != null) {
printFileInfo();
analysisOutput.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
```
Sometimes the information printed out by printFileInfo does not appear in the results file... | The `BufferedWriter` will already flush when it fills its buffer. From the docs of [`BufferedWriter.write`](http://java.sun.com/javase/6/docs/api/java/io/BufferedWriter.html#write):
> Ordinarily this method stores characters from the given array into this stream's buffer,
> *flushing the buffer to the underlying stream as needed*.
(Emphasis mine.)
The point of `BufferedWriter` is basically to consolidate lots of little writes into far fewer big writes, as that's usually more efficient (but more of a pain to code for). You shouldn't need to do anything special to get it to work properly though, other than making sure you flush it when you're *finished* with it - and calling `close()` will do this and flush/close the underlying writer anyway.
In other words, relax - just write, write, write and close :) The only time you normally need to call `flush` manually is if you really, really need the data to be on disk now. (For instance, if you have a perpetual logger, you might want to flush it every so often so that whoever's reading the logs doesn't need to wait until the buffer's full before they can see new log entries!) | The ideal flushing moment is when you need another program reading the file to see the data that's been written, before the file is closed. In many cases, that's never. | When to flush a BufferedWriter | [
"",
"java",
"io",
""
] |
This code fails to actually save any changes:
```
//
// POST: /SomeType/Edit/5
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, SomeType Model)
{
db.AttachTo(Model.GetType().Name, Model);
db.ApplyPropertyChanges(Model.EntityKey.EntitySetName, Model);
db.SaveChanges();
return RedirectToAction("Index");
}
```
ASP.NET MVC creates the object Model as a Department type EntityObject with an EntityState value of **Detached**.
After using the *AttachTo* method, its EntityState becomes **Unchanged**.
[MSDN on Attaching Objects (Entity Framework)](http://msdn.microsoft.com/en-us/library/bb896271.aspx)
> Objects are attached to the object
> context in an **Unchanged** state.
Because of its **Unchanged** state, the method *ApplyPropertyChanges* does nothing.
I want it to instead have state **Modified**.
[MSDN on EntityState Enumeration](http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx)
> **Detached**
> The object exists but it is not being tracked by Object
> Services. An entity is in this state
> immediately after it has been created
> and before it is added to the object
> context. An entity is also in this
> state after it has been removed from
> the context by calling the Detach
> method or if it is loaded using a
> NoTrackingMergeOption.
>
> **Unchanged**
> The object has not been modified since it was loaded into
> the context or since the last time
> that the SaveChanges method was
> called.
>
> **Modified**
> The object is changed but the SaveChanges method has not
> been called.
I cannot explicitly set an EntityObject's EntityState property to **Modified**. It is read only.
Is it just impossible to have strongly-typed MVC controllers with EntityObjects? | You need to get the ObjectStateManager from your ObjectContext. With the ObjectStateManager, you can explicitly set the state for your object without needing to make a call to the database:
```
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, SomeType Model)
{
db.AttachTo(Model.GetType().Name, Model);
ObjectStateManager stateMgr = db.ObjectStateManager;
ObjectStateEntry stateEntry = stateMgr.GetObjectStateEntry(model);
stateEntry.SetModified(); // Make sure the entity is marked as modified
//db.ApplyPropertyChanges(Model.EntityKey.EntitySetName, Model);
db.SaveChanges();
return RedirectToAction("Index");
}
```
The ObjectStateEntry also allows you to apply finer-grained state change data via the SetModifiedProperty. If you call SetModified, EF will treat the entire entity as modified, and persist every property to the data store. With SetModifiedProperty, EF can optimize the queries and only involve the properties that have actually changed. Using SetModifiedProperty is obviously more complex, as you usually need to know the original value of each property.
I hope this helps. ObjectStateManager is a powerful little tool in the EF toolbox, and can help improve EF v1.0's otherwise morbid performance and efficiency. | I found none of the above seemed to work for me, but the MSDN guide example did which is where you get the original item from the context, and then attach the updated item.
Second example:
<http://msdn.microsoft.com/en-us/library/bb896248.aspx#Mtps_DropDownFilterText>
```
private static void ApplyItemUpdates(SalesOrderDetail updatedItem){
// Define an ObjectStateEntry and EntityKey for the current object.
EntityKey key;
object originalItem;
using (AdventureWorksEntities advWorksContext =
new AdventureWorksEntities())
{
try
{
// Create the detached object's entity key.
key = advWorksContext.CreateEntityKey("SalesOrderDetail", updatedItem);
// Get the original item based on the entity key from the context
// or from the database.
if (advWorksContext.TryGetObjectByKey(key, out originalItem))
{
// Call the ApplyPropertyChanges method to apply changes
// from the updated item to the original version.
advWorksContext.ApplyPropertyChanges(
key.EntitySetName, updatedItem);
}
advWorksContext.SaveChanges();
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.ToString());
}
}
```
} | Strongly-Typed ASP.NET MVC with Entity Framework | [
"",
"c#",
".net",
"asp.net",
"asp.net-mvc",
"entity-framework",
""
] |
We have bunch of Domain Entities which should be rendered to an html format, which shows their detail in a pop up window.
I would be glad to do something like this:
```
Product product = new Product(...);
product.ToHtml(); // or: HtmlRenderer.Render(Product);
```
but my main problem is how to do this stuff from behind.
I have 3 different answers:
**1. Render By Code:**
I can simply write my code for rendering the Html inside the ToHtml Method (C#) - the problem it is that it is *too* static. if you would like to move a little bit the header to the middle you should change code.
moreover, it is very hard to read Html indentation in C#.
**2. Using XSL:**
XSL Files can easily manage the Html template and using XSLT I can transform XML file to the right place of the documents.
the parser already written by someone else (just need to learn the syntax)
\*\* for this we will need that each object could serialize to Xml. and if the object changed -> the Xml will be changed --> the xslt need to be changed too
\*\* this will also give me the option to indent the html easily for example: adding css capabilities and\or change the html design
**3. using other template engine:**
Write my own C# -> Html template Engine so it will read the template from file (\*.template) and will insert the right property in the right place of the template using reflection.
\*\* For this solution we have many issues that we can think of, for example: How the syntax should be?
Is this thing ok?
**%Name%**
##### %Description%
And how we can handle arrays?
\*\* Maybe we can use an existing engine (Brail or T4-Templating)?
What do you prefer?
Do you know a good engine?
For now I prefer the second solution, but it gonna be very slow. | I can't agree more with John Feminella. Integrating Html rendering directly into your domain entities is a horrid pollution of your domain with a completely arbitrary and external concern. Like John said, you will make your entities very brittle by doing that, and break both of those critical rules: Separation of Concerns and Single Responsibility.
From the choices you gave, #3 is the closest to an appropriate way to do it. You need not write your own template engine. There are plenty free and ready-made template engines on the net that will do the job more than adequately (NVelocity, StringTemplate, Brail, etc. etc.)
Keep rendering where it belongs...in your presentation/view, and don't pollute your domain with higher level concerns. | I once had a need to render a collection of any type to an Html Table. I created an extension method on IEnumerable<T> that had overloads for css and the like. You can see my blog post about it here:
<http://crazorsharp.blogspot.com/2009/03/cool-ienumberable-extension-method_25.html>
It uses reflection to get all the properties of the object, and renders a nice little table. See if that would work for you.
```
[System.Runtime.CompilerServices.Extension()]
public string ToHtmlTable<T>(IEnumerable<T> list, string propertiesToIncludeAsColumns = "")
{
return ToHtmlTable(list, string.Empty, string.Empty, string.Empty, string.Empty, propertiesToIncludeAsColumns);
}
[System.Runtime.CompilerServices.Extension()]
public string ToHtmlTable<T>(IEnumerable<T> list, string tableSyle, string headerStyle, string rowStyle, string alternateRowStyle, string propertiesToIncludeAsColumns = "")
{
dynamic result = new StringBuilder();
if (String.IsNullOrEmpty(tableSyle)) {
result.Append("<table id=\"" + typeof(T).Name + "Table\">");
} else {
result.Append((Convert.ToString("<table id=\"" + typeof(T).Name + "Table\" class=\"") + tableSyle) + "\">");
}
dynamic propertyArray = typeof(T).GetProperties();
foreach (object prop in propertyArray) {
if (string.IsNullOrEmpty(propertiesToIncludeAsColumns) || propertiesToIncludeAsColumns.Contains(prop.Name + ",")) {
if (String.IsNullOrEmpty(headerStyle)) {
result.AppendFormat("<th>{0}</th>", prop.Name);
} else {
result.AppendFormat("<th class=\"{0}\">{1}</th>", headerStyle, prop.Name);
}
}
}
for (int i = 0; i <= list.Count() - 1; i++) {
if (!String.IsNullOrEmpty(rowStyle) && !String.IsNullOrEmpty(alternateRowStyle)) {
result.AppendFormat("<tr class=\"{0}\">", i % 2 == 0 ? rowStyle : alternateRowStyle);
} else {
result.AppendFormat("<tr>");
}
foreach (object prop in propertyArray) {
if (string.IsNullOrEmpty(propertiesToIncludeAsColumns) || propertiesToIncludeAsColumns.Contains(prop.Name + ",")) {
object value = prop.GetValue(list.ElementAt(i), null);
result.AppendFormat("<td>{0}</td>", value ?? String.Empty);
}
}
result.AppendLine("</tr>");
}
result.Append("</table>");
return result.ToString();
}
``` | Rendering C# Objects to Html | [
"",
"c#",
"html",
"rendering",
"template-engine",
""
] |
I have a textbox with the .Multiline property set to true. At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added. How do I accomplish this? | > At regular intervals, I am adding new lines of text to it. I would like the textbox to automatically scroll to the bottom-most entry (the newest one) whenever a new line is added.
If you use [`TextBox.AppendText(string text)`](http://msdn.microsoft.com/en-us/library/system.windows.forms.textboxbase.appendtext.aspx), it will automatically scroll to the end of the newly appended text. It avoids the flickering scrollbar if you're calling it in a loop.
It also happens to be an order of magnitude faster than concatenating onto the `.Text` property. Though that might depend on how often you're calling it; I was testing with a tight loop.
---
This will not scroll if it is called before the textbox is shown, or if the textbox is otherwise not visible (e.g. in a different tab of a TabPanel). See [TextBox.AppendText() not autoscrolling](https://stackoverflow.com/questions/18260702/textbox-appendtext-not-autoscrolling). This may or may not be important, depending on if you require autoscroll when the user can't see the textbox.
It seems that the alternative method from the other answers also don't work in this case. One way around it is to perform additional scrolling on the `VisibleChanged` event:
```
textBox.VisibleChanged += (sender, e) =>
{
if (textBox.Visible)
{
textBox.SelectionStart = textBox.TextLength;
textBox.ScrollToCaret();
}
};
```
---
Internally, `AppendText` does something like this:
```
textBox.Select(textBox.TextLength + 1, 0);
textBox.SelectedText = textToAppend;
```
But there should be no reason to do it manually.
(If you decompile it yourself, you'll see that it uses some possibly more efficient internal methods, and has what seems to be a minor special case.) | You can use the following code snippet:
```
myTextBox.SelectionStart = myTextBox.Text.Length;
myTextBox.ScrollToCaret();
```
which will automatically scroll to the end. | How do I automatically scroll to the bottom of a multiline text box? | [
"",
"c#",
"winforms",
"textbox",
"scroll",
""
] |
[Resultset](http://java.sun.com/j2se/1.4.2/docs/api/java/sql/ResultSet.html) has no method for hasNext. I want to check if the resultSet has any value
is this the correct way
```
if (!resultSet.next() ) {
System.out.println("no data");
}
``` | That's correct, initially the `ResultSet`'s cursor is pointing to before the first row, if the first call to `next()` returns `false` then there was no data in the `ResultSet`.
If you use this method, you may have to call `beforeFirst()` immediately after to reset it, since it has positioned itself past the first row now.
It should be noted however, that [Seifer's answer](https://stackoverflow.com/a/6813771/1030) below is a more elegant solution to this question. | Assuming you are working with a newly returned `ResultSet` whose cursor is pointing before the first row, an easier way to check this is to just call `isBeforeFirst()`. This avoids having to back-track if the data is to be read.
[As explained in the documentation](https://docs.oracle.com/javase/9/docs/api/java/sql/ResultSet.html#isBeforeFirst--), this returns false if the cursor is not before the first record or if **there are no rows in the ResultSet**.
```
if (!resultSet.isBeforeFirst() ) {
System.out.println("No data");
}
``` | Java ResultSet how to check if there are any results | [
"",
"java",
"jdbc",
""
] |
I've recently moved to Java, but I've had some problems with variable aliasing. I've searched everywhere, but I can't seem to find the proper way to copy the contents of one object to another object without just referencing to the same object. Does anyone have any suggestions?
Edit: What if it is an int that I am having aliasing problems with? Should I be avoiding situations like this in the first place? If so, how? | If your class implements the [Clonable](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Cloneable.html) interface, then you can use the [Object.clone()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Object.html#clone()) method to create a hard copy. The [Wikipedia](http://en.wikipedia.org/wiki/Clone_(Java_method)) entry has some good details.
An alternative is to use [copy constructors](http://www.javapractices.com/topic/TopicAction.do?Id=12), which according to [this page](http://www.javapractices.com/topic/TopicAction.do?Id=71) are safer. | It depends on the "content". For example, you cannot just copy a FileInputStream and then assume that both will continue loading from the same file.
Basically, there are two ways: If the class supports "Cloneable" interface, you can clone it by calling clone(). If not, it often has a copy constructor, that copies in data from another object.
Usually, you will end up with a shallow copy (i. e. all fields of the class are copied, but they point to the same object).
On the other hand, a lot of objects are designed to be immutable (like the String class), and there is no need to copy such an object as it cannot be changed anyway. | Java variable aliasing workaround | [
"",
"java",
"object",
"reference",
"alias",
""
] |
Are there any lightweight tools that allow easy-to-read crafting of SQL independently of the main apps/utilities associated with a particular database?
I lately find myself working with MySQL, Access & now MS-SQL and use Notepad++ to build queries as it provides basic syntax highlighting that helps my unfamiliar eyes, but no logic formatting - new lines for INNER JOIN, WHERE etc., indenting of continuing parameters, dare I say it even IntelliSense - that kind of thing.
Particularly when re-jigging an existing query that is presented as an incomprehensible lump, it would be nice to be able to paste this in somewhere, click a button and have it displayed in a more human-friendly format.
Does such a tool exist?
**Edit:** Thanks for the suggestions. In particular, SQLinForm has the kind of fine-grained control I was ideally imagining.
Pity only the online version is free, an OSS standalone app (not Java - gumph!) would be preferable as SQL is not exactly a main focus of my work and I can't see me swinging even $30 past the bean counters just so I don't get a headache trying to fix their crummy reporting.
Any more?
**Edit 2:** Oops, seems this has been asked before. I wasn't obviously searching for the right thing when I checked. Searching on the tool names, [or via Google](https://stackoverflow.uservoice.com/pages/1722-general/suggestions/181675-use-google-search-instead-on-the-inbuilt-one), brings up many similar questions - voted to close. | I've used [SQLInform](http://www.sqlinform.com/) in the past with pretty good results - again it formats any SQL you paste in with reasonable accuracy. | I used this on in the past to make some ugly sql somewhat readable: <http://www.dpriver.com/pp/sqlformat.htm> | Are there any platform agnostic SQL query builders with syntax, logic formatting etc.? | [
"",
"sql",
"editor",
"cross-platform",
"text-editor",
"editing",
""
] |
A data import was done from an access database and there was no validation on the email address field. Does anyone have an sql script that can return a list of invalid email addresses (missing @, etc). | ```
SELECT * FROM people WHERE email NOT LIKE '%_@__%.__%'
```
Anything more complex will likely return false negatives and run slower.
Validating e-mail addresses in code is virtually impossible.
EDIT: Related questions
* I've answered a similar question some time ago: [TSQL Email Validation (without regex)](https://stackoverflow.com/questions/229824/tsql-email-validation-without-regex)
* [T-SQL: checking for email format](https://stackoverflow.com/questions/423606/t-sql-checking-for-email-format)
* [Regexp recognition of email address hard?](https://stackoverflow.com/questions/156430/regexp-recognition-of-email-address-hard)
* [many other Stack Overflow questions](http://www.google.com/search?q=validation%20email%20address%20site%3Astackoverflow.com) | Here is a quick and easy solution:
```
CREATE FUNCTION dbo.vaValidEmail(@EMAIL varchar(100))
RETURNS bit as
BEGIN
DECLARE @bitRetVal as Bit
IF (@EMAIL <> '' AND @EMAIL NOT LIKE '_%@__%.__%')
SET @bitRetVal = 0 -- Invalid
ELSE
SET @bitRetVal = 1 -- Valid
RETURN @bitRetVal
END
```
Then you can find all rows by using the function:
```
SELECT * FROM users WHERE dbo.vaValidEmail(email) = 0
```
If you are not happy with creating a function in your database, you can use the LIKE-clause directly in your query:
```
SELECT * FROM users WHERE email NOT LIKE '_%@__%.__%'
```
[Source](http://www.vandamme.com/blog.aspx?id=624&blogid=194) | Sql script to find invalid email addresses | [
"",
"sql",
"validation",
"email",
""
] |
is there any function in C++ that calculates a fingerprint or hash of a string that's guaranteed to be at least 64 bits wide?
I'd like to replace my `unordered_map<string, int>` with `unordered_map<long long, int>`.
Given the answers that I'm getting (thanks Stack Overflow community...) the technique that I'm describing is not well-known. The reason that I want an unordered map of fingerprints instead of strings is for space and speed. The second map does not have to store strings and when doing the lookup, it doesn't incur any extra cache misses to fetch those strings. The only downside is the slight chance of a collision. That's why the key has to be 64 bits: a probability of 2^(-64) is basically an impossibility. Of course, this is predicated on a good hash function, which is exactly what my question is seeking.
Thanks again, Stack Overflowers. | c++ has no native 128 Bit type, nor does it have native hashing support. Such extensions for hashing are supposed to be added in TR1, but as far as I am aware 128 bit ints aren't supported my many compilers. (Microsoft supports an `__int128` type -- only on x64 platforms though)
I'd expect the functions included with unordered\_map would be faster in any case.
If you really do want to do things that way, MD5 provides a good 128 bit hash. | `unordered_map` always hashes the key into a `size_t` variable. This is independent from the type of the key and depends solely on the architecture you are working with. | is there any function in C++ that calculates a fingerprint or hash of a string that's guaranteed to be at least 64 bits wide? | [
"",
"c++",
"stl",
"boost",
""
] |
Is it possible (and if so, how) to write a program in C++ that takes parameters, then run that program from another C++ program.
Ie: I can create a function that adds two numbers:
```
int add(int a,int b){return a+b;}
```
Is it possible to do the same thing, except instead of a function, a separate C++ .exe?
EDIT: Since a lot of people don't understand my question, I'll try to say exactly what I want to know how to do.
I want to have a program, lets call it "p1".
I want that program to get two numbers from the user:
```
int x,y;
cin>>x;
cin>>y;
```
Now I want to create another program, that takes two numbers, and adds them, the same way a function would, except a seperate program.
Then I want to run the second program from the first program with the numbers it got from the user. Ie:
```
#include<iostream>
using namespace std;
int main()
{
int x,y;
cin>>x;
cin>>y;
add(x,y); //this is how I would call a function named "add". I want to know how to do that with a separate program instead of just a separate function.
return 0;
}
```
EDIT: I figured out how to use
```
(void)system("C:\\Program Files\\test.exe");
```
How would I use that to pass arguments, and how could I write a program that takes those arguments? | On most OSes, you can pass arguments in system() by space-seperating them:
```
system("someapp.exe 42 24");
```
This string, of course, can be built up by sprintf or std::ostringstream or what have you.
Then you just need to process your arguments in the other program:
```
int main(int argc, char **argv) {
// important - make sure we have enough args
if (argc != 3) { // first (zeroth) argument is always the program name, so 1+2 args is needed
fprintf(stderr, "Wrong number of arguments\n");
return EXIT_FAILURE;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
// do stuff
}
``` | I'm not exactly sure what you want to do, but you can start apps in windows several ways. The most common "windows" way to do it is:
* Use [ShellExecute](http://msdn.microsoft.com/en-us/library/bb762153(VS.85).aspx) to start a program in windows.
* If you need to get the return value back, you can use [CreateProcess](http://msdn.microsoft.com/en-us/library/ms682425.aspx) instead.
It sounds like you want to take the argc, and argv values from the source application, and then use those values as parameters into the above functions to start your second application.
You can communicate between the processes in several ways, by using pipes, sockets, files, or even the 2nd program's return code might be enough.
You might be better off creating a DLL to load from your first application. The DLL would do whatever you want and can return the values to you directly without an extra communications layer. | How to create/run a .exe from a program? (C++) | [
"",
"c++",
"function",
"parameters",
"executable",
""
] |
I don't want to know a way to preload images, I found much on the net, but I want to know how it works.
How is javascript able to preload images?
I mean, I tried a snippet from here, and even if it works, it doesn't seem to preload images.
When I check firebug, I can see that the image is loaded twice, once while the preloading, another time when displaying it!
To improve this code I'd like to know how it works.
Here is what i do:
```
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('<img/>')[0].src = this;
//(new Image()).src = this;
alert(this +' && ' + i++);
});
}
```
then i do something like that:
```
preloader = function() {
preload(myImages);
}
$(document).ready(preloader);
```
Here is how i display/add the image :
```
$("li.works").click(function() {
$("#viewer").children().empty();
$('#viewer').children().append('<img src=\'images/ref/'+this.firstChild.id+'.jpg\' alt="'+this.firstChild.id+'" \/>')
$("#viewer").children().fadeIn();
``` | Your basic Javascript preloader does this:
```
var image = new Image();
image.src = '/path/to/the/image.jpg';
```
The way it works is simply by creating a new Image object and setting the src of it, the browser is going to go grab the image. We're not adding *this* particular image to the browser, but when the time comes to show the image in the page via whatever method we have setup, the browser will already have it in its cache and will not go fetch it again. I can't really tell you why whatever you have isn't working this way without looking at the code, though.
One interesting gotcha that is discussed [in this question](https://stackoverflow.com/questions/761263/what-is-the-best-way-to-preload-multiple-images-in-javascript) is what happens when you have an array of images and try preloading them all by using the same Image object:
```
var images = ['image1.jpg','image2.jpg'];
var image = new Image();
for(var x = 0; x < images.length; x++) {
image.src = images[x];
}
```
This will only preload the last image as the rest will not have time to preload before the loop comes around again to change the source of the object. [View an example of this](http://www.rootspot.com/stackoverflow/preload.php). You should be able to instantly see the second image once you click on the button, but the first one will have to load as it didn't get a chance to preload when you try to view it.
As such, the proper way to do many at once would be:
```
var images = ['image1.jpg','image2.jpg'];
for(var x = 0; x < images.length; x++) {
var image = new Image();
image.src = images[x];
}
``` | Javascript preloading works by taking advantage of the caching mechanism used by browsers.
The basic idea is that once a resource is downloaded, it is stored for a period of time locally on the client machine so that the browser doesn't have to retrieve the resource again from across the net, the next time it is required for display/use by the browser.
Your code is probably working just fine and you're just misinterpeting what Fire Bug is displaying.
To test this theory just hit www.google.com with a clean cache. I.e. clear your download history first.
The first time through everything will likely have a status of 200 OK. Meaning your browser requested the resource and the server sent it. If you look at the bottom on the Fire Bug window it will says how big the page was say 195Kb and how much of that was pulled from cache. In this case 0Kb.
Then reload the same page without clearing your cache, and you will still see the same number of requests in FireBug.
The reason for this is simple enough. The page hasn't changed and still needs all the same resources it needed before.
What is different is that for the majority of these requests the server returned a 304 Not Modified Status, so the browser checked it's cache to see if it already had the resource stored locally, which in this case it did from the previous page load. So the browser just pulled the resource from the local cache.
If you look at the bottom of the Fire Bug window you will see that page size is still the same (195Kb) but that the majority of it, in my case 188Kb, was pulled locally from cache.
So the cache did work and the second time i hit Google I saved 188Kb of download.
I'm sure you will find the same thing with preloading your images. The request is still made but if the server returns a status of 304 then you will see that the image is in fact just pulled from local cache and not the net.
So with caching, the advantage is NOT that you kill off all future resource requests, i.e. a Uri lookup is still made to the net but rather that if possible the browser will pull from the local cache to satisify the need for the content, rather than run around the net looking for it. | How does the javascript preloading work? | [
"",
"javascript",
"browser",
"preloader",
"image-preloader",
""
] |
### Background
Consider the following:
```
template <unsigned N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
};
```
This is a common example and we can get the value of a Fibonacci number as a compile-time constant:
```
int main(void)
{
std::cout << "Fibonacci(15) = ";
std::cout << Fibonacci<15>::value;
std::cout << std::endl;
}
```
But you obviously cannot get the value at runtime:
```
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
// ensure the table exists up to a certain size
// (even though the rest of the code won't work)
static const unsigned fibbMax = 20;
Fibonacci<fibbMax>::value;
// get index into sequence
unsigned fibb = std::rand() % fibbMax;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << Fibonacci<fibb>::value;
std::cout << std::endl;
}
```
Because **fibb** is not a compile-time constant.
### Question
So my question is:
What is the best way to peek into this table at run-time? The most obvious solution (and "solution" should be taken lightly), is to have a large switch statement:
```
unsigned fibonacci(unsigned index)
{
switch (index)
{
case 0:
return Fibonacci<0>::value;
case 1:
return Fibonacci<1>::value;
case 2:
return Fibonacci<2>::value;
.
.
.
case 20:
return Fibonacci<20>::value;
default:
return fibonacci(index - 1) + fibonacci(index - 2);
}
}
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
static const unsigned fibbMax = 20;
// get index into sequence
unsigned fibb = std::rand() % fibbMax;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << fibonacci(fibb);
std::cout << std::endl;
}
```
But now the size of the table is very hard coded and it wouldn't be easy to expand it to say, 40.
The only one I came up with that has a similiar method of query is this:
```
template <int TableSize = 40>
class FibonacciTable
{
public:
enum
{
max = TableSize
};
static unsigned get(unsigned index)
{
if (index == TableSize)
{
return Fibonacci<TableSize>::value;
}
else
{
// too far, pass downwards
return FibonacciTable<TableSize - 1>::get(index);
}
}
};
template <>
class FibonacciTable<0>
{
public:
enum
{
max = 0
};
static unsigned get(unsigned)
{
// doesn't matter, no where else to go.
// must be 0, or the original value was
// not in table
return 0;
}
};
int main(void)
{
std::srand(static_cast<unsigned>(std::time(0)));
// get index into sequence
unsigned fibb = std::rand() % FibonacciTable<>::max;
std::cout << "Fibonacci(" << fibb << ") = ";
std::cout << FibonacciTable<>::get(fibb);
std::cout << std::endl;
}
```
Which seems to work great. The only two problems I see are:
* Potentially large call stack, since calculating Fibonacci<2> requires we go through TableMax all the way to 2, and:
* If the value is outside of the table, it returns zero as opposed to calculating it.
So is there something I am missing? It seems there should be a better way to pick out these values at runtime.
A template metaprogramming version of a switch statement perhaps, that generates a switch statement up to a certain number?
Thanks in advance. | ```
template <unsigned long N>
struct Fibonacci
{
enum
{
value = Fibonacci<N-1>::value + Fibonacci<N-2>::value
};
static void add_values(vector<unsigned long>& v)
{
Fibonacci<N-1>::add_values(v);
v.push_back(value);
}
};
template <>
struct Fibonacci<0>
{
enum
{
value = 0
};
static void add_values(vector<unsigned long>& v)
{
v.push_back(value);
}
};
template <>
struct Fibonacci<1>
{
enum
{
value = 1
};
static void add_values(vector<unsigned long>& v)
{
Fibonacci<0>::add_values(v);
v.push_back(value);
}
};
int main()
{
vector<unsigned long> fibonacci_seq;
Fibonacci<45>::add_values(fibonacci_seq);
for (int i = 0; i <= 45; ++i)
cout << "F" << i << " is " << fibonacci_seq[i] << '\n';
}
```
After much thought into the problem, I came up with this solution. Of course, you still have to add the values to a container at run-time, but (importantly) they are not *computed* at run-time.
As a side note, it's important not to define `Fibonacci<1>` above `Fibonacci<0>`, or your compiler will get *very* confused when it resolves the call to `Fibonacci<0>::add_values`, since `Fibonacci<0>`'s template specialization has not been specified.
Of course, TMP has its limitations: You need a precomputed maximum, and getting the values at run-time requires recursion (since templates are defined recursively). | I know this question is old, but it intrigued me and I had to have a go at doing without a dynamic container filled at runtime:
```
#ifndef _FIBONACCI_HPP
#define _FIBONACCI_HPP
template <unsigned long N>
struct Fibonacci
{
static const unsigned long long value = Fibonacci<N-1>::value + Fibonacci<N-2>::value;
static unsigned long long get_value(unsigned long n)
{
switch (n) {
case N:
return value;
default:
return n < N ? Fibonacci<N-1>::get_value(n)
: get_value(n-2) + get_value(n-1);
}
}
};
template <>
struct Fibonacci<0>
{
static const unsigned long long value = 0;
static unsigned long long get_value(unsigned long n)
{
return value;
}
};
template <>
struct Fibonacci<1>
{
static const unsigned long long value = 1;
static unsigned long get_value(unsigned long n)
{
if(n == N){
return value;
}else{
return 0; // For `Fibonacci<N>::get(0);`
}
}
};
#endif
```
This seems to work, and when compiled with optimizations (not sure if you were going to allow that), the call stack does not get to deep - there is normal runtime recursion on the stack of course for values (arguments) n > N, where N is the TableSize used in the template instantiation. However, once you go below the TableSize the generated code substitutes a constant computed at compile time, or at worst a value "computed" by dropping through a jump table (compiled in gcc with -c -g -Wa,-adhlns=main.s and checked the listing), the same as I reckon your explicit switch statement would result in.
When used like this:
```
int main()
{
std::cout << "F" << 39 << " is " << Fibonacci<40>::get_value(39) << '\n';
std::cout << "F" << 45 << " is " << Fibonacci<40>::get_value(45) << '\n';
}
```
There is no call to a computation at all in the first case (value computed at compile time), and in the second case the call stack depth is at worst:
```
fibtest.exe!Fibonacci<40>::get_value(unsigned long n=41) Line 18 + 0xe bytes C++
fibtest.exe!Fibonacci<40>::get_value(unsigned long n=42) Line 18 + 0x2c bytes C++
fibtest.exe!Fibonacci<40>::get_value(unsigned long n=43) Line 18 + 0x2c bytes C++
fibtest.exe!Fibonacci<40>::get_value(unsigned long n=45) Line 18 + 0xe bytes C++
fibtest.exe!main() Line 9 + 0x7 bytes C++
fibtest.exe!__tmainCRTStartup() Line 597 + 0x17 bytes C
```
I.e. it recurses until it finds a value in the "Table". (verified by stepping through Disassembly in the debugger line by line, also by replacing the test ints by a random number <= 45)
The recursive part could also be replaced by the linear iterative solution:
```
static unsigned long long get_value(unsigned long n)
{
switch (n) {
case N:
return value;
default:
if (n < N) {
return Fibonacci<N-1>::get_value(n);
} else {
// n > N
unsigned long long i = Fibonacci<N-1>::value, j = value, t;
for (unsigned long k = N; k < n; k++) {
t = i + j;
i = j;
j = t;
}
return j;
}
}
}
``` | Getting template metaprogramming compile-time constants at runtime | [
"",
"c++",
"templates",
"runtime",
"metaprogramming",
""
] |
I am using WCF to send some Linq objects across the wire. I want to log message size either using Message logging or tracing. I don't however want, or have the ability to use the config file to set this up. I am struggling to figure out how to do this programatically. I don't care if this happens at the host of client. I control both.
Does anyone have experience doing this? | Marc's right, Message Inspectors will allow you to do this. Create a class that: Implements [IDispatchMessageInspector](http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.idispatchmessageinspector.aspx). The below method will be made available where you can implement code to manipulate the request message.
```
Public Function AfterReceiveRequest(ByRef request As System.ServiceModel.Channels.Message, ByVal channel As System.ServiceModel.IClientChannel, ByVal instanceContext As System.ServiceModel.InstanceContext) As Object Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest
'Output the request message to immediate window
System.Diagnostics.Debug.WriteLine("*** SERVER - RECEIVED REQUEST ***")
System.Diagnostics.Debug.WriteLine(request.ToString())
Return Nothing
End Function
```
Also, the following [Link](http://weblogs.asp.net/paolopia/archive/2007/08/23/writing-a-wcf-message-inspector.aspx) may also provide some help.
Good Luck | Not programming, but perhaps: [wireshark](http://www.wireshark.org/)?
Alternatively, look into [message inspectors](http://msdn.microsoft.com/en-us/library/aa717047.aspx). I don't have a specific example for size logging, though. | Logging WCF message sizes | [
"",
"c#",
"wcf",
"logging",
"message",
""
] |
There are 2 html files, file-1.htm and file-2.htm. There is another html file, test.htm, with a drop-down having 2 values, "Load Sample-1" and "Load Sample-2".
This is what I am trying:
When "Load Sample-1" is selected from the drop-down, file-1.htm should be loaded as a nested html in test.htm.
Right now I am able to achieve this through javascript by having the content of file-1.htm and file-2.htm inside test.htm. Bt as the drop-down grows bigger, test.htm would become huge. How can this be achieved by having separate html files for each entry in the drop-down? | Why don't you just use an [`<iframe>`](http://www.w3schools.com/TAGS/tag_iframe.asp), and then have the JavaScript dynamically change the source of the iframe?
Here's a bare-bones page demonstrating how to use this:
```
<html>
<head>
<script type="text/javascript">
var changePage = function() {
var iframe = document.getElementById("myiframe"); // One of the many ways to select your iframe
var select = document.getElementById("pageselected");
var url = select.options[select.selectedIndex].value;
iframe.src = url;
}
</script>
</head>
<body>
<select id="pageselected">
<option value="page1.html">Page 1</option>
<option value="page2.html">Page 2</option>
</select>
<input type="button" onclick="changePage()" value="Change Page" />
<iframe id="myiframe"></iframe>
</body>
</html>
```
You may be asking yourself "why did he not just use `onchange` for the `<select>`? Well, I've got a little war going with `<select>` + `onchange` that [I detail here](https://stackoverflow.com/questions/586936/jquery-change-on-select-and-firefox/586969#586969), but basically using it makes your website completely inaccessible to keyboard-only users who are using Internet Explorer 6 or 7. (Not sure if it is still broken in 8.) | If you use JQuery they have a fancy function jquery('#div').load()
<http://jquery.com/>
<http://docs.jquery.com/Ajax/load>
Works great and also supports GET and POST parameters. | Insert one HTML file in another dynamically? | [
"",
"javascript",
"html",
""
] |
Is there a platform-independent method to embed file data into a c++ program? For instance, I am making a game, and the levels are stored in text format. But I don't want to distribute those text files with the game itself. What are my options? | This has been [asked here before](https://stackoverflow.com/questions/72616/embed-data-in-a-c-program). Basically, you just name the data with an accessible symbol. I like this method best:
> You can always write a small program or script to convert your text file into a header > > file and run it as part of your build process. | You can always put the text in the code. Say, for example, as an array of Strings or array of pointers to characters.
```
String txt[] = {
"My first line.\n",
"My second line.\n"
}
```
Of course there are better structures in the standard libraries, but in any case you put the text in a source file.
You could also consider putting the text into the package and encrypting it, if you're worried about people accessing it. | Embedding data inside a c++ application | [
"",
"c++",
"cross-platform",
""
] |
This is a javascript security question: suppose a page finds out the screen resolution of the computer, such as 1024 x 768, and want to use an AJAX call to log this data into the DB.
Is there a way to actually prevent fake data from being entered into the DB? I think whatever the HTML or Javascript does, the user can reverse engineer the code so that some fake numbers get entered into the DB, or is there a way prevent it from happening totally? (100% secure).
**Update**: or in a similar situation... if i write a simple javascript game... is there a way for the user to send back the score by AJAX and lie about their score? | If you start with the assumption that the user you are communicating with is malicious, then no; there is nothing you can do to control what data they pass you. Certainly not with 100% certainty - in the worst case, they can use network tools to rewrite or replace any "correct" content with whatever they want.
If you just want to prevent casual maliciousness, you could obfuscate or encrypt your code and/or data. This will not deter a determined attacker.
If you actually trust the real user, but suspect that others might try to impersonate them, you can use other techniques like a dynamic canary: send the user a random number, and if they return that same number to you, you know that it really came from them. (Or you're being hit by a man-in-the-middle attack, but hey; that's what SSL is for.) | It's not possible to stop users from sending any numbers they like back from JavaScript.
I think the best you could do is do some sort of check on the server-side to make sure the numbers sent back look like a realistic resolution.
I'm not sure why someone would spend the time to spoof those numbers in the first place though. | javascript securty: an AJAX call to record the user's screen resolution, is it possible to prevent fake numbers? | [
"",
"javascript",
"security",
"csrf",
"javascript-security",
""
] |
I'd like to load a font from an external server and once is loaded (I guess that's necessary) use it to create a few textfields.
I'm trying:
```
font_uri = new Uri("http://localhost/assets/fonts/wingding.ttf");
bf_helvetica = new FontFamily(font_uri, "bf_helvetica");
TextBlock test_tb = new TextBlock();
test_tb.Text = "This is a test";
test_tb.FontSize = 16;
test_tb.Foreground = Brushes.Red;
test_tb.FontFamily = bf_helvetica;
stage.Children.Add(test_tb);
```
But it creates the textblock with the default font.
Any ideas?
Thanks in advance :) | If you can load it into a Stream, try using a [PrivateFontCollection](http://msdn.microsoft.com/en-us/library/system.drawing.text.privatefontcollection.aspx). Example code in [my answer to another question](https://stackoverflow.com/questions/727053/how-do-i-embed-a-font-with-my-c-application-using-visual-studio-2005/727127#727127).
**EDIT**: See [System.Net.WebRequest.GetRequestStream](http://msdn.microsoft.com/en-us/library/system.net.webrequest.getrequeststream.aspx), load the URI into a Stream, then load that Stream into the PFC as mentioned in the linked code.
Also, I'd save the file locally, and look for it there first, so you don't have to download it every time you run the program.
**EDIT AGAIN**: Sorry, not WebRequest.GetRequestStream, you want WebResponse.GetResponseStream(). Here's some sample code to do exactly what you're looking for.
```
using System;
using System.Drawing;
using System.Drawing.Text;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;
namespace RemoteFontTest
{
public partial class Form1 : Form
{
readonly PrivateFontCollection pfc = new PrivateFontCollection();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebRequest request = WebRequest.Create(@"http://somedomain.com/foo/blah/somefont.ttf");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
using (Stream fontStream = response.GetResponseStream())
{
if (null == fontStream)
{
return;
}
int fontStreamLength = (int)fontStream.Length;
IntPtr data = Marshal.AllocCoTaskMem(fontStreamLength);
byte[] fontData = new byte[fontStreamLength];
fontStream.Read(fontData, 0, fontStreamLength);
Marshal.Copy(fontData, 0, data, fontStreamLength);
pfc.AddMemoryFont(data, fontStreamLength);
Marshal.FreeCoTaskMem(data);
}
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
using (SolidBrush brush = new SolidBrush(Color.Black))
{
using (Font font = new Font(pfc.Families[0], 32, FontStyle.Regular, GraphicsUnit.Point))
{
e.Graphics.DrawString(font.Name, font, brush, 10, 10, StringFormat.GenericTypographic);
}
}
}
}
}
``` | Is the family name you pass to the FontFamily constructor actually a family name exposed by the font file? In your example, if you loaded the Wingding.ttf, the font family name would be Wingdings, not bf\_helvetica. If the font file is bf\_helvetica.ttf, the family name is likely something other than the name of the font, like Helvetica or Helvetica Bold. | Load external font and use it in C# | [
"",
"c#",
"wpf",
"fonts",
"load",
""
] |
Okay, so I'm trying to set a variable via a javascript method call. However this is not working. I googled and ended ip going back and trying swLiveConnect, but that's outdated and it turns out my way is now the way to do it. So here's my javascript function and actionscript. I have no idea what's going on, I bow before the more skilled actionscripters.
**Actionscript**
```
//==========================================================
function decide_proposal(e:Event):void {
//==========================================================
var address1:String = form1.project_address.text + ", " + form1.project_city.text + ", " + form1.project_state.text + ", " + form1.project_zip.text;
var distance:Number = ExternalInterface.call("showLocation(" + address1 + ")");
var commit:String = e.currentTarget.name;
if (form1.stories.value >= 2.5 || form1.wood_no.selected || form1.framed_sqft.value >= 5000 || form1.roof_slope.value < 3 || form1.civil.selected || form1.cmt.selected || form1.commercial.selected || form1.c.selected || distance >= 180 || form1.bore_holes1.value >= 4) {
send_proposal(e);
} else if (commit == "quote") {
perform_calculations(distance);
} else {
send_proposal(e);
}
}
```
**Javascript**
```
var geocoder;
var location1;
function initialize() {
geocoder = new GClientGeocoder();
}
function showLocation(address) {
var locations = 0;
geocoder.getLocations(address, function (response) {
if (!response || response.Status.code != 200)
{
alert("There was an error");
}
else
{
location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0]};
}
});
var glatlng1 = new GLatLng(location1.lat, location1.lon);
var brenham = new GLatLng(30.152289,-96.384881);
var college_station = new GLatLng(30.610584,-96.306002);
var miledistance1 = glatlng1.distanceFrom(brenham);
var miledistance2 = glatlng1.distanceFrom(college_station);
if (miledistance1 <= miledistance2) {
locations = (miledistance1 * .000621371192);
} else {
locations = (miledistance2 * .000621371192);
}
return locations;
}
window.onload=function() {initialize();}
```
I'm fairly certain it has something to do with return, but am not sure. At this point I have tried tracing what address is getting passed to the function, it is correct. I have traced what the distance is set to before and after the call. Before, NaN; after, 0. From Firebug I get the correct number. I just don't know. | Okay the problem was simple. I was passing the parameters to the function incorrectly. Here's how you do it:
```
var distance:Number = ExternalInterface.call("showLocation", address1);
```
Annnnd Bob's your uncle. | Make sure you have allowScriptAccess="always" in the HTML object/embed code. | Javascript and Actionscript 3 [Setting a variable woes] | [
"",
"javascript",
"actionscript-3",
"google-maps",
""
] |
Is there any built-in support for that? And if not, is there any consensus about handling such dates?
---
Links to owncoded solutions, or fragments of it, are very welcome. | There is no built in support for dates in this range so you will have to code your own.
Here is an example <http://flipbit.co.uk/2009/03/representing-large-ad-and-bc-dates-in-c.html>. | If you're referring the handling of DateTime values < DateTime.MinValue, then I think the only "consensus" is to not use System.DateTime to try to represent them.
Any consensus would likely exist only within a community that does work with such dates. What is the area in which you are working? Astronomy?
---
Whatever the area of interest, there are likely to be others who have experienced this same problem. I'd do some research first, especially if your dates will ever need to interoperate with other software in this same area of interest. Even if you have to code your own, you can at least become aware of the issues that others have had in coding *their* own. | What is the (best) way to handle dates before Christ in C#/.NET? | [
"",
"c#",
".net",
"datetime",
""
] |
I am currently running jetty from eclipse as an external java program. The problem is when I terminate jetty and I try to relaunch it again, it cannot due to the port still being in use.
What I have to do is open up Windows Task Manager and kill the java process manually. How do you get jetty to shutdown/terminate/end nicely?
The following are my maven jetty application settings
> Arguments: jetty:run-war
>
> MAVEN\_OPTS: -Xdebug -Xnoagent
> -Djava.compiler=NONE -Xrunjdwp:transport=dt\_socket, address=8080,server=y, suspend=y
Setting suspend=n doesn't seem to solve the problem either. | It seems that I forgot to tick "Allow termination of remote VM". Strange that it didn't seem to work before. | If a java application does not shutdown it is because of an alive non-daemon thread. Try getting a thread dump of the running maven process, e.g. using [VisualVM](https://visualvm.dev.java.net/) and see what keeps the application alive. | maven jetty does not shutdown properly in eclipse | [
"",
"java",
"eclipse",
""
] |
I am trying to use JDBC and my query is working in some cases but not working in others.
I would really appreciate any help.
Some of my code:
```
public Result getSpecificTopic()
{
String query = "Select msg_body, msg_author from lawers_topic_msg";// where msg_id=2 order by msg_id desc";
try
{
con = mysql.getConnection();
//Statement stmt = con.createStatement();
PreparedStatement stmt = con.prepareStatement(query);
//stmt.setInt(1, topicId);
ResultSet rs = stmt.executeQuery(query);
int rowCount = rs.getRow();
specificTopic = ResultSupport.toResult(rs);
con.close();
stmt.close();
}
catch(Exception e)
{
}
return this.specificTopic;
}
public void setTopicId(String num)
{
this.topicId = Integer.parseInt(num);
}
public int getTopicId()
{
return this.topicId;
}
```
However if i change
```
String query = "Select msg_body, msg_author from lawers_topic_msg";
```
to the
```
String query = "Select msg_body, msg_author from lawers_topic_msg where msg_id = " + topicId;
```
Then the resultset retunrs nothing....
I am breaking my head here and still cannot figure out what is the problem | As a first step, it'd be worth making sure an exception's not being thrown - at the very least log something in your catch() block.
Also be worth logging the SQL generated, and making sure that actually returns what you expect from the database when running it directly.
If you have multiple databases, it'd be worth confirming you're running against the one you think you are - I'm embarrassed to admit I've been caught out that way before. | You still aren't closing your resources properly. That should be done in a finally block:
<http://www.java-blog.com/correct-closing-jdbc-resources> | Strange problem with JDBC, select returns null | [
"",
"java",
"jsp",
"jdbc",
""
] |
I've got the following two programs, one acting as a reader and the other as a writer. The writer seems to only send about 3/4 of the data correctly to be read by the reader. Is there any way to guarantee that all the data is being sent? I think I've got it set up so that it reads and writes reliably, but it still seems to miss 1/4 of the data.
Heres the source of the writer
```
#define pipe "/tmp/testPipe"
using namespace std;
queue<string> sproutFeed;
ssize_t r_write(int fd, char *buf, size_t size) {
char *bufp;
size_t bytestowrite;
ssize_t byteswritten;
size_t totalbytes;
for (bufp = buf, bytestowrite = size, totalbytes = 0;
bytestowrite > 0;
bufp += byteswritten, bytestowrite -= byteswritten) {
byteswritten = write(fd, bufp, bytestowrite);
if(errno == EPIPE)
{
signal(SIGPIPE,SIG_IGN);
}
if ((byteswritten) == -1 && (errno != EINTR))
return -1;
if (byteswritten == -1)
byteswritten = 0;
totalbytes += byteswritten;
}
return totalbytes;
}
void* sendData(void *thread_arg)
{
int fd, ret_val, count, numread;
string word;
char bufpipe[5];
ret_val = mkfifo(pipe, 0777); //make the sprout pipe
if (( ret_val == -1) && (errno != EEXIST))
{
perror("Error creating named pipe");
exit(1);
}
while(1)
{
if(!sproutFeed.empty())
{
string s;
s.clear();
s = sproutFeed.front();
int sizeOfData = s.length();
snprintf(bufpipe, 5, "%04d\0", sizeOfData);
char stringToSend[strlen(bufpipe) + sizeOfData +1];
bzero(stringToSend, sizeof(stringToSend));
strncpy(stringToSend,bufpipe, strlen(bufpipe));
strncat(stringToSend,s.c_str(),strlen(s.c_str()));
strncat(stringToSend, "\0", strlen("\0"));
int fullSize = strlen(stringToSend);
signal(SIGPIPE,SIG_IGN);
fd = open(pipe,O_WRONLY);
int numWrite = r_write(fd, stringToSend, strlen(stringToSend) );
cout << errno << endl;
if(errno == EPIPE)
{
signal(SIGPIPE,SIG_IGN);
}
if(numWrite != fullSize )
{
signal(SIGPIPE,SIG_IGN);
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
close(fd);
}
else
{
signal(SIGPIPE,SIG_IGN);
sproutFeed.pop();
close(fd);
bzero(bufpipe, strlen(bufpipe));
bzero(stringToSend, strlen(stringToSend));
}
}
else
{
if(usleep(.0002) == -1)
{
perror("sleeping error\n");
}
}
}
```
}
```
int main(int argc, char *argv[])
{
signal(SIGPIPE,SIG_IGN);
int x;
for(x = 0; x < 100; x++)
{
sproutFeed.push("All ships in the sea sink except for that blue one over there, that one never sinks. Most likley because it\'s blue and thats the mightiest colour of ship. Interesting huh?");
}
int rc, i , status;
pthread_t threads[1];
printf("Starting Threads...\n");
pthread_create(&threads[0], NULL, sendData, NULL);
rc = pthread_join(threads[0], (void **) &status);
}
```
Heres the source of the reader
```
#define pipe "/tmp/testPipe"
char dataString[50000];
using namespace std;
char *getSproutItem();
void* readItem(void *thread_arg)
{
while(1)
{
x++;
char *s = getSproutItem();
if(s != NULL)
{
cout << "READ IN: " << s << endl;
}
}
}
ssize_t r_read(int fd, char *buf, size_t size) {
ssize_t retval;
while (retval = read(fd, buf, size), retval == -1 && errno == EINTR) ;
return retval;
}
char * getSproutItem()
{
cout << "Getting item" << endl;
char stringSize[4];
bzero(stringSize, sizeof(stringSize));
int fd = open(pipe,O_RDONLY);
cout << "Reading" << endl;
int numread = r_read(fd,stringSize, sizeof(stringSize));
if(errno == EPIPE)
{
signal(SIGPIPE,SIG_IGN);
}
cout << "Read Complete" << endl;
if(numread > 1)
{
stringSize[numread] = '\0';
int length = atoi(stringSize);
char recievedString[length];
bzero(recievedString, sizeof(recievedString));
int numread1 = r_read(fd, recievedString, sizeof(recievedString));
if(errno == EPIPE)
{
signal(SIGPIPE,SIG_IGN);
}
if(numread1 > 1)
{
recievedString[numread1] = '\0';
cout << "DATA RECIEVED: " << recievedString << endl;
bzero(dataString, sizeof(dataString));
strncpy(dataString, recievedString, strlen(recievedString));
strncat(dataString, "\0", strlen("\0"));
close(fd);
return dataString;
}
else
{
return NULL;
}
}
else
{
return NULL;
}
close(fd);
```
}
```
int main(int argc, char *argv[])
{
int rc, i , status;
pthread_t threads[1];
printf("Starting Threads...\n");
pthread_create(&threads[0], NULL, readItem, NULL);
rc = pthread_join(threads[0], (void **) &status);
}
``` | You are definitely using signals the wrong way. Threads are completely unnecessary here - at least in the code provided. String calculations are just weird. Get [this book](http://www.kohala.com/start/apue.html) and do not touch the keyboard until you finished reading :) | It's difficult to say what is going on here. Maybe you are getting an error returned from one of your system calls? Are you sure that you are successfully sending all of the data?
You also appear to have some invalid code here:
```
int length = atoi(stringSize);
char recievedString[length];
```
This is a syntax error, since you cannot create an array on the stack using a non-constanct expression for the size. Maybe you are using different code in your real version?
Do you need to read the data in a loop? Sometimes a function will return a portion of the available data and require you to call it repeatedly until all of the data is gone.
Some system calls in Unix can also return EAGAIN if the system call is interrupted - you are not handling this case by the looks of things. | How to guarantee read() actually sends 100% of data sent by write() through named pipes | [
"",
"c++",
"unix",
"named-pipes",
""
] |
I am using a Richfaces' [picklist](http://livedemo.exadel.com/richfaces-demo/richfaces/pickList.jsf?tab=usage&cid=5212106) and I want to populate the right-side panel with a list of SelectItems from my backing bean.
Populating the left-side is not a problem from the backing bean, however, the right hand side is problematic.
This is what I currently have
```
<h:outputText value="Roles" />
<rich:pickList showButtonsLabel="false">
<f:selectItems value="#{Bean.allRoles}" />
</rich:pickList>
```
**EDIT:**
So I have roles 'a', 'b', 'c', and 'd'.
The user has roles 'a' and 'd', so 'a' and 'd' should be on the right-side panel and 'b' and 'c' should be on the left-side panel.
**EDIT:**
Further explanation.
I have three lists for the user.
1. All posible roles (a thru d)
2. All roles the user is part of (a and d)
3. All roles the user is NOT part of (b and c)
All lists have the data type `ArrayList<SelectItem>`.
I need the capability to move individual roles between list number 1 and list number 2 and then save the new set of roles. I thought the picklist would be the best richfaces object for the job. | You want this code:
```
<h:outputText value="Roles" />
<rich:pickList showButtonsLabel="false" value="#{bean.chosenRoles}">
<f:selectItems value="#{Bean.allRoles}" />
</rich:pickList>
```
and in your bean you want:
```
private String[] chosenRoles;
+ getter/setter
```
Whenver you want to make default roles you just add the roles into the chosenRoles array (for example in the bean constructor). That way chosenRoles will always contain the elements on the right side of the picklist, while elements on the left side are not in the array.
Hope this helps! | It seems that I found the solution.
```
<rich:pickList value="#{aBean.rightSideValues}">
<f:selectItems value="#{aBean.leftSideValues}"/>
</rich:pickList>
```
* **`"#{aBean.rightSideValues}"`** should point to the list or array of
objects. With these values right side
of the pick list will be populated.
* **`#{aBean.leftSideValues}`** should point to the list of the SelectItem
object.
**ONE NOTICE -- SelectItem object MUST BE constructed with objects from the `"#{aBean.rightSideValues}"`**.
***Example***.
```
class ABean{
...
List<SomeObject> getRightSideValues(){
...
}
List<SelectItem> getLeftSideValues(){
List<SomeObjects> someObjects = getAllAvailableObjects();
List<SelectItem> sItems = new ArrayList<SelectItem>();
for(SomeObject sObj : someObjects){
SelectItem sItem = new SelectItem(sObj, sObj.toString());
sItems.add(sItem);
}
return sItems;
}
```
Notice that SelectItem takes first argument and this argument is the reference to the SomeObject. In the internals rich faces will compare objects from the **`"#{aBean.rightSideValues}"`** with objects from the
**`#{aBean.leftSideValues}`** with help of the method
`SomeObject.equals()` | How to populate the right side of a richfaces picklist? | [
"",
"java",
"jsf",
"richfaces",
""
] |
I am trying to use the myType class declared in the package
com.mycompany.myproject in a class that lives in
com.mycompany.myproject.client but I am getting the following errors
when compiling:
> [ERROR] Line [X]: The import com.mycompany.myproject.myType cannot be
> resolved
If I try to run the hosted browser I get:
> [ERROR] Line [X]: No source code is available for type
> com.mycompany.myproject.myType; did you forget to inherit a required
> module?
Any idea? | This error means that the GWT compiler cannot find your class. The GWT compiler can only find classes referenced by the .gwt.xml file for your project.
It's all explained here:
<http://code.google.com/webtoolkit/doc/latest/DevGuideOrganizingProjects.html> | project structure:
* com.mycompany.service
* com.mycompany.myproject
+ client
+ service
+ myproject.gwt.xml
the source package by default is "client" that is placed in the same directory with
gwt.xml file. If you want to add or change source directory - you have to edit gwt.xml.
1) for instance, you want make available for gwt package "com.my~ny.p~ct.service".
In gwt.xml file add < source path="service"/>.
path-attribute values like "../", "." - will not work.
2) if you want to make available "com.my~ny.service" package.
create module (gwt.xml file) in com.mycompany,
where you have point source directory
and inherit default gwt User module. | Cannot use class in client package with GWT | [
"",
"java",
"gwt",
""
] |
In python 2.x I could do this:
```
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
```
Now however, I get a `TypeError: can't write bytes to text stream`. Is there some secret encoding that I should use? | A better way:
```
import sys
sys.stdout.buffer.write(b"some binary data")
``` | An idiomatic way of doing so, which is only available for Python 3, is:
```
with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
stdout.write(b"my bytes object")
stdout.flush()
```
The good part is that it uses the normal file object interface, which everybody is used to in Python.
Notice that I'm setting `closefd=False` to avoid closing `sys.stdout` when exiting the `with` block. Otherwise, your program wouldn't be able to print to stdout anymore. However, for other kind of file descriptors, you may want to skip that part. | How to write binary data to stdout in python 3? | [
"",
"python",
"python-3.x",
""
] |
I have a small problem where I want to find the next "active" item in a list with linq. Then next "active" item is defined by a startDate and EndDate. Here is an example list.
```
//-- Create Lists of turns
IList<Turn> turns= new List<Turn>(){
new Turn(){Name = "Turn 1", StartDate = DateTime.Parse("2009-05-01"), EndDate = DateTime.Parse("2009-05-01") }
, new Turn(){Name = "Turn 2", StartDate = DateTime.Parse("2009-06-01"), EndDate = DateTime.Parse("2009-06-01") }
, new Turn(){Name = "Turn 3", StartDate = DateTime.Parse("2009-07-01"), EndDate = DateTime.Parse("2009-07-02") }
, new Turn(){Name = "Turn 4", StartDate = DateTime.Parse("2009-08-01"), EndDate = DateTime.Parse("2009-08-03") }
}
//-- Get the next Turn by DateTime.
DateTime toDay = DateTime.Parse("2009-06-02");
//-- Should return the "Turn 3" item...
Turn turn = (from item in turns
where .....
select turn).FirstOrDefault<Turn>();
```
Is there a good solution to find the next turn by using startDate/endDate properties on Turn. I have tryed to first order the list by startdate and the find First one in the list, but I wounder if there is a more "safe" way to get it that dosen't need the list in correct order to find the correct Turn. | Why don't you just get the first item with a start date after today? I added an explict `OrderBy()` call just to be sure that the list is sorted. If you know that it is sorted, you can leave that out, of course.
```
turns.OrderBy(t => t.StartDate).FirstOrDefault(t => t.StartDate > today);
```
**UPDATE**
I missed your last lines. Yes, you can do it without sorting the list explicitly. You have to search the list for the item with a start date after today and ther must be no item with a start date after today but before that of the current item. But this will really slow down the search because you have to look at the whole list for every item making the thing O(n²).
```
turns.Single(t =>
t.StartDate > today &&
turns.All(u => u.StartDate <= today || u.StartDate > t.StartDate))
```
This assumes that the turns are non-overlapping. If they overlapp, you must use `First` instead of `Single` or add additional constraints to get a unique result. **And finally: use the the sorting solution - this solution is by no means safer than sorting and getting the first item.** | You could do this.
```
Turn turn = turns
.Where(t => t.StartDate >= toDay)
.OrderBy(t => t.StartDate)
.FirstOrDefault();
```
The Where call is optional - its goal is to reduce the amount of items that have to be ordered. | How to get next active item in a list with LINQ | [
"",
"c#",
".net",
"linq",
""
] |
A basic simple question for all of you DBA.
When I do a select, is it always guaranteed that my result will be ordered by the primary key, or should I specify it with an 'order by'?
I'm using Oracle as my DB. | No, if you do not use "order by" you are not guaranteed any ordering whatsoever. In fact, you are not guaranteed that the ordering from one query to the next will be the same. Remember that SQL is dealing with data in a set based fashion. Now, one database implementation or another may happen to provide orderings in a certain way but you should never rely on that. | > When I do a select, is it always guaranteed that my result will be ordered by the primary key, or should I specify it with an 'order by'?
No, it's by far not guaranteed.
```
SELECT *
FROM table
```
most probably will use `TABLE SCAN` which does not use primary key at all.
You can use a hint:
```
SELECT /*+ INDEX(pk_index_name) */
*
FROM table
```
, but even in this case the ordering is not guaranteed: if you use `Enterprise Edition`, the query may be parallelized.
This is a problem, since `ORDER BY` cannot be used in a `SELECT` clause subquery and you cannot write something like this:
```
SELECT (
SELECT column
FROM table
WHERE rownum = 1
ORDER BY
other_column
)
FROM other_table
``` | Does 'Select' always order by primary key? | [
"",
"sql",
"database",
"oracle",
"primary-key",
""
] |
I have seen many crazy methods to get access to private variables when unit testing. The most mind-blowing I've seen is `#define private public`.
However, I've never seen anyone suggest turning off private variables at the compiler level. I had always just assumed that you couldn't. I've complained to many a developer that unit testing would be a lot easier if you could just tell the compiler to back off for this one file.
Then I stumble across the `-fno-access-control` GCC compiler option. It's so obviously the perfect way to unit test. Your original source files are unmodified, no injected friends just for the unit test, no recompiling with bizarre preprocessor magic. Just flick the 'no access control' switch when compiling your unit tests.
Am I missing something? Is this the unit testing silver bullet I hope it is?
The only disadvantage I see is the GCC-specific nature of the technique. However, I assume MSVS has a similar flag. | I would argue that unit tests should not need access to private members.
In general, unit tests are meant to test the *interface* to your classes, not the internal implementation. That way, changes to the internals will only break the tests if the interface has been compromised.
Have a look at my [answer](https://stackoverflow.com/questions/342037/testing-classes/342065#342065) to a similar question, and the ensuing discussion. It is a controversial topic, to be sure, but that's my $0.02. | I normally try to use only the public interface of my classes in unit tests. Test Driven Development/Design helps a lot here as the resulting classes tend to enable this style of unit test.
However sometimes you do need to let a unit test access non public members, eg replace the contents of a Singleton with a Fake instance. For this I use package protection in Java and friends in C++.
Some people seem to bend over backwards to avoid friends but they should be used when appropriate and their use doesn't compromise the design. They are also declarative and let other programmers know what you are doing. | Unit testing with -fno-access-control | [
"",
"c++",
"unit-testing",
"gcc",
""
] |
I want to use JNI on Ubuntu 8.10, using Eclipse and gcc (the standard one with Ubuntu if there are flavours).
I can't seem to load my library despite the make file creating it successfully.
The main Java class is as follows:
```
class Hello {
public native void sayHello();
static {
System.loadLibrary("hello.so");
}
public static void main(String[] args) {
Hello h = new Hello();
h.sayHello();
}
}
```
My make file is as such;
```
all : hello.so
hello.so : Hello.o
gcc -shared -o hello.so Hello.o
Hello.o : Hello.c Hello.h
gcc -I/usr/lib/jvm/java-6-sun/include -I/usr/lib/jvm/java-6-sun/include/linux -c Hello.c -o Hello.o
Hello.h : Hello.class
javah -jni Hello
clean :
-del Hello.h
-del Hello.o
```
The rest of the code (Hello.c) looks like one would think.
The error I'm getting is as follows;
```
Exception in thread "main" java.lang.UnsatisfiedLinkError: no hello.so in java.library.path
```
If I use an explicit path:
```
System.loadLibrary("/home/gavin/Work/workspace/JNI/hello.so");
```
Then it works, but I'd much rather not use an explicit path if possible. | As per Pax you should set the library path to where ever Java should look for the library. Your library name should be libhello.so. The call to load the library should then be:
```
System.loadLibrary("hello");
```
Linux libraries are referenced by the convention lib**name**.so and loaded based on the name. Here is a [link](http://www.swig.org/Doc1.3/Java.html#dynamic_linking_problems) about dynamic linking problems in Java from the SWIG documentation, although you are not using SWIG this section is still relevant. | You're calling `System.loadLibrary()` incorrect. The `loadLibrary` method takes a library name, e.g. "hello", and tries to load the corresponding shared object. On Unix, it will attempt to load "libhello.so", and on windows it will try to load "hello.dll". It will expect the file to be found in `java.library.path`.
The method you probably intend to be calling is `System.load()` which takes a fully qualified filename and loads it. This method should take a `File` as argument, but it takes a string instead. If you use `load`, you'll have to handle local naming conventions manually, but you won't have to rely on `java.library.path` to be set. | How should I load native libraries for JNI to avoid an UnsatisfiedLinkError? | [
"",
"java",
"c",
"java-native-interface",
""
] |
What are the best practices for creating exceptions? I just saw this, and I don't know if I should be horrified, or like it. I read several times in books that exceptions should never ever hold a string, because strings themselves can throw exceptions. Any real truth to this?
Basically from my understanding from the scripts is that this was done so all the inhouse Python libraries will have a common error message format (something that is desperately needed) so I can understand why putting the error message string is a good idea. (Almost every method throws exceptions due to the utter need for nothing invalid getting through).
The code in question is the following:
```
"""
Base Exception, Error
"""
class Error(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return "[ERROR] %s\n" % str(self.message)
def log(self):
ret = "%s" % str(self.message)
if(hasattr(self, "reason")):
return "".join([ret, "\n==> %s" % str(self.reason)])
return ret
class PCSException(Error):
def __init__(self, message, reason = None):
self.message = message
self.reason = reason
def __str__(self):
ret = "[PCS_ERROR] %s\n" % str(self.message)
if(self.reason != None):
ret += "[REASON] %s\n" % str(self.reason)
return ret
```
This is just the tip of the iceberg, but can someone give me some insight in what makes this a terrible idea? Or if there is a much better exception coding process/style. | > I read several times in books that
> exceptions should never ever hold a
> string, because strings themselves can
> throw exceptions. Any real truth to
> this?
What?
Please provide a reference or a link to this. It's totally untrue.
Since all objects can throw exceptions, no object could be contained in an exception by that logic.
No, the "no strings" is simply crazy in a Python context. Perhaps you read it in a C++ context.
---
**Edit**
Once upon a time (back in the olden days) you could raise a Python exception by name instead of by the actual class.
```
raise "SomeNameOfAnExceptionClass"
```
This is bad. But this is *not* including a string inside an exception. This is naming the exception with a string instead of the actual class object. In 2.5, this can still work, but gets a deprecation warning.
Perhaps this is what you read "Do not raise an exception with a string name" | [Robust exception handling (in Python)](http://eli.thegreenplace.net/2008/08/21/robust-exception-handling/) - a "best practices for Python exceptions" blog post I wrote a while ago. You may find it useful.
Some key points from the blog:
> **Never use exceptions for flow-control**
>
> Exceptions exist for exceptional situations: events that are not a
> part of normal execution.
Consider 'find' on a string returning -1 if the pattern isn't found, but indexing beyond the end of a string raises an exception. Not finding the string is normal execution.
> **Handle exceptions at the level that knows how to handle them**
>
> ...
>
> The
> best place is that piece of code that can handle the exception. For
> some exceptions, like programming errors (e.g. IndexError, TypeError,
> NameError etc.) exceptions are best left to the programmer / user,
> because "handling" them will just hide real bugs.
Always ask "is this the right place to handle this exception?" and be careful with catching all exceptions.
> **Document the exceptions thrown by your code**
>
> ...
>
> thinking about which exceptions your code may throw will help you
> write better, safer and more encapsulated code | Best Practices for Python Exceptions? | [
"",
"python",
"exception",
""
] |
maybe it's dumb but is there a difference between
```
new Something().method();
```
and
```
Something tmpSomething = new Something();
tmpSomething.method();
```
as I was calling only one method on this particular object, I chose the first solution but I'm not sure that this is exactly the same behavior...
I just want to mention the constructor initializes a Writer and method writes in this file... | I did a quick test. This is the extremely trivial test code:
```
public class TestLiveness
{
public static void test1()
{
System.out.println(new Square(4).square());
count();
}
public static void test2()
{
Square t = new Square(4);
System.out.println(t.square());
count();
}
private static void count()
{
for(int i=0; i<1000000; i++)
System.out.println(i);
}
static class Square
{
private int val;
Square(int val)
{
this.val = val;
}
int square()
{
return val * val;
}
}
}
```
Javap shows that the two methods are compiled differently; chaining doesn't touch the local variable table whereas the temporary variable does indeed stick around until the method returns. However, the VM/JIT compiler may still perform liveness analysis and allow the instance to be garbage collected before the method returns.
```
public static void test1();
Code:
0: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
3: new #3; //class TestLiveness$Square
6: dup
7: iconst_4
8: invokespecial #4; //Method TestLiveness$Square."<init>":(I)V
11: invokevirtual #5; //Method TestLiveness$Square.square:()I
14: invokevirtual #6; //Method java/io/PrintStream.println:(I)V
17: invokestatic #7; //Method count:()V
20: return
public static void test2();
Code:
0: new #3; //class TestLiveness$Square
3: dup
4: iconst_4
5: invokespecial #4; //Method TestLiveness$Square."<init>":(I)V
8: astore_0
9: getstatic #2; //Field java/lang/System.out:Ljava/io/PrintStream;
12: aload_0
13: invokevirtual #5; //Method TestLiveness$Square.square:()I
16: invokevirtual #6; //Method java/io/PrintStream.println:(I)V
19: invokestatic #7; //Method count:()V
22: return
``` | There is no difference whatsoever except that in the second case you have an unnecessary variable lying around that makes the code harder to maintain.
Also, objects that get created only to be discarded after calling a single method constitute a [code smell](http://en.wikipedia.org/wiki/Code_smell). | Java: new Something().method() vs a temp variable | [
"",
"java",
""
] |
this is the code that I use to disable the button
```
$("#btnSubmit").attr('disabled', 'disabled')
$("#btnSubmit").disabled = true;
```
and this is my submit button
```
<input id="btnSubmit" class="grayButtonBlueText" type="submit" value="Submit" />
```
the button although looks disabled, you can still click on it.. This is tested with FF 3.0 and IE6
Am I doing something wrong here? | Depending on how the form submission is handled you might also need to remove any click handlers and/or add one that aborts the submission.
```
$('#btnSubmit').unbind('click').click( function() { return false; } );
```
You'd have to add the click handler's again when (if) you re-enable the button. | If it's a *real* form, ie **not javascript event handled**, this should work.
If you're handling the button with an onClick event, you'll find it probably still triggers. If you are doing that, you'll do better just to set a variable in your JS like buttonDisabled and check that var when you handle the onClick event.
Otherwise try
```
$(yourButton).attr("disabled", "true");
```
And if after all of that, you're still getting nowhere, you can manually "break" the button using jquery (this is getting serious now):
```
$(submitButton).click(function(ev) {
ev.stopPropagation();
ev.preventDefault();
});
```
That should stop the button acting like a button. | properly disabling the submit button | [
"",
"javascript",
"jquery",
"html",
""
] |
It seems that there are several really fast prime factorization algorithms around (one that looks ideal is quadratic sieving). However, rather than make my own (likely poor) implementation I would like to use a ready-made library for simplicity.
I need to be able to factor integers of up to 15 digits efficiently. Because of that, I'm not looking for the algorithm that necessarily scales asymptotically best since we can assume the numbers being factored are less than 1015.
I've already had a look at some of the implementations listed on [Wikipedia's Quadratic Sieve page](http://en.wikipedia.org/wiki/Quadratic_sieve#Implementations). However, some of the implementations don't seem well-maintained; some don't have documentation; and so on! I checked if a few well-known libraries, such as Boost, had factorization methods but they don't seem to.
Can anyone recommend a library that fits the above criteria? | Check out [MSIEVE](https://github.com/radii/msieve) library for factoring large integers by Jason Papadopoulos.
> Msieve is the result of my efforts to understand and optimize how
> integers are factored using the most powerful modern algorithms.
>
> This documentation corresponds to version 1.46 of the Msieve library.
> Do not expect to become a factoring expert just by reading it. I've
> included a relatively complete list of references that you can and
> should look up if you want to treat the code as more than a black box
> to solve your factoring problems. | To **factor integers** in C you can try to use a **probabilistic** approach :
The headers of my proposition :
```
#include <stdlib.h>
#include <sys/time.h>
typedef unsigned long long int positive_number; // __uint128_t
static inline positive_number multiplication_modulo(positive_number lhs, positive_number rhs, positive_number mod);
static int is_prime(positive_number n, int k); // prime checker
positive_number factor_worker(positive_number n);
positive_number factor(positive_number n, int timeout);
```
The factorization process **manager**, because there is a timeout:
```
double microtime() {
struct timeval time; gettimeofday(&time, 0);
return (double) time.tv_sec + (double) time.tv_usec / 1e6;
}
// This is the master function you can call, expecting a number and a timeout(s)
positive_number factor(positive_number n, int timeout) {
if (n < 4) return n;
if (n != (n | 1)) return 2;
double begin = microtime();
int steps = 8; // primality check iterations
positive_number a, b;
for (a = n >> 1, b = (a + n / a) >> 1; b < a; a = b, b = (a + n / a) >> 1, ++steps);
if (b * b == n) return b ; // we just computed b = sqrt(n)
if (is_prime(n, steps)) return n;
do { positive_number res = factor_worker(n);
if (res != n) return res;
if (++steps % 96 == 0 && is_prime(n, 32)) return n ; // adjust it
} while (microtime() - begin < timeout);
return n;
}
```
The **multiplier** helper because computations are done modulo N :
```
static inline positive_number multiplication_modulo(positive_number lhs, positive_number rhs, positive_number mod) {
positive_number res = 0; // we avoid overflow in modular multiplication
for (lhs %= mod, rhs%= mod; rhs; (rhs & 1) ? (res = (res + lhs) % mod) : 0, lhs = (lhs << 1) % mod, rhs >>= 1);
return res; // <= (lhs * rhs) % mod
}
```
The **prime checker** helper, of course :
```
static int is_prime(positive_number n, int k) {
positive_number a = 0, b, c, d, e, f, g; int h, i;
if ((n == 1) == (n & 1)) return n == 2;
if (n < 51529) // fast constexpr check for small primes (removable)
return (n & 1) & ((n < 6) * 42 + 0x208A2882) >> n % 30 && (n < 49 || (n % 7 && n % 11 && n % 13 && n % 17 && n % 19 && n % 23 && n % 29 && n % 31 && n % 37 && (n < 1369 || (n % 41 && n % 43 && n % 47 && n % 53 && n % 59 && n % 61 && n % 67 && n % 71 && n % 73 && ( n < 6241 || (n % 79 && n % 83 && n % 89 && n % 97 && n % 101 && n % 103 && n % 107 && n % 109 && n % 113 && ( n < 16129 || (n % 127 && n % 131 && n % 137 && n % 139 && n % 149 && n % 151 && n % 157 && n % 163 && n % 167 && ( n < 29929 || (n % 173 && n % 179 && n % 181 && n % 191 && n % 193 && n % 197 && n % 199 && n % 211 && n % 223))))))))));
for (b = c = n - 1, h = 0; !(b & 1); b >>= 1, ++h);
for (; k--;) {
for (g = 0; g < sizeof(positive_number); ((char*)&a)[g++] = rand()); // random number
do for (d = e = 1 + a % c, f = n; (d %= f) && (f %= d););
while (d > 1 && f > 1);
for (d = f = 1; f <= b; f <<= 1);
for (; f >>= 1; d = multiplication_modulo(d, d, n), f & b && (d = multiplication_modulo(e, d, n)));
if (d == 1) continue;
for (i = h; i-- && d != c; d = multiplication_modulo(d, d, n));
if (d != c) return 0;
}
return 1;
}
```
The factorization **worker**, a single call does not guarantee a success, it's a probabilistic try :
```
positive_number factor_worker(positive_number n) {
size_t a; positive_number b = 0, c, d, e, f;
for (a = 0; a < sizeof(positive_number); ((char*)&b)[a++] = rand()); // pick random polynomial
c = b %= n;
do {
b = multiplication_modulo(b, b, n); if(++b == n) b = 0;
c = multiplication_modulo(c, c, n); if(++c == n) c = 0;
c = multiplication_modulo(c, c, n); if(++c == n) c = 0;
for (d = n, e = b > c ? b - c : c - b; e; f = e, e = multiplication_modulo(d / f, f, n), e = (d - e) % n, d = f);
// handle your precise timeout in the for loop body
} while (d == 1);
return d;
}
```
Example of usage :
```
#include <stdio.h>
positive_number exec(positive_number n) {
positive_number res = factor(n, 2); // 2 seconds
if (res == n) return res + printf("%llu * ", n) * fflush(stdout) ;
return exec(res) * exec(n / res);
}
int main() {
positive_number n = 0, mask = -1, res;
for (int i = 0; i < 1000;) {
int bits = 4 + rand() % 60; // adjust the modulo for tests
for (size_t k = 0; k < sizeof(positive_number); ((char*)&n)[k++] = rand());
// slice a random number with the "bits" variable
n &= mask >> (8 * sizeof (positive_number) - bits); n += 4;
printf("%5d. (%2d bits) %llu = ", ++i, bits, n);
res = exec(n);
if (res != n) return 1;
printf("1\n");
}
}
```
You can put it into a `primes.c` file then compile + execute :
```
gcc -O3 -std=c99 -Wall -pedantic primes.c ; ./a.out ;
```
Also, [128-bit integers GCC extension](https://gcc.gnu.org/onlinedocs/gcc-4.8.1/gcc/_005f_005fint128.html) extension may be available.
Example output :
```
358205873110913227 = 380003149 * 942639223 took 0.01s
195482582293315223 = 242470939 * 806210357 took 0.0021s
107179818338278057 = 139812461 * 766597037 took 0.0023s
44636597321924407 = 182540669 * 244529603 took 0s
747503348409771887 = 865588487 * 863578201 took 0.016s
// 128-bit extension available output :
170141183460469231731687303715506697937 =
13602473 * 230287853 * 54315095311400476747373 took 0.646652s
```
**Info** : This **C99** 100 lines probabilistic factorization software proposition is based on a *Miller–Rabin primality test* followed or not by a *Pollard's rho* algo. Like you, i initially aimed to factorize just a little `long long int`. By my tests it's working fast enough to me, even for some larger. Thank you.
*THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.* | C or C++: Libraries for factoring integers? | [
"",
"c++",
"c",
"algorithm",
"prime-factoring",
""
] |
I know I can hook into the client side events to run JavaScript after every partial postback; however, I want to do something like this:
```
protected void FooClicked(object sender, EventArgs e) {
ClientScript.RegisterStartupScript(GetType(), "msg", "showMsg('Foo clicked');",true);
}
```
I know I could totally hack it with hidden fields and run something after *every* postback, but there should be a pretty straightfoward way to in a similar fashion to this. | The specific code sample you are describing does not work with partial post-backs, since `ClientScript.RegisterStartupScript()` writes JS to the page during the output construction phase of the request lifecycle; whereas a partial postback only updates a selected portion of the page via JavaScript (even though the markup for the entire page, including your startup script, is generated on the server).
To closely mimic what you are describing, you ought to include a Literal control inside your UpdatePanel, and during partial postback set the Text property of the content panel to the script you wish to run:
```
myLiteral.Text = "<script type=\"JavaScript\">doStuff();</script>";
```
IMO, a more proper way is to use the [client-side API for async postbacks](http://msdn.microsoft.com/en-us/library/bb398976.aspx) to register an event handler to run when the postback completes:
```
function endRequestHandler(sender, args) {
doStuff();
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
```
If you need to pass information which was generated during the postback into the handler, you can pass that via hidden fields and grab that from the DOM in your client-side handler. | [This](http://www.coderenaissance.com/2009/02/update-panel-partial-postback-and.html) is much more elegant, IMO. apparently ASP AJAX will call any JS function named pageLoad. so write a function called pageLoad and it will be executed on every page load, even after partial update. | How to control which JavaScript gets run after UpdatePanel partial postback endRequest? | [
"",
"javascript",
"asp.net-ajax",
"updatepanel",
""
] |
In my previous projects, I have already implemented undo system in c++, and I know how it work. I am also aware of the Command pattern.
I will be implementing a C#/WPF desktop application and would like to base my design on the M-V-VM pattern.
The application will:
* be relatively a small project (2-3 weeks estimated work for 1 dev)
* have a simple data model with persistence (linq to XML)
* support undo/redo
I was wondering if anybody has experience with implementing an undo system when following the M-V-VM pattern. How would it fit in it? How can it benefit from the INotifyPropertyChanged and INotifyCollectionChanged notifications so minimal work is required when implementing the Models (business objects).
I would think the undo system would some kind of integrated into the ViewModel layer, as it is a UI state.
Any thought? | Here is the solution I used for my project. The solution proved to be working perfectly.
The system is using undo event objects, where each undo event know how to undo and redo itself.
```
interface IUndoEvent
{
void Undo();
void Redo();
}
```
I was able to build the system by implementing only 2 undo events: One for property changes; one for collection changes.
The idea is that those events implement the Undo/Redo by modifying the model directly.
```
class PropertyChangeUndoEvent : IUndoEvent
{
private ModelBase _target;
private string _propertyName;
private object _oldValue;
private object _newValue;
public PropertyChangeUndoEvent(ModelBase target, string propertyName, object oldValue, object newValue)
{
_target = target;
_propertyName = propertyName;
_oldValue = oldValue;
_newValue = newValue;
}
public void Undo()
{
SetValue(_oldValue);
}
public void Redo()
{
SetValue(_newValue);
}
private void SetValue(object value)
{
// Set Value on the _target using reflection (_propertyName)
}
}
```
The ViewModel take care of creating undo events by calling ViewModelBase functions:
```
class MyViewModel : ViewModelBase
{
public string Name
{
get { return _model.Name; }
// The SetValue will create a undo event, and push it to the UndoManager
set { SetValue(_model, "Name", value); }
}
}
```
Finally, there is a UndoManager (project singleton) that stores the undo stack and the redo stack. | You may find the Monitored Undo Framework to be useful. <http://muf.codeplex.com/>. It doesn't use the "top down" command pattern, but instead monitors for changes as they happen and allows you to put a delegate on the undo stack that will reverse the change.
I created this as part of a WPF application that was built using MVVM. Most of the undo actions originated in our underlying domain model, but we also hooked into some areas of the ViewModels to allow undo / redo there too.
You can find more info and documentation on the codeplex site at <http://muf.codeplex.com/>. | Undo inside WPF M-V-VM, how does it fit? | [
"",
"c#",
"wpf",
"mvvm",
"undo",
""
] |
Having just pulled my hair off because of a difference, I'd like to know what the difference *really* is in Python 2.5.
I had two blocks of code (`dbao.getConnection()` returns a MySQLdb connection).
```
conn = dbao.getConnection()
with conn:
# Do stuff
```
And
```
with dbao.getConnection() as conn:
# Do stuff
```
I thought these would have the same effect but apparently not as the `conn` object of the latter version was a `Cursor`. Where did the cursor come from and *is* there a way to combine the variable initialization and with statement somehow? | In general terms, the value assigned by the `as` part of a `with` statement is going to be whatever gets returned by the [`__enter__` method of the context manager](http://docs.python.org/library/stdtypes.html#contextmanager.__enter__). | It may be a little confusing at first glance, but
```
with babby() as b:
...
```
is *not* equivalent to
```
b = babby()
with b:
...
```
To see why, here's how the context manager would be implemented:
```
class babby(object):
def __enter__(self):
return 'frigth'
def __exit__(self, type, value, tb):
pass
```
In the first case, the name `b` will be bound to whatever is returned from the `__enter__` method of the context manager. This is often the context manager itself (for example for file objects), but it doesn't have to be; in this case it's the string `'frigth'`, and in your case it's the database cursor.
In the second case, `b` is the context manager object itself. | Python's 'with' statement versus 'with .. as' | [
"",
"python",
"syntax",
""
] |
EDIT: OK, I believe the following solutions are valid:
1. Use the jQuery AOP plugin. It basically wraps the old function together with the hook into a function sandwich and reassigns it to the old function name. This causes nesting of functions with each new added hook.
If jQuery is not usable for you, just pillage the source code, there did not seem to be any jQuery dependencies in the plugin, and the source is simple and very small.
2. Have an object describing all hooks and their targets and one to store the initial unmodified function. When adding a new hook, the wrapping would be redone around the original function, instead of re-wrap the the previous wrapping function.
You escape nested functions, and get two objects to handle instead. Potentially, this could also mean easier hook handling, if you add/remove hooks often and out of order.
I'll go with the first, since it's already done, and I don't have performance to worry about. And since the original functions are not affected, even if I switch hooking methods, I'll only need to redo the hook adding, which might be just some simple search&replace operations.
---
Hi,
Is it possible to create a mechanism, in which function A might have a set of hooks(functions that will execute before/after function A)?
Ideally, function A would not be aware of hooking functionality, so that I do not have to modify the source code of function A to call the hooks. Something like:
```
A = function(){
alert("I'm a naive function");
};
B = function(){
alert("I'm having a piggyback ride on function A!"+
"And the fool doesn't even know it!");
};
addHook(B, A)//add hook B to function A
A()
//getting alerts "I'm a naive function"/"I'm having a
//piggyback ride on function A! And the fool doesn't even know it!"
```
I've been trying to hack something up for a couple of hours, but so far no luck. | Take a look at [jQuery's AOP plugin](http://plugins.jquery.com/project/AOP). In general, google "javascript aspect oriented programming". | Might not be pretty but it seems to work...
```
<script>
function A(x) { alert(x); return x; }
function B() { alert(123); }
function addHook(functionB, functionA, parent)
{
if (typeof parent == 'undefined')
parent = window;
for (var i in parent)
{
if (parent[i] === functionA)
{
parent[i] = function()
{
functionB();
return functionA.apply(this, arguments)
}
break;
}
}
}
addHook(B, A);
A(2);
</script>
``` | Javascript function hooks | [
"",
"javascript",
"aop",
"hook",
""
] |
I have a bean which I map to the database using Hibernate. I'm using Hibernate Annotations to indicate the mapping I want, and to create the indices. The thoroughly simplified code is shown below.
The problem I have is that the indices on my byte[] field are not created; specifically that my multi-field index sysUuid does not get created (see example code). In the Hibernate debug logs I do not even see an attempt to create an index!
I'd like to point out that an @Index annotation on the uuid field also does not result in an index on the database.
I do know how to create an index by hand using MySQL:
```
create index sysuuid on persons ( system, `uuid`(8) );
```
where the interesting features are that uuid needs to be escaped (as it is a MySQL function) and that a length needs to be given on the field (as with text fields).
I however have not found a way to give the index length field using Hibernate Annotations so I cannot test wether that is the problem. It is however certain that naming the field "uuid(8)" in the annotation does not work.
```
@Entity
// The UniqueConstraints work
@Table(name = "persons",
uniqueConstraints = {@UniqueConstraint(columnNames = {"uid", "system"}) } )
// but these don't generate an index
@org.hibernate.annotations.Table(appliesTo="persons",
indexes={@Index(name="sysUuid", columnNames={"system", "uuid"}) } )
public class Person {
@Basic
@NotNull
private String uid;
@Basic
private int system;
// Gets mapped to tinyblob
@Basic
@Size(min = 16, max = 16)
private byte[] uuid;
// getters and setters here
}
```
What I'd like to ask you is: Is it possible to add an index on a lob using an annotation, and if so, how?
**EDIT**
It is indeed possible for me to move to a String-based UUID, but I'm not really comfortable with that as uuid is conceptually a 16-byte identifier.
I strongly prefer the Java types to match the problem domain.
And as I said - I do have an SQL statement handy so I can deploy the code + a SQL script. I just think it's better do have self-documenting code whenever feasible.
**EDIT & Added Bounty**
I believe the index I need cannot be created using Hibernate Annotations (re. Matt Solnit's answer).
I however would appreciate a bit more information about creating indices with Hibernate Annotations in general so the eventual answer ends up documenting the limitations of the
API. | You could do this using Hibernate's [auxiliary objects](http://docs.jboss.org/hibernate/stable/core/reference/en/html/mapping-database-object.html) support, but it cannot be done using annotations :-(.
In your example, it would look something like this (lots of stuff omitted for brevity):
```
<class name="Person" table="persons">
<!-- whatever -->
<database-object>
<create>create index sysuuid on persons ( system, `uuid`(8) )</create>
<drop>drop index sysuuid</drop>
<dialect-scope name="org.hibernate.dialect.MySQL5InnoDBDialect" />
</database-object>
</class>
```
I apologize for the lack of an annotation-based answer :-(. Hopefully this helps.
**NOTE**: If you do take this approach, be aware that the dialect scope has to match *exactly*. For example, if your Hibernate configuration says to use `MySQL5InnoDBDialect`, then you must have this dialect in the `<dialect-scope>` element as well. Using `MySQLDialect` will not work even though it is the super-class of the InnoDB dialect. | What you really want to do is to define your UUID property as a String rather than a byte array. That way Hibernate will map it to a character column in the database rather than a LOB, and I think it'll create the index you want. | How to use Hibernate Annotations to add an index on a Lob / Clob / tinyblob | [
"",
"java",
"mysql",
"hibernate",
""
] |
I am looking at modifying a jQuery Plugin to cater for an additional requirement I need.
Sorry, not a programming question, but can you pass an array from javascript into a jQuery plugin, that will maintain all it's information or do I lose the array content between javascript and jQuery Plugin?
Thanks.
TT. | jQuery is written entirely in javascript. jQuery extensions (and indeed jQuery itself) are just normal functions. There's nothing special nor different about it, so to answer your question, yes you can pass arrays. | Here's an example plugin that has an array as an argument.
```
// plugin definition
$.fn.myPlugin = function(arrArg) {
// the plugin implementation code goes here
// do something with arrArg, which is an array
};
```
Then to call the plugin with an array:
```
$('.class').myPlugin([1, 2, 3]);
``` | Passing Arrays into a jQuery PlugIn | [
"",
"javascript",
"jquery",
"plugins",
""
] |
**Casus:**
*How to edit and advance with the same code, from several distanced locations and computers as easily as possible?*
I have this thought for some time now. I am regularly having problems when I have to work on one project from different computers, as I have not taken any measures or whatsoever to ease myself in this situation. That is partially due to the fact that I rarely do freelance projects and they are normally small web sites.
Imagine that you need to work on a project at home, where you have setup database, webserver, phpmyadmin and everything you'll need to get your app running. Then you go to your girlfriend's house for the weekend but you need to advance with the project and during that time you want to do some coding.
What I am currently doing is that I am archiving my whole project, along with a DB dump usually and place it on a ftp host, so that I may access it later when I need it. I probably don't have to explain how tedious this might be, especially if you need to setup the whole environment on the PC you are currently being at.
**Considerations:**
* Turn my home PC into a dev server with Remote Desktop enabled - the problem with this is that remote connection is not always fast and snippy as one would need it to be in order to do RAD. Also that implies the PC must be always be turned on at home, regardless that I might not even need it, If say, there are better things to do during the weekend. I might need to buy an UPS, as power outages happen from time to time around here.. I already don't like this solution.
* Create database and SVN repositories at public hosting service and checkout code. This still has some of the problems, as you might need to install software, SVN client and eventually edit some configuration each time you change the computer. Oh, and as with the previous 'solution' - you are totally dependent on Internet access.
* Buy an Eee PC and carry it around - that way you can have all of your environment with you. No network required as well. You have to drag the darn thing around tho, and even it is small, it is not something you might fit in your pocket. I also consider that these EEE PC's aren't very suitable for normal coding (small keyboard, screen, etc).
* And finally, I have been thinking of an ideal scenario, where I have one of those linux distributions which go along a single CD or even a [**flashdrive**](http://www.pendrivelinux.com/). On the latest you can have all your environment always with you along with all the projects. You can fit it in your pocket. Nova days all computers have built-in USB ports, contrary not every computer has a CD ROM in place.
Thinking about it, I consider the last solution to be optimal and completely satisfying. Problem is, I am not very linux savvy and I haven't been messing with it so much. Especially with flashdrive OS.
**Bottom line questions**:
1. Do you agree that a flashdrive is an optimal solution? Is there a better practice I can put into work? Perhaps I should reconsider this way of working at all?:)
2. Do you think a flashdrive OS as say <http://www.pendrivelinux.com/> is suitable for such web development environment at all; Are there better candidates for an OS?
3. Are there any problems with booting from USB generally? Naturally I guess this shouldn't be a problem on most PC's?
4. What is your personal experience in working from several locations on the same project? | Here's an alternate solution: carry a portable hard drive that has a portable installation of a virtual machine player and a virtual machine with all the dev tools you need. Just plug this into whatever computers are available, fire up the VM, put it in fullscreen mode and you're good to go. Carries the advantage of not having to mess with live-cd or live-usb Linux setup, especially since you stated you're not very familiar with Linux.
EDIT: you could also run your VM off a flash drive, though performance would be abysmal. | You really should just get a laptop and do all your coding on that machine. Messing around with netbooks and/or thumbdrives is not a long-term solution. I have a MacBook that I use to do all my coding. When I'm home, it's attached to a 21-inch monitor and a full keyboard and mouse. When I need to travel I unplug all the cords and put it in my bag. Since I use the same machine, I don't have to worry about migrating files or settings back and forth, and while the screen is somewhat small, it's not bad to get a bit of work done on the go.
If I couldn't carry my laptop around, I'd set up a development environment on a Linux server. However, this solution is highly dependent on the type of development you're doing and how familiar you are with Linux and the command line. I definitely don't recommend it for those that are starting out. However, with Screen and Emacs (or vim if you swing that way) you can have a fully-fledged development environment anywhere with internet access. | The ideal "always/anywhere available" web development environment? | [
"",
"php",
"development-environment",
"usb-drive",
""
] |
I'm writing a program in C++ and for some reason I'm getting a segmentation error at the following line:
```
char* param= new char[200];
```
I've tried different variations and even tried putting before it
```
int* param= new int;//for no reason
```
and the same error occurs. What might I have done to cause this problem?
What could possibly cause a simple memory allocation like this to give problems.
I would include the rest of the program, but it's over 1000 lines. But feel free to ask for more info. | I'd say Neil's on the right track - it's probably something you trampled earlier on that's only being caught there.
Have you made sure that:
1. All previous allocations succeeded.
2. You've not written past the end or beginnings of any arrays (there's [a plethora of information and tools for bounds checking](http://www.google.co.uk/search?q=C%2B%2B+bounds+checking&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-GB:official&client=firefox-a) out there).
**[Edit]** In response to your comment about having 4GB of RAM, suppose you code effectively does the following:
```
unsigned int amountToAllocate = 0;
amountToAllocate -= 1;
int* someStorage = new int[amountToAllocate];
someStorage[0] = 5;
```
...because `amountToAllocate` is an `unsigned int`, it will wrap round to it's maximum value (4294967295 if `unsigned int`s are 32 bit on your hardware). So you'd be trying to allocate 4294967295\*4 bytes (again, assuming `int`s are 32 bit for you)... which is ~4\*4GB and will fail and die a nasty death. | Do you do any memory allocating & freeing before this point? If so, you have probably corrupted the heap in some way. Impossible to diagnose further without seeing more code. | what could be wrong with: char* param= new char[200]; | [
"",
"c++",
"new-operator",
""
] |
I was wondering if PHP can do this as there seems to be no good solution to it yet:
```
p($i)
```
and it will print
```
$i is 5
```
and
```
p(1 + 2)
```
will print
```
1 + 2 is 3
```
and
```
p($i * 2) => $i * 2 is 10
p(3 * factorial(3)) => 3 * factorial(3) is 18
```
C and Ruby both can do it... in C, it can be done by stringification, and in Ruby, there is a solution using `p{'i'}` or `p{'1 + 2'}` (by passing the block with the binding over, to do an eval)... I wonder in PHP, is it possible too? | I think it could be done by taking a backtrace then loading and tokenizing the file that calls `p()`. I wouldn't call it a "good" solution though.
Of course you could stringify it yourself...
```
p('$i');
function p($str)
{
echo $str, " = ", eval("return ($str);");
}
``` | If you mess with the string to make it into a return statement, you can use [eval](http://php.net/eval)...
```
function p($expr)
{
$php="return {$expr};";
echo "$expr is ".eval($php)."\n";
}
p("1+2");
```
Works for simple expressions, but if you tried to reference a variable in your $expr, then it wont find it inside the scope of function p() - a little hack like the following can help:
```
function p($expr)
{
$php="return {$expr};";
$php=preg_replace('/\\$(\w+)/', '$GLOBALS[\'$1\']', $php);
echo "$expr is ".eval($php)."\n";
}
$x=5;
p('$x+4');
```
Here we've search for variable references in the code and turned them into $GLOBALS array references. The expression `$x+4` is turned into `return $GLOBALS['x']+4;`
Not sure I'd ever want to see this in production code though :) | can PHP do something like p($i) and it prints "$i is 5" -- C and Ruby can... (that is, to print out "$i" automatically) | [
"",
"php",
"c",
"ruby",
"debugging",
"printing",
""
] |
I am looking to figure out what my IP address is from a console application.
I am used to a web application by using the `Request.ServerVariables` collection and/or `Request.UserHostAddress`.
How can this be done in a console app? | The easiest way to do this is as follows:
```
using System;
using System.Net;
namespace ConsoleTest
{
class Program
{
static void Main()
{
String strHostName = string.Empty;
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
}
}
}
``` | Try this:
```
String strHostName = Dns.GetHostName();
Console.WriteLine("Host Name: " + strHostName);
// Find host by name IPHostEntry
iphostentry = Dns.GetHostByName(strHostName);
// Enumerate IP addresses
int nIP = 0;
foreach(IPAddress ipaddress in iphostentry.AddressList) {
Console.WriteLine("IP #" + ++nIP + ": " + ipaddress.ToString());
}
``` | Get IP address in a console application | [
"",
"c#",
"console-application",
""
] |
I find my self hard to design action enums for events.
f.ex making calculation processor.
so I should have enum like this ? :
```
public enum CalculatorCoreActions
{
ProcessStarted,
ProcessFinished,
ProcessFailure,
ProcessFailed,
SubstractionStarded,
SubstractionFinished,
SubstractionFailure,
SubstractionFailed,
<etc.>...
}
```
Or I should make two enums ?, f.ex:
```
public enum CalculatorAction
{
Process,
Substraction,
Division
}
public enum CalculationActionResult
{
Started,
Finished,
Failure,
Failed
}
```
Or even I should create an new classes ? :
```
public class CalculatorActionEventArgs : EventArgs {<...>}
public class CalculatorActionFailedEventArgs : EventArgs {<...>}
public class etc... : EventArgs {<...>}
```
Which method is the best in your opinion? | What are you trying to do? What are you going to use the enums for? Your first example may be OK for very few combinations, whereas the second will be more complex but much cleaner and easier to extend.
My guess is that you want to be able to display the state of calculation, and perhaps act on the state in e.g. error handling. You might consider the [State](http://cnx.org/content/m17257/latest/) or [State Machine](http://dotnet.zcu.cz/NET_2006/Papers_2006/short/B31-full.pdf) patterns rather than enums, in order to avoid huge switch statements on your enums. | Of the two choices for enumerations that you presented I would go with the second set of enumerations.
Why, well when you cross (literaly multiply) the states with the actions you come up with a large growth pattern. When you want to add either a state or a feature in the future you no longer add one item but 1xM or Nx1 items. For other references to this style of problem see **Martin Fowler's** book **Refactoring** and object hierachy entanglement.
Now for the event args, use the generic EventArgs and give it the action and state in an object. Don't create more things than you have to and it will minimize the number of headaches you create. | Best-Practices: action enum usage for events | [
"",
"c#",
".net",
"events",
""
] |
The two functions in openCV cvLoadImage and cvSaveImage accept file path's as arguments.
For example, when saving a image it's **cvSaveImage("/tmp/output.jpg", dstIpl)** and it writes on the disk.
Is there any way to feed this a buffer already in memory? So instead of a disk write, the output image will be in memory.
I would also like to know this for both cvSaveImage and cvLoadImage (read and write to memory buffers). Thanks!
---
My goal is to store the Encoded (jpeg) version of the file in Memory. Same goes to cvLoadImage, I want to load a jpeg that's in memory in to the IplImage format. | There are a couple of undocumented functions in the SVN version of the libary:
```
CV_IMPL CvMat* cvEncodeImage( const char* ext,
const CvArr* arr, const int* _params )
CV_IMPL IplImage* cvDecodeImage( const CvMat* _buf, int iscolor )
```
Latest check in message states that they are for native encoding/decoding for bmp, png, ppm and tiff (encoding only).
Alternatively you could use a standard image encoding library (e.g. libjpeg) and manipulate the data in the IplImage to match the input structure of the encoding library. | This worked for me
```
// decode jpg (or other image from a pointer)
// imageBuf contains the jpg image
cv::Mat imgbuf = cv::Mat(480, 640, CV_8U, imageBuf);
cv::Mat imgMat = cv::imdecode(imgbuf, CV_LOAD_IMAGE_COLOR);
// imgMat is the decoded image
// encode image into jpg
cv::vector<uchar> buf;
cv::imencode(".jpg", imgMat, buf, std::vector<int>() );
// encoded image is now in buf (a vector)
imageBuf = (unsigned char *) realloc(imageBuf, buf.size());
memcpy(imageBuf, &buf[0], buf.size());
// size of imageBuf is buf.size();
```
I was asked about a C version instead of C++:
```
#include <opencv/cv.h>
#include <opencv/highgui.h>
int
main(int argc, char **argv)
{
char *cvwin = "camimg";
cvNamedWindow(cvwin, CV_WINDOW_AUTOSIZE);
// setup code, initialization, etc ...
[ ... ]
while (1) {
// getImage was my routine for getting a jpeg from a camera
char *img = getImage(fp);
CvMat mat;
// substitute 640/480 with your image width, height
cvInitMatHeader(&mat, 640, 480, CV_8UC3, img, 0);
IplImage *cvImg = cvDecodeImage(&mat, CV_LOAD_IMAGE_COLOR);
cvShowImage(cvwin, cvImg);
cvReleaseImage(&cvImg);
if (27 == cvWaitKey(1)) // exit when user hits 'ESC' key
break;
}
cvDestroyWindow(cvwin);
}
``` | OpenCV to use in memory buffers or file pointers | [
"",
"c++",
"memory",
"opencv",
""
] |
I am new to php and I am getting this error trying to load a cert
```
jameys-macbookpro41:~ user$ php -f ~/Sites/providerService.php
```
Warning: stream\_socket\_client(): Unable to set local cert chain file `cert.pem'; Check that your cafile/capath settings include details of your certificate and its issuer in /Users/jamey/Sites/providerService.php on line 27
cert.pem is in the same folder as the php file. the file cert.pem was created in the Apple keychain tool
```
class pushNotifications {
...
private $sslPem = 'cert.pem';
...
function connectToAPNS(){
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl',
'local_cert', $this->sslPem);
```
Thanks for any help! | You are getting an error because it's trying to find your cert.pem file in the directory you are running the script from, not the directory the script is in. In your example, it is your user directory "~".
Try changing your class to this, or something similar:
```
class pushNotifications {
...
private $sslPem = 'cert.pem';
...
function connectToAPNS(){
$streamContext = stream_context_create();
stream_context_set_option($streamContext, 'ssl', 'local_cert', dirname(__FILE__) . '/' . $this->sslPem);
``` | I was having this issue as well, it turns out that for some reason my private key didn't match the one associated with the aps\_developer\_identity.cer I had...
I ended up clearing *all* of my public and private keys from my 'login' keychain item, then I started the entire process over again (Generated the request)...I submitted the new request file on the program portal and generated a new certificate, downloaded, and installed it by double-clicking it (developer\_identity.cer). Then, I reset the provisioning profiles to use the new Push SSL certs, downloaded those, and installed them by double-clicking (aps\_developer\_identity.cer). Finally, I reset the provisioning profile and downloaded the new one. I cleared out the old one in the Xcode Organizer, and installed the new one. Finally, I exported my 'private' key as key.p12 and my aps\_developer\_identity.cer as apsdi.p12, and ran the following commands against them:
```
openssl pkcs12 -clcerts -nokeys -out apsdi.pem -in apsdi.p12
openssl pkcs12 -nocerts -out key.pem -in key.p12
```
If you're okay using a passphrase (recommended for production):
```
cat apsdi.pem key.pem > cert.pem
```
If you wish to use a 'blank' passphrase, you'll need to unencrypt your private key first, *using the password you specified when you converted it to pem format*:
```
openssl rsa -in key.pem -out key.unencrypted.pem
```
And then cat the cert and unencrypted key into apns.pem (or whatever filename you have chosen):
```
cat apsdi.pem key.unencrypted.pem > apns.pem
```
It's very important that you export your aps\_developer\_identity certificate, *not* your developer\_identity certificate as apsdi.pem.
*If you can expand your developer\_identity.cer and aps\_developer\_identity.cer entries in Keychain Access, and you see a 'private' key when you do, everything should work.* | Error using ssl cert with PHP | [
"",
"php",
"sockets",
"ssl",
""
] |
Is there any way to return an array from a function? More specifically, I've created this function:
```
char bin[8];
for(int i = 7; i >= 0; i--)
{
int ascii='a';
if(2^i-ascii >= 0)
{
bin[i]='1';
ascii=2^i-ascii;
}
else
{
bin[i]='0';
}
}
```
and I need a way to return `bin[]`. | Your array is a local variable allocated on the stack. You should use `new []` to allocate it on the heap. Then you can just say: `return bin;`. Beware that you will have to explicitly free it with `delete []` when you are done with it. | You can't do that but you can:
* return a dynamicaly allocated array - best owned by a smart pointer so that the caller does not have to care about deallocating memory for it - you could also return something like an std::vector this way.
* populate an array/vector passed to you as an argument by pointer (suggested) or a non const reference. | How can I return an array? | [
"",
"c++",
"arrays",
"return-value",
""
] |
I have an ASP.NET user control (.ascx file). In this user control I want to use a .js file.
So I include `<script src="file.js" type"text/javascript"></script>` on the page.
However, sometimes I use this user control in a webpage where this same script has already been loaded.
How can I add a `<script />` declaration that will render on the page only if the page doesn't already contain another `<script />` tag for the same script? | As you are using asp.net, it makes sense to do the check server-side as that will be where you choose to add the reference to the javascript file. From your .ascx file you could register with the following:
```
this.Page.ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
```
... from your page you just call the ClientScript object directly:
```
ClientScript.RegisterClientScriptInclude("GlobalUnqiueKey", UrlOfJavascriptFile);
```
The 'GlobalUniqueKey' can be any string (I use the url of the javascript file for this too)
If you try to register a script with the same key string, it doesn't do anything. So if you call this in your page, your control or anywhere else, you'll end up with only one reference in your page. The benefit of this is that you can have multiple instances of a control on a page and even though they all try to register the same script, it is only ever done a maximum of one time. And none of them need to worry about the script being already registered.
There is a 'IsClientScriptIncludeRegistered(stringkey)' method which you can use to see if a script has already been included under that key but it seems pretty redundant to do that check before registering as multiple attempts to register do not throw exceptions or cause any other errors.
Doing the check client-side means that, assuming the multiple javascript references are cached by the browser (they may not be), you still have multiple tags and the over head of each one causing some javascript to run. If you had 20 instances of your control on a page, you could get serious issues. | You can do one of two things client side...
1. Check the dom for the script tag corresponding to the javascript file your want to check
2. Test a variable or function you know has/will be defined within the javascript file for undefined.
Here's a quick JS function which uses JQuery to do what you need:
```
function requireOnce(url) {
if (!$("script[src='" + url + "']").length) {
$('head').append("<script type='text/javascript' src='" + url + "'></script>");
}
}
``` | How can I tell whether a JavaScript file has already been included in an ASP.NET page? | [
"",
"asp.net",
"javascript",
"html",
"script-tag",
""
] |
I'm using fstream. Is there any way to get the failure message/exception?
For example if I'm unable to open the file? | From checking it out I found that also `errno` and also `GetLastError()` do set the last error and checking them is quite helpful. For getting the string message use:
```
strerror(errno);
``` | Streams by default do not throw exceptions on error, they set flags. You can make them throw exceptions by using the stream's exception() member function:
```
ifstream ifs;
ifs.exceptions( std::ios::failbit ); // throw if failbit get set
```
Theoretically, you could then do something like this:
```
try {
int x;
ifs >> x;
}
catch( const std::exception & ex ) {
std::cerr << "Could not convert to int - reason is "
<< ex.what();
}
```
Unfortunately, the C++ Standard does not specify that thrown exceptions contain any error message, so you are in implementation specific territory here. | Get std::fstream failure error messages and/or exceptions | [
"",
"c++",
""
] |
When should I use `std::string` and when should I use `char*` to manage arrays of `char`s in C++?
It seems you should use `char*` if performance(speed) is crucial and you're willing to accept some of a risky business because of the memory management.
Are there other scenarios to consider? | You can pass `std::string`s by reference if they are large to avoid copying, or a pointer to the instance, so I don't see any real advantage using `char` pointers.
I use `std::string`/`wstring` for more or less everything that is actual text. `char *` is useful for other types of data though and you can be sure it gets deallocated like it should. Otherwise `std::vector<char>` is the way to go.
There are probably exceptions to all of this. | My point of view is:
* Never use char \* if you don't call "C" code.
* Always use std::string: It's easier, it's more friendly, it's optimized, it's standard, it will prevent you from having bugs, it's been checked and proven to work. | char* vs std::string in c++ | [
"",
"c++",
"stl",
"stdstring",
"arrays",
""
] |
I'm building a search function for a php website using Zend Lucene and i'm having a problem.
My web site is a Shop Director (something like that).
For example i have a shop named "FooBar" but my visitors seach for "Foo Bar" and get zero results. Also if a shop is named "Foo Bar" and visitor seaches "FooBar" nothing is found.
I tried to seach for " foobar~ " (fuzzy seach) but did not found articles named "Foo Bar"
Is there a speciar way to build the index or to make the query? | Option 1: Break the input query string in two parts at various points and search them. eg. In this case query would be (+fo +bar) OR (+foo +bar) OR (+foob +ar) The problem is this tokenization assumes there are two tokens in input query string. Also, you may get extra, possibly irrelevant, results such as results of (+foob +ar)
Option 2: Use n-gram tokenization while indexing and querying. While indexing the tokens for "foo bar" would be fo, oo, ba, ar. While searching with foobar, tokens would be fo, oo, ob, ba, ar. Searching with OR as operator will give you the documents with maximum n-gram matches at the top. This can achieved with [NGramTokenizer](http://lucene.apache.org/java/2_4_1/api/contrib-analyzers/org/apache/lucene/analysis/ngram/NGramTokenizer.html) | Manually add index entries for most common name confusions. Get your customers to type them in on a special form. | How to find "FooBar" when seaching "Foo Bar" in Zend Lucene | [
"",
"php",
"zend-framework",
"lucene",
"zend-search-lucene",
"fuzzy-search",
""
] |
the question's in the title really.
I have an online form where, after a series of stages, the user is sent off to a payment gateway on another server, then back again after completing their details there (no card or personal info is sent, just encrypted tokens, that's the point).
So can I rely on the session data still being available when they are sent back (via POST?), and also *should* I do so?
My testing would seem to indicate yes, but this is the first time I've tried to do anything like this. The alternative is to save form progress before the redirect & then reinstate it when they return. Would that be better & why if so?
TIA :) | It depends on the timeout of the session and whether or not the apache crashes/restarts. If you need a failsafe way then persist the session info back into a database. | Yes, you can generally rely on this working.
Your session will still time out in the normal way, so as long as you expect your customer to spend less time in the third party site than it takes for the session to time out, you should be fine.
I do exactly what you are suggesting with some sites I maintain, and there are no serious problems. I guess it might be more complicated if a large percentage of your customers are expected to have cookies disabled, but if you are dealing with the public, this is really not an issue.
However, most payment gateways let you pass them additional information that they will send on to you when they return the customer to your site. Even if they don't have a built in way of doing this, you add GET params to the URL they use to return the customer to you. It is well worth adding an ID or order number here, so you can do something even if the session has died.
NOTE: Some payment services don't actually return the customer to your site at the end of the transaction, but instead just make a call to your server to let you know that a particular payment completed. In this situation your session will be not intact, as it is not the customer making the request from your web server. | Can I rely on session availability after redirect to & from another server? | [
"",
"php",
"security",
"apache",
"session",
""
] |
In the bug fixing of a small ASP.NET/C# web app I have made, I have encountered an OutOfMemoryException.
There is no tips as to where to look as this is a compile time error. How can I diagnose this exception? I am assuming this is exactly where memory profiling comes into play? Any tips?
Thanks | You should take a memory dump of your program at the point in time OutOfMemoryException occurs and analyze what's taking up so much memory.
Tess Ferrandez has an [excellent How-To series](http://blogs.msdn.com/tess/archive/2008/02/15/net-debugging-demos-lab-3-memory.aspx) on her blog. | Sorry above, but to me it has happened more than 3 times - Redgate broke either VS or the whole Windows ...
Try this [approach](http://support.microsoft.com/kb/306355).
I quess the root cause for your problem is weak debugging , check [log4net](http://logging.apache.org/log4net/download.html).
Also simple
if ( DebuggingFlag == true )
Response.Write ( "DebugMsg" )
might be useful as simple and absurd it sounds ... | Debugging outofmemoryexception | [
"",
"c#",
".net",
"asp.net",
"debugging",
""
] |
I was debugging a stored procedure the other day and found some logic something like this:
```
SELECT something
FROM someTable
WHERE idcode <> (SELECT ids FROM tmpIdTable)
```
This returned nothing. I thought it looked a little odd with the "<>" so I changed it to "NOT IN" and then everything worked fine. I was wondering why this is? This is a pretty old proc and I am not really sure how long the issue has been around, but we recently switched from SQL Server 2005 to SQL Server 2008 when this was discovered. What is the real difference between "<>" and "NOT IN" and has the behavior changed between Server2005 and 2008? | ```
SELECT something
FROM someTable
WHERE idcode NOT IN (SELECT ids FROM tmpIdTable)
```
checks against any value in the list.
However, the NOT IN is not NULL-tolerant. If the sub-query returned a set of values that contained NULL, no records would be returned at all. (This is because internally the NOT IN is optimized to `idcode <> 'foo' AND idcode <> 'bar' AND idcode <> NULL` etc., which will always fail because any comparison to NULL yields UNKNOWN, preventing the whole expression from ever becoming TRUE.)
A nicer, NULL-tolerant variant would be this:
```
SELECT something
FROM someTable
WHERE NOT EXISTS (SELECT ids FROM tmpIdTable WHERE ids = someTable.idcode)
```
---
EDIT: I initially assumed that this:
```
SELECT something
FROM someTable
WHERE idcode <> (SELECT ids FROM tmpIdTable)
```
would check against the first value only. It turns out that this assumption is wrong at least for SQL Server, where it actually triggers his error:
```
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
``` | try this, may run faster because of index usage:
```
SELECT something
FROM someTable
LEFT OUTER JOIN tmpIdTable ON idcode=ids
WHERE ids IS NULL
``` | "<>" vs "NOT IN" | [
"",
"sql",
"sql-server",
"sql-server-2005",
"sql-server-2008",
""
] |
The aim is to be able to switch debugging calls on at run-time from database on a production build ... | No; the point of conditional methods and preprocessor directives is that they cause the compiler to omit code from the final executable. The runtime equivalent of these is an `if` statement.
However, [aspect-orientated programming](http://www.google.co.uk/search?q=.NET+AOP&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a) is roughly equivalent to what you're asking, in that it allows you to inject code into a running program that wouldn't otherwise be there.
**Edit:** as Joe mentioned, the way to do this is to program against a logging framework like log4net that allows fine-grained control over what gets logged. | Not at the pre-processor level. After all, you're running the result of that process. Of course, you could change your pre-processor checks to be normal code checks, which can obviously be switched as required. | Is there a way to assign conditional methods or add preprosessor directives at run-time in C#? | [
"",
"c#",
"debugging",
"runtime",
"c-preprocessor",
""
] |
Any astronomers out there? I'm wondering if anyone has produced or stumbled upon a .NET (preferably C#) implementation of the [US Naval Observatoru Vector Astrometry Subroutines (NOVAS)](http://aa.usno.navy.mil/software/novas/novas_info.php). | I know nothing (of consequence) about astronomy, and absolutely nothing about NOVAS, so please take this with a grain of salt.
But, I did look at the website, and it looks like they have a C implementation. You could always take the C implementation, access it via pinvoke, and write a C# wrapper around it. | Are you only interested in a port of that library or anything usable from C# for astronomy?
I don't have anything for the first part, but for the second I would take a look at AGI's [Components](http://www.agi.com/products/components/). Their libraries provide ways to compute all kind of astronomical data. The [Dynamic Geometry Library](http://www.agi.com/products/components/main.cfm?tab=overview) lets you model everything including planets and such rather easily. | NOVAS for .NET | [
"",
"c#",
"astronomy",
""
] |
I want to write a JAR file that makes use of the javax servlet API. If I write against version 2.2, does that mean it will work on versions 2.3, 2.4 and 2.5?
Thanks | Yes, they are backwards compatible.
[Oracle Source](http://docs.oracle.com/cd/E19798-01/821-1752/beagj/index.html) | In most cases, there shouldn't be any compatibility issues. There may be a couple of gotchas, depending on what you are doing. If you are writing some framework that decorates container classes, the interfaces have occasionally been modified. For example, the method [ServletRequest.getRemotePort()](http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getRemotePort()) was not present in the [J2EE 1.3 version](http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/ServletRequest.html) (before Servlet 2.4). These difficulties can be overcome, but be aware that you're going to have to factor them into your development and testing. | Are the Java Servlet APIs backwards compatible? | [
"",
"java",
"servlets",
""
] |
\*\*\*\*Update:\*\*
**using the Rank() over partition syntax available in MS SQL Server 2005 does indeed point me in the right direction, it (or maybe I should write "I") is unable to give me the results I need without resorting to enumerating rows in code.**
**For example, if we select TOP (1) of rank, I get only one value, ie., slot 1. If I use MAX(), then I get the top ranked value for each slot...which, in my case, doesn't work, because if slot 2's top value is NULL, but it's next to MAX value is non-empty, that is the one I want.**
**So, unable to find a completely T-SQL solution, I've resorted to filtering as much as possible in SQL and then enumerating the results in code on the client side.**
Original:
I've been hitting [advanced T-SQL books](https://rads.stackoverflow.com/amzn/click/com/0964981203), StackOverflow and google trying to figure out how to handle this query either by using pivots or by using analytic functions. So far, I haven't hit on the right combination.
I have schedules that are ranked (higher value, greater precedence). Each schedule has a playlist of a certain number of numbered slots with files.
What I need to do, is line up all the schedules and their associated playlists, and for each slot, grab the file from the schedule having the highest ranking value.
so, if I had a query for a specific customer with a join between the playlists and the schedules, ordered by Schedule.Rank DESC like so:
```
PlaylistId Schedule.Rank SlotNumber FileId
100 100 1 1001
100 100 2 NULL
100 100 3 NULL
200 80 1 1101
200 80 2 NULL
200 80 3 NULL
300 60 1 1201
300 60 2 NULL
300 60 3 2202
400 20 1 1301
400 20 2 2301
400 20 3 NULL
```
From this, I need to find the FileId for the MAX ranked row per slotnumber:
```
SlotNumber FileId Schedule.Rank
1 1001 100
2 2301 20
3 2202 60
```
Any ideas on how to do this?
Table Definitions below:
```
CREATE TABLE dbo.Playlists(
id int NOT NULL)
CREATE TABLE dbo.Customers(
id int NOT NULL,
name nchar(10) NULL)
CREATE TABLE dbo.Schedules(
id int NOT NULL,
rank int NOT NULL,
playlistid int NULL,
customerid int NULL)
CREATE TABLE dbo.PlaylistSlots(
id int NOT NULL,
slotnumber int NOT NULL,
playlistid int NULL,
fileid int NULL)
``` | ```
SELECT slotnumber, fileid, rank
FROM
(
SELECT slotnumber, fileid, Schedules.rank, RANK() OVER (PARTITION BY slotnumber ORDER BY Schedules.rank DESC) as rankfunc
FROM Schedules
INNER JOIN PlaylistSlots ON Schedules.playlistid = PlaylistSlots.playlistid
) tmp
WHERE rankfunc = 1
``` | Have you looked at SQL Server's (2005 onwards) [PARTITION and RANK](http://weblogs.sqlteam.com/jeffs/archive/2007/03/28/60146.aspx) features? | SQL Server query grouped by max value in column | [
"",
"sql",
"sql-server-2005",
"t-sql",
"sql-server-2008",
""
] |
I am currently working on an MP3 player (in a WPF application) with a WPF `MediaPlayer` and basically, I want to implement a Song Seeker which moves along with the current playing song.
I already implemented a song slider (from [Sacha Barber's application](http://www.codeproject.com/KB/WPF/WPF_Media_Player.aspx?fid=459289&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26#xx0xx)) and it works when the user drags the seeker manually (as in, the song continues from that position) but I cannot figure out how to make the seeker move according to the current position in the song.
Trouble is I don't think there is a way to check when the `Position` property of the `MediaPlayer` has changed, so I'm stumped as to how I should implement this feature.
Any ideas on how to go about such an issue?
**[Update]**
As regards incrementing the seeker with a timer, I actually thought of using the reason I didn't try it yet is because I think there is a better way to implement this using the `MediaTimeline`...but I'm yet to figure out how. | ARISE answer! and serve your master
OK, I've figured out how to work this. I'm sure I'm not doing it the completely correct way but it does work.
Here is the code-behind of a WPF application, with a Pause/Play button.
```
public partial class Main : Window
{
MediaPlayer MPlayer;
MediaTimeline MTimeline;
public Main()
{
InitializeComponent();
var uri = new Uri("C:\\Test.mp3");
MPlayer = new MediaPlayer();
MTimeline = new MediaTimeline(uri);
MTimeline.CurrentTimeInvalidated += new EventHandler(MTimeline_CurrentTimeInvalidated);
MPlayer.Clock = MTimeline.CreateClock(true) as MediaClock;
MPlayer.Clock.Controller.Stop();
}
void MTimeline_CurrentTimeInvalidated(object sender, EventArgs e)
{
Console.WriteLine(MPlayer.Clock.CurrentTime.Value.TotalSeconds);
}
private void btnPlayPause_Click(object sender, RoutedEventArgs e)
{
//Is Active
if (MPlayer.Clock.CurrentState == ClockState.Active)
{
//Is Paused
if (MPlayer.Clock.CurrentGlobalSpeed == 0.0)
MPlayer.Clock.Controller.Resume();
else //Is Playing
MPlayer.Clock.Controller.Pause();
}
else if (MPlayer.Clock.CurrentState == ClockState.Stopped) //Is Stopped
MPlayer.Clock.Controller.Begin();
}
}
```
The trick is that once you set the clock of a MediaPlayer, it becomes clock controlled, thus the use of MPlayer.Clock.Controller to do all of the controlling :) | Never played with media player but assuming you know the length of song could you not setup a timer that ticks every second while the song is playing. Therefore for every tick just increment the seeker in relation to how long the song is in total.
Song is 100 seconds long. Therefore every second/tick is worth 1 percent of total progress.
You'd have to stop the timer when pausing song etc... | WPF: Implementing a MediaPlayer Audio / Video Seeker | [
"",
"c#",
"wpf",
"xaml",
"audio",
"media-player",
""
] |
Here's the problem.
I ,for example,have a string "2500".Its converted from byte array into string.I have to convert it to decimal(int).
This is what I should get:
```
string : "2500"
byte[] : {0x25, 0x00}
UInt16 : 0x0025 //note its reversed
int : 43 //decimal of 0x0025
```
How do I do that? | Converting from hex string to UInt16 is `UInt16.Parse(s, NumberStyles.AllowHexSpecifier)`.
You'll need to write some code to do the "reversal in two-digit blocks" though. If you have control over the code that generates the string from the byte array, a convenient way to do this would be to build the string in reverse, e.g. by traversing the array from length - 1 *down* to 0 instead of in the normal upward direction. Alternatively, assuming that you know it's exactly a 4 character string, `s = s.Substring(2, 2) + s.Substring(0, 2)` would do the trick. | It might be better to explicitly specify what base you want with [Convert.ToUInt16](http://msdn.microsoft.com/en-us/library/8444cfyw.aspx).
Then, you can flip it around with [IPAddress.HostToNetworkOrder](http://msdn.microsoft.com/en-us/library/ht0w88zx.aspx) (though you'll have to cast it to an int16, then cast the result back to a uint16. | C#: Convert a UInt16 in string format into an integer(decimal) | [
"",
"c#",
""
] |
I've downloaded, unzipped and setup Eclipse 3.4.2 with some plugins (noteable, EPIC, Clearcase, QuantumDB, MisterQ).
Now I find when I'm editing Java projects the code completion is not working. If I type `String.` and press `ctrl`+`space` a popup shows "No Default Proposals" and the status bar at the bottom shows "No completions available".
Any ideas? | Try **restoring the default options** in '`Windows > Preferences > Java > Editor > Content Assist > Advanced`'
An example of the kind of data you see in this preference screen, however not necessarily what you currently have.

(From [Vadim](http://www.berezniker.com/users/vadim) in this [blog post " Content Assist Duplicates in Eclipse (Mylyn)"](http://www.berezniker.com/content/pages/java/content-assist-duplicates-eclipse-mylyn):
if have duplicate Mylyn entries, uncheck the duplicate entries that do not contain "`(Mylyn)`" in their name)
The [Eclipse help page](http://help.eclipse.org/helios/index.jsp?topic=/org.eclipse.jdt.doc.user/reference/preferences/java/editor/ref-preferences-content-assist-advanced.htm) defines the default list to restore:
> Select the proposal kinds contained in the **'default' content assist list**:
>
> * Other Java Proposals,
> * SWT Template Proposals,
> * Template Proposals,
> * Type Proposals | I'm adding an answer here in case someone else finds this on Google. Same symptoms; different problem. For me, the type caches had become corrupt.
From <http://mschrag.blogspot.co.nz/2009/01/open-type-cant-find-your-class.html>
* Quit Eclipse
* Go to workspace/.metadata/.plugins/org.eclipse.jdt.core
* Remove \*.index and savedIndexNames.txt
* Restart Eclipse and search `Ctrl`+`T` for the offending type. The indexes will be rebuilt. | Eclipse/Java code completion not working | [
"",
"java",
"eclipse",
"ide",
""
] |
I want to put a sharpen filter on an image. I have found a web [with short tutorial](http://www.student.kuleuven.be/~m0216922/CG/filtering.html).
I tried to do it in C# so here is my code. Anyway, I tried to find out why it is not working. I do not know if I am doing something wrong, if yes, please advise me what to do to make it work as it should be. Thanks
```
public static Bitmap sharpen(Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
int filterWidth = 3;
int filterHeight = 3;
int w = image.Width;
int h = image.Height;
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
Color imageColor = image.GetPixel(x, y);
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
red += imageColor.R * filter[filterX, filterY];
green += imageColor.G * filter[filterX, filterY];
blue += imageColor.B * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
sharpenImage.SetPixel(i, j, result[i, j]);
}
}
return sharpenImage;
}
``` | ```
public static Bitmap sharpen(Bitmap image)
{
Bitmap sharpenImage = new Bitmap(image.Width, image.Height);
int filterWidth = 3;
int filterHeight = 3;
int w = image.Width;
int h = image.Height;
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
for (int x = 0; x < w; ++x)
{
for (int y = 0; y < h; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
//=====[REMOVE LINES]========================================================
// Color must be read per filter entry, not per image pixel.
Color imageColor = image.GetPixel(x, y);
//===========================================================================
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + w) % w;
int imageY = (y - filterHeight / 2 + filterY + h) % h;
//=====[INSERT LINES]========================================================
// Get the color here - once per fiter entry and image pixel.
Color imageColor = image.GetPixel(imageX, imageY);
//===========================================================================
red += imageColor.R * filter[filterX, filterY];
green += imageColor.G * filter[filterX, filterY];
blue += imageColor.B * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
for (int i = 0; i < w; ++i)
{
for (int j = 0; j < h; ++j)
{
sharpenImage.SetPixel(i, j, result[i, j]);
}
}
return sharpenImage;
}
``` | I took Daniel's answer and modified it for performance, by using BitmapData class, since using GetPixel/SetPixel is very expensive and inappropriate for performance-hungry systems. It works exactly the same as the previous solution and can be used instead.
```
public static Bitmap Sharpen(Bitmap image)
{
Bitmap sharpenImage = (Bitmap)image.Clone();
int filterWidth = 3;
int filterHeight = 3;
int width = image.Width;
int height = image.Height;
// Create sharpening filter.
double[,] filter = new double[filterWidth, filterHeight];
filter[0, 0] = filter[0, 1] = filter[0, 2] = filter[1, 0] = filter[1, 2] = filter[2, 0] = filter[2, 1] = filter[2, 2] = -1;
filter[1, 1] = 9;
double factor = 1.0;
double bias = 0.0;
Color[,] result = new Color[image.Width, image.Height];
// Lock image bits for read/write.
BitmapData pbits = sharpenImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb);
// Declare an array to hold the bytes of the bitmap.
int bytes = pbits.Stride * height;
byte[] rgbValues = new byte[bytes];
// Copy the RGB values into the array.
System.Runtime.InteropServices.Marshal.Copy(pbits.Scan0, rgbValues, 0, bytes);
int rgb;
// Fill the color array with the new sharpened color values.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
double red = 0.0, green = 0.0, blue = 0.0;
for (int filterX = 0; filterX < filterWidth; filterX++)
{
for (int filterY = 0; filterY < filterHeight; filterY++)
{
int imageX = (x - filterWidth / 2 + filterX + width) % width;
int imageY = (y - filterHeight / 2 + filterY + height) % height;
rgb = imageY * pbits.Stride + 3 * imageX;
red += rgbValues[rgb + 2] * filter[filterX, filterY];
green += rgbValues[rgb + 1] * filter[filterX, filterY];
blue += rgbValues[rgb + 0] * filter[filterX, filterY];
}
int r = Math.Min(Math.Max((int)(factor * red + bias), 0), 255);
int g = Math.Min(Math.Max((int)(factor * green + bias), 0), 255);
int b = Math.Min(Math.Max((int)(factor * blue + bias), 0), 255);
result[x, y] = Color.FromArgb(r, g, b);
}
}
}
// Update the image with the sharpened pixels.
for (int x = 0; x < width; ++x)
{
for (int y = 0; y < height; ++y)
{
rgb = y * pbits.Stride + 3 * x;
rgbValues[rgb + 2] = result[x, y].R;
rgbValues[rgb + 1] = result[x, y].G;
rgbValues[rgb + 0] = result[x, y].B;
}
}
// Copy the RGB values back to the bitmap.
System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, pbits.Scan0, bytes);
// Release image bits.
sharpenImage.UnlockBits(pbits);
return sharpenImage;
}
``` | Sharpen on a Bitmap using C# | [
"",
"c#",
"image",
"image-processing",
"bitmap",
""
] |
I got a job offer today for a position as a SharePoint developer. One of my friends is telling me that sharepoint is a big mess and not something I would want to be doing.
What are some of your experiences/thoughts in working with SharePoint? | I'm going to buck the trend here a bit. I see SharePoint as a development platform - plain and simple. It utilizes other technologies such as IIS, ASP.NET, SQL Server, and Windows Workflow so I don't have to reinvent the wheel. It lets me focus on solving business problems instead of worrying about plumbing and system-level code.
Don't get me wrong, SharePoint does come with baggage, but if you like to solve real-world business problems and not just sling code, it has a lot to offer. I am continuously amazed at how rich the platform is with WSSv3 - which is free.
If you like to align yourself with Microsoft technology, then you need to realize that SharePoint is here to stay and will continue to get better and be more commonplace. The current version (v3 - WSSv3 / MOSS 2007) is lacking in AJAX, social networking, and other functionality/technology. The v4 version is just around the corner and is bound to improve in these areas.
In regards to some of the negatives I have read in this thread:
* I have written web parts that live in SharePoint that utilize the AJAX toolkit and so have co-workers of mine. One co-worker is very active with Silverlight web parts.
* Yes, you do tend to develop on Windows Server 2003/2008. This doesn't bother me and I don't spend much time at all on installation and configuration. I do use virtual machines for development environments sometimes and agree that can sometimes be a pain.
What I am able to do, however, is configure some things instead of develop. Authorization, done; provisioning, done; row-level security, done; basic UI CRUD, done; deployment to multiple front ends, done; search, done. Now I have time to focus on solving the business problem.
If you are going to do SharePoint development, you need to get started on the right foot. I highly recommend [Inside Microsoft Windows SharePoint Server 3.0](https://rads.stackoverflow.com/amzn/click/com/0735623201) to get to the meat of what a developer can/should do within SharePoint.
For what it's worth, I've been a developer for over 20 years working on Unix and Windows in several different languages and technology. I've been focusing on SharePoint v3 since it's beta days and am happy with the direction I have chosen. | I'm surprised at all of the positive responses. Let me just ask, do you mind creating your markup in code? As in HtmlWriter.BeginTag("br") (or whatever, sorry for not knowing the HtmlWriter api). That's considered best practices for creating redistributable web parts.
How about the Ajax Toolkit? Oops, off limits. Doesn't work due to a missing doc-type in the header.
And your laptop is running Windows server 2003, right? Because of course Sharepoint won't run on anything else.
I understand people defending their platform, but as someone who has had to do some work in Sharepoint, but doesn't any more ... let me say that developing for Sharepoint is the worst development experience of my life. Now, I've been pretty careful in my choices to date, so it's not the worst possible experience, but it's down there. Or, to put it another way, I would much prefer working in PHP than Sharepoint. | How good/bad is sharepoint programming? | [
"",
"c#",
".net",
"sharepoint",
""
] |
What is the correct syntax for applying string functions (e.g. "normalize-space") on a attribute using the xpath query below?
Query: "./@media"
I've seen examples of this elsewhere but if I try it using php's xpath library it returns nothing... | Using [query()](https://www.php.net/manual/en/domxpath.query.php) on a DOMXPath object will *always* result in a node-set (wrapped in a [DOMNodeList](https://www.php.net/manual/en/class.domnodelist.php) object), never in a string.
You can't pull out the results of XPath functions. You must query the nodes you want to process, and process them in PHP. | Use [evaluate()](http://www.php.net/manual/en/domxpath.evaluate.php) instead of `query()`. It will return a typed result. It's available since PHP 5.1.
```
$doc = new DOMDocument();
$xpath = new DOMXpath($doc);
$q = $xpath->evaluate('"test"');
var_dump($q);
```
output:
```
string(4) "test"
``` | php xpath - string functions on a attribute | [
"",
"php",
"xpath",
""
] |
Why isn't the following piece of code working in IE8?
```
<select>
<option onclick="javascript: alert('test');">5</option>
```
Quite bizarre - no alert is shown in IE8. I do not see the error icon in the left corner as well. Of course it works in FF and Opera. Any ideas? | Putting an `onclick` handler on an `<option>` element seems.... weird to me. You might want to switch that to the more common `onchange` event of the `<select>`. You can still do whatever you want to do from there, and this is the "accepted" way of doing whatever you want to do to the select. That being said, you might want to try removing the `javascript:` part of it. That is only needed when you are executing Javascript in a link `href` for example. An `onclick` handler *expects* javascript. | All versions of IE (6,7,8) do not support **ANY** event handlers on the option elements.
This is a (fairly) well known bug that the IE team has indicated they are in no rush to fix. :-(
Then again Opera, Safari & Chrome all have limited or no support for event handlers on options too.
Lack of events on options: [bug 280](http://webbugtrack.blogspot.com/2007/11/bug-280-lack-of-events-for-options.html)
(related) Lack of styles on options: [bug 281](http://webbugtrack.blogspot.com/2007/11/bug-291-no-styling-options-in-ie.html)
*It should be noted that "Edge" (think IE12 on Windows 10) is currently showing that this issue is fixed in preview releases.* | IE8 simple alert is failing? | [
"",
"javascript",
"internet-explorer-8",
""
] |
Anyone knows a simple JavaScript library implementing the UNZIP algorithm?
No disk-file access, only zip and unzip a string of values.
There are ActiveX, using WinZIP and other client dependent software for ZIP, written in JS. But no pure JavaScript algorithm implementation.
I would use it for displaying KMZ files in a HTML page with the GMap object (google maps). The KMZ file is just a zipped KML file. I want to unzip a KMZ file and feed the KML to GMap. | No need to unzip the KMZ file as [Google Maps absolutely understands it.](http://maps.google.com/support/bin/answer.py?hl=en&answer=41136) You can check it, simply search for the URL where your KMZ file is located in the [Google Maps web interface](http://maps.google.com/) and it will show its content on the map.
[Here is a demo](http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=http:%2F%2Fwww.ceressuto.hu%2Fimages%2Fmaps%2Fmapceres-2359112.kmz&ie=UTF8&z=7). | [DotNetZip](http://dotnetzip.codeplex.com) has a COM interface, that can be accessed from Javascript. It has a stream-to-stream unzip capability, but I have never tried using that from Javascript.
Also I have never tried using the library in any way from within IE. | unzip strings in javascript | [
"",
"javascript",
"google-maps",
"zip",
"kml",
"unzip",
""
] |
One of the first things I learned in C++ was that
```
#include <iostream>
int main()
{
std::cout<<"Hello, World!\n";
return 0;
}
```
would simply appear and disappear extremely quickly without pause. To prevent this, I had to go to notepad, and save
```
helloworld.exe
pause
```
ase
```
helloworld.bat
```
This got tedious when I needed to create a bunch of small test programs, and eventually I simply put `while(true);` at the end on most of my test programs, just so I could see the results. Is there a better wait function I can use? | you can require the user to hit enter before closing the program... something like this works.
```
#include <iostream>
int main()
{
std::cout << "Hello, World\n";
std::cin.ignore();
return 0;
}
```
The cin reads in user input, and the .ignore() function of cin tells the program to just ignore the input. The program will continue once the user hits enter.
[Link](http://en.cppreference.com/w/cpp/io/basic_istream/ignore) | Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.
**For forcing your programme stop or wait, you have several options :**
---
* **sleep(unsigned int)**
The value has to be a positive integer in millisecond.
That means that if you want your programme wait for 2 seconds, enter 2000.
Here's an example :
```
#include <iostream> //for using cout
#include <stdlib.h> //for using the function sleep
using namespace std; //for using cout
int main(void)
{
cout << "test" << endl;
sleep(5000); //make the programme waiting for 5 seconds
cout << "test" << endl;
sleep(2000); // wait for 2 seconds before closing
return 0;
}
```
If you wait too long, that probably means the parameter is in seconds. So change it to this:
```
sleep(5);
```
For those who get error message or problem using sleep try to replace it by \_sleep or Sleep especially on Code::Bloks.
And if you still getting problems, try to add of one this library on the beginning of the code.
```
#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>
```
---
* **system("PAUSE")**
A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").
```
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
system("PAUSE");
return 0;
}
```
If you get the message "error: 'system' was not declared in this scope" just add
the following line at the biggining of the code :
```
#include <cstdlib>
```
---
* **cin.ignore()**
The same result can be reached by using cin.ignore() :
```
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.ignore();
return 0;
}
```
---
* **cin.get()**
example :
```
#include <iostream>
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
cin.get();
return 0;
}
```
---
* **getch()**
Just don't forget to add the library conio.h :
```
#include <iostream>
#include <conio.h> //for using the function getch()
using namespace std;
int main(void)
{
cout << "Hello world!" << endl;
getch();
return 0;
}
```
You can have message telling you to use \_getch() insted of getch | Is there a decent wait function in C++? | [
"",
"c++",
"wait",
""
] |
I'd like to create a generic method for converting any System.Enum derived type to its corresponding integer value, without casting and preferably without parsing a string.
Eg, what I want is something like this:
```
// Trivial example, not actually what I'm doing.
class Converter
{
int ToInteger(System.Enum anEnum)
{
(int)anEnum;
}
}
```
But this doesn't appear to work. Resharper reports that you can not cast expression of type 'System.Enum' to type 'int'.
Now I've come up with this solution but I'd rather have something more efficient.
```
class Converter
{
int ToInteger(System.Enum anEnum)
{
return int.Parse(anEnum.ToString("d"));
}
}
```
Any suggestions? | If you don't want to cast,
```
Convert.ToInt32()
```
could do the trick.
The direct cast (via `(int)enumValue`) is not possible. Note that this would also be "dangerous" since an enum can have different underlying types (`int`, `long`, `byte`...).
More formally: `System.Enum` has no direct inheritance relationship with `Int32` (though both are `ValueType`s), so the explicit cast cannot be correct within the type system | I got it to work by casting to an object and then to an int:
```
public static class EnumExtensions
{
public static int ToInt(this Enum enumValue)
{
return (int)((object)enumValue);
}
}
```
This is ugly and probably not the best way. I'll keep messing with it, to see if I can come up with something better....
EDIT: Was just about to post that Convert.ToInt32(enumValue) works as well, and noticed that MartinStettner beat me to it.
```
public static class EnumExtensions
{
public static int ToInt(this Enum enumValue)
{
return Convert.ToInt32(enumValue);
}
}
```
Test:
```
int x = DayOfWeek.Friday.ToInt();
Console.WriteLine(x); // results in 5 which is int value of Friday
```
EDIT 2: In the comments, someone said that this only works in C# 3.0. I just tested this in VS2005 like this and it worked:
```
public static class Helpers
{
public static int ToInt(Enum enumValue)
{
return Convert.ToInt32(enumValue);
}
}
static void Main(string[] args)
{
Console.WriteLine(Helpers.ToInt(DayOfWeek.Friday));
}
``` | How to convert from System.Enum to base integer? | [
"",
"c#",
"enums",
"type-conversion",
""
] |
I write some C# class libary and I want to use Ninject to provide dependency injection for my classes. Is it possible for class libary to declare some code (method) that would be executed each fime the class libary is loaded. I need this to define bindings for Ninject. | I have used Ninject quite a bit over the last 9 months. Sounds like what you need to do is "load" your modules that exist in your libray into the Ninject kernel in order to register the bindings.
I am not sure if you're using Ninject 1.x or the 2.0 beta. The two versions perform things slightly differently, though conceptually, they are the same. I'll stick with version 1.x for this discussion. The other piece of information I don't know is if your main program is instantiating the Ninject kernel and your library is simply adding bindings to that kernel, or if your library itself contains the kernel and bindings. I am assuming that you need to add bindings in your library to an existing Ninject kernel in the main assembly. Finally, I'll make the assumption that you are dynamically loading this library and that it's not statically linked to the main program.
The first thing to do is define a ninject module in your library in which you register all your bindings -- you may have already done this, but it's worth mentioning. For example:
```
public class MyLibraryModule : StandardModule {
public override void Load() {
Bind<IMyService>()
.To<ServiceImpl>();
// ... more bindings ...
}
}
```
Now that your bindings are contained within a Ninject module, you can easily register them when loading your assembly. The idea is that once you load your assembly, you can scan it for all types that are derived from StandardModule. Once you have these types, you can load them into the kernel.
```
// Somewhere, you define the kernel...
var kernel = new StandardKernel();
// ... then elsewhere, load your library and load the modules in it ...
var myLib = Assembly.Load("MyLibrary");
var stdModuleTypes = myLib
.GetExportedTypes()
.Where(t => typeof(StandardModule).IsAssignableFrom(t));
foreach (Type type in stdModuleTypes) {
kernel.Load((StandardModule)Activator.CreateInstance(type));
}
```
One thing to note, you can generalize the above code further to load multiple libraries and register multiple types. Also, as I mentioned above, Ninject 2 has this sort of capability built-in -- it actually has the ability to scan directories, load assemblies and register modules. Very cool.
If your scenario is slightly different than what I've outlined, similar principles can likely be adapted. | It sounds like you are looking for the equivalent of C++'s DllMain. There is no way to do this in C#.
Can you give us some more information about your scenario and why you need code to execute in a DllMain style function?
Defining a static constructor on a type does not solve this problem. A static type constructor is only guaranteed to run before the type itself is used in any way. You can define a static constructor, use other code within the Dll that does not access the type and it's constructor will never run. | C# method that is executed after assembly is loaded | [
"",
"c#",
"class",
"ninject",
""
] |
I'm implementing a function that receives an argument which it needs to convert to its string representation.
If a given object implements a `toString()` method, then the function should use it. Otherwise, the function can rely on what the JavaScript implementation offers.
What I come up with is like this:
```
var convert = function (arg) {
return (new String(arg)).valueOf();
}
``` | I'm not sure you even need a function, but this would be the shortest way:
```
function( arg ) {
return arg + '';
}
```
Otherwise this is the shortest way:
```
arg += '';
``` | `String(null)` returns - "null"
`String(undefined)` returns - "undefined"
`String(10)` returns - "10"
`String(1.3)` returns - "1.3"
`String(true)` returns - "true"
`String(new Error("foo"))` returns - "Error: foo"
I think this is a more elegant way. | How to convert instance of any type to string? | [
"",
"javascript",
""
] |
Is this possible:
```
myList = []
myList[12] = 'a'
myList[22] = 'b'
myList[32] = 'c'
myList[42] = 'd'
```
When I try, I get:
```
# IndexError: list assignment index out of range #
``` | You'll have to pre-fill it with something (e.g. `0` or `None`) before you can index it:
```
myList = [None] * 100 # Create list of 100 'None's
myList[12] = 'a' # etc.
```
Alternatively, use a dict instead of a list, as [Alex Martelli suggested](https://stackoverflow.com/questions/869778/populating-a-list-array-by-index-in-python/869805#869805). | For a "sparse list" you could use a `dict` instead:
```
mylist = {}
mylist[12] = 'a'
```
etc. If you want an actual list (initialize it with `[]`, *not* `()`, of course!-) you need to fill the un-set slots to \_some\_thing, e.g. `None`, by a little auxiliary function or by subclassing `list`. | Populating a list/array by index in Python? | [
"",
"python",
"list",
""
] |
I have a code that looks like this:
```
int main () {
fstream file;
file.open("test.bin", ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
return 0;
}
```
when I run it alone, it exits with -1, so obviously it failed to open "test.bin". However, if I save a blank notepad file as "test.bin", and run it, it works fine. What I am wondering is how I can get my C++ program to automatically generate an empty file "test.bin" if a file called "test.bin" does not already exist. | Your code snippet is wrong since it's trying to write to a file that you've opened for input. If you want to write to the file, simply use `ios::out` instead of `ios::in`.
If you want to open the file for reading but create it if it does not exist, you can use:
```
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
file.open("test.bin", ios::out | ios::binary);
int n = 3;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.close();
file.open("test.bin", ios::in | ios::binary);
if(!file.is_open()) {
return -1;
}
}
```
This will initialize the file with the integer 3 as the default contents, if it doesn't already exist.
If it does exist, it will leave the contents alone. In either case, you'll have the file open at the first byte. | I'd assume you could probably just do it by opening and closing a file:
```
if (GetFileAttributes("test.bin") == INVALID_FILE_ATTRIBUTES)
{
fstream file;
file.open("test.bin", ios::out);
file.close();
}
``` | Is there a function in C++ that creates a .bin file, or is this code missing something? | [
"",
"c++",
"file-io",
"binary-data",
""
] |
I'm trying to get into PDO details. So I coded this:
```
$cn = getConnection();
// get table sequence
$comando = "call p_generate_seq('bitacora')";
$id = getValue($cn, $comando);
//$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (?, ?, ?)';
$comando = 'INSERT INTO dsa_bitacora (id, estado, fch_creacion) VALUES (:id, :estado, :fch_creacion)';
$parametros = array (
':id'=> (int)$id,
':estado'=>1,
':fch_creacion'=>date('Y-m-d H:i:s')
);
execWithParameters($cn, $comando, $parametros);
```
my getValue function works fine, and I get the next sequence for the table. But when I get into execWithParameters, i get this exception:
> PDOException: SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL\_ATTR\_USE\_BUFFERED\_QUERY attribute. in D:\Servidor\xampp\_1\_7\_1\htdocs\bitacora\func\_db.php on line 77
I tried to modify the connection attributes but it doesn't work.
These are my core db functions:
```
function getConnection() {
try {
$cn = new PDO("mysql:host=$host;dbname=$bd", $usuario, $clave, array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));
$cn->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true);
return $cn;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
}
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
while($res = $resul->fetch()) {
$retorno = $res[0][0];
break;
}
return $retorno;
}
function execWithParameters($cn, $comando, $parametros) {
$q = $cn->prepare($comando);
$q->execute($parametros);
if ($q->errorInfo() != null) {
$e = $q->errorInfo();
echo $e[0].':'.$e[1].':'.$e[2];
}
}
```
Somebody who can shed a light for this? PD. Please do not suggest doing autonumeric id, cause i am porting from another system. | The issue is that mysql only allows for one outstanding cursor at a given time. By using the fetch() method and not consuming all the pending data, you are leaving a cursor open.
The recommended approach is to consume all the data using the fetchAll() method.
An alternative is to use the closeCursor() method.
If you change this function, I think you will be happier:
```
<?php
function getValue($cn, $comando) {
$resul = $cn->query($comando);
if (!$resul) return null;
foreach ($resul->fetchAll() as $res) {
$retorno = $res[0];
break;
}
return $retorno;
}
?>
``` | I don't think PDOStatement::closeCursor() would work if you're not doing a query that returns data (i.e. an UPDATE, INSERT, etc).
A better solution is to simply unset() your PDOStatement object after calling PDOStatement::execute():
```
$stmt = $pdo->prepare('UPDATE users SET active = 1');
$stmt->execute();
unset($stmt);
``` | PDO Unbuffered queries | [
"",
"php",
"pdo",
""
] |
What is the minimum code required to read a file and assign its contents to a string in c++?
I did read a lot of tutorials that worked but they were all different in a way so i am trying to see why, so if you could please include some explanatory comments that would be great.
---
**Related:** [What is the best way to read an entire file into a std::string in C++?](https://stackoverflow.com/questions/116038/what-is-the-best-way-to-slurp-a-file-into-a-stdstring-in-c) | ```
#include <fstream>
#include <string>
int main()
{
std::ifstream file("myfile.txt"); // open the file
std::string line, whole_file;
// Read one line at a time from 'file' and store the result
// in the string called 'line'.
while (std::getline(file, line))
{
// Append each line together so the entire file will
// be in one string.
whole_file += line;
whole_file += '\n';
}
return 0;
// 'file' is closed automatically when the object goes out of scope.
}
```
A couple of things to note here. `getline()` returns a reference to the stream object, which fails the while-test if anything bad happens or if you reach the end of the file. Also, the trailing newline is *not* included in the string, so you have to append it manually. | The shortest code: (not effecient)
```
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
std::ifstream f("plop");
std::string buffer;
std::copy(std::istreambuf_iterator<char>(f),
std::istreambuf_iterator<char>(),
std::back_inserter(buffer));
}
```
How I would probably do it:
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <fstream>
int main()
{
// Find the size of the file
std::ifstream file("Plop");
file.seekg(0,std::ios_base::end);
std::streampos size = file.tellg();
// Read the file in one go.
file.seekg(0);
std::vector<char> buffer(size); // pre-szie the vector.
file.read(&buffer[0],size);
// or
// Until the next version of the standard I don't think string gurantees contigious storage.
// But all the current versions I know do use continious storage so it should workd.
file.seekg(0);
std::string buffer1(size);
file.read(&buffer1[0],size);
}
``` | C++ Reading Files | [
"",
"c++",
""
] |
I have a DB table that contains a comma separated list of ID's (ints) that are stored as nvarchar.
I have a get method to return these in one hit as a list. At the moment I think I'll have to do something like this:
```
List<int> ids = new List<int>();
string[] pageids = experssion.Split(separators)
foreach (string number in pageids)
{
ids.Add(Convert.ToInt32(number));
}
```
Can anyone think of a nicer way to do this ? Can I do it all on the split somehow ? | I'd to it like this:
```
var ids = expression.Split(separator).Select(s => int.Parse(s));
```
It uses the Linq extensions of .NET 3.0. As an alternative (saves one lambda), you could also do this which is arguably less readable:
```
var ids = expression.Split(separator).Select((Func<string, int>)int.Parse);
``` | If you're not using C# 3.0, or aren't a fan of LINQ, you could do it the C# 2.0 way:
```
// This gives you an int[]
int[] pageids = Array.ConvertAll(expression.Split(separator), new Converter<string,int>(StringToInt));
// Add each id to the list
ids.AddRange(pageids);
public static int StringToInt(string s)
{
return int.Parse(s);
}
```
EDIT:
Or, even simpler as per Konrad's suggestion:
```
int[] pageids = Array.ConvertAll<string,int>(expression.Split(separator),int.Parse);
ids.AddRange(pageids);
``` | Best way to do a split and convert the result into ints | [
"",
"c#",
"string",
""
] |
I'm looking for a method, or a way to detect clients using any type of proxy server viewing my web site. I'm using PHP/Apache... what's the best way to do this? Any proxy server would need to be detected, not specifically one or the other.
**Edit**
I am more interested in the anonymous proxies... as the normal ones are easily detected by looking for `HTTP_X_FORWARDED_FOR`.
**Another Edit**
Try this:
1) go to <http://kproxy.com> (or any other free anonymous proxy site)
2) visit: <http://www.worldofwarcraft.com>
3) they are able to block somehow, as the page errors out with "Error loading stylesheet: A network error occurred loading an XSLT stylesheet:<http://kproxy.com/new-hp/layout/layout.xsl>"
I want to do something similar to prevent proxies. | You can't detect that unless they pass on special headers which explictly mention it like X-Forwarded-For or something.
As far as I know you have to use a blacklist. Users who use putty portforwarding, VPN or other more sophisticated methods are undetactable as they behave exactly like normal users. | Use the following 2 solutions in PHP.
Method 1: quick but does not work with anonymous proxies
```
$proxy_headers = array(
'HTTP_VIA',
'HTTP_X_FORWARDED_FOR',
'HTTP_FORWARDED_FOR',
'HTTP_X_FORWARDED',
'HTTP_FORWARDED',
'HTTP_CLIENT_IP',
'HTTP_FORWARDED_FOR_IP',
'VIA',
'X_FORWARDED_FOR',
'FORWARDED_FOR',
'X_FORWARDED',
'FORWARDED',
'CLIENT_IP',
'FORWARDED_FOR_IP',
'HTTP_PROXY_CONNECTION'
);
foreach($proxy_headers as $x){
if (isset($_SERVER[$x])) die("You are using a proxy!");
}
```
Method 2: portscan back to the origin IP at the normal proxy ports used.
```
$ports = array(8080,80,81,1080,6588,8000,3128,553,554,4480);
foreach($ports as $port) {
if (@fsockopen($_SERVER['REMOTE_ADDR'], $port, $errno, $errstr, 30)) {
die("You are using a proxy!");
}
}
``` | Detect clients with Proxy Servers via PHP | [
"",
"php",
"proxy",
""
] |
I have a bit of Javascript code that creates a "save friendly" version of a webpage.
`child = window.open("","child");
child.document.write(htmlPage);`
"htmlPage" is the basic html of the page with all the javascript references taken out, a different set of header images references, etc.
Everything displays perfectly in the popup window, with no javascript running.
When I click on "File->Save As", the saved file is the parent window, along with all of its javascript, and with no trace of the child window. Does anyone know how to solve this problem? I want to save only the child window.
Thanks,
-Kraryal | When you save the page it will save the original URL content (e.g. just as if you downloaded a fresh copy)
If you want a "cleansed" version, you'll need to generate that version on the server, and open the popup with that URL as the first param. | I had a similar situation (but wasn't willing to give up altogether). I'm constructing a save-friendly version of a webpage using Javascript that I want the user to download as a text file (comma-separated values, in my case). I think `data:` URIs can help here.
```
//construct the csvOutput in Javascript first
var popup = window.open("data:application/octet-stream," + encodeURIComponent(csvOutput), "child");
//no need to document.write() anything in the child window
```
In Firefox, this doesn't pop up a window even, just asks the user if they want to save the file, and saves it as a .part file. Not exactly ideal, but at least it saves the file without popping up an unnecessary window.
Alternatively, we can use the text/plain MIME type:
```
//construct the csvOutput in Javascript first
var popup = window.open("data:text/plain;charset=utf-8," + encodeURIComponent(csvOutput), "child");
```
In Firefox, this does pop open a new window, but then it's saved by default as ASCII text, without any of the cruft of the parent window or any line-wrapping. This is probably what I will use.
It looks like this won't work in IE though. IE 8 is the only version that supports `data:` URIs, and it has a [series of restrictions](http://msdn.microsoft.com/en-us/library/cc848897%28VS.85%29.aspx) on where it can be used. For IE, you might look at [execCommand](http://msdn.microsoft.com/en-us/library/ms536419(VS.85).aspx).
Thanks to this [tek-tip thread](http://www.tek-tips.com/viewthread.cfm?qid=1517391&page=1) and the [Wikipedia article on the data URI scheme](http://en.wikipedia.org/wiki/Data_URI_scheme). | Saving a child window saves the parent window instead (Javascript) | [
"",
"javascript",
"internet-explorer",
"file",
"save",
"window.open",
""
] |
Currently having some problems-
```
now = datetime.datetime.now()
month = now.strftime("%B")
site = wikipedia.getSite('en', 'wikiquote')
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:abc")
```
I need to get abc to change into the name of the month before it then tries to get the page, yet everything I try it gives an error of some sort.
How could I do it?
Thanks! | Would this work?
```
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day:" + month)
``` | The page URL format is actually [`Wikiquote:Quote_of_the_day/Month`](http://en.wikiquote.org/wiki/Wikiquote:Quote_of_the_day/May). Try this:
```
page = wikipedia.Page(site, u"Wikiquote:Quote_of_the_day/%s" % month)
``` | How to do this with datetime & getpage in Python? | [
"",
"python",
""
] |
In C#, how do I round a float upwards to the nearest int?
I see Math.Ceiling and Math.Round, but these returns a decimal. Do I use one of these then cast to an Int? | If you want to round to the **nearest** int:
```
int rounded = (int)Math.Round(precise, 0);
```
You can also use:
```
int rounded = Convert.ToInt32(precise);
```
Which will use `Math.Round(x, 0);` to round and cast for you. It looks neater but is slightly less clear IMO.
---
If you want to round **up**:
```
int roundedUp = (int)Math.Ceiling(precise);
``` | Off the top of my head:
```
float fl = 0.678;
int rounded_f = (int)(fl+0.5f);
``` | How do I round a float upwards to the nearest int in C#? | [
"",
"c#",
".net",
"rounding",
""
] |
I have read multiple articles about why singletons are bad.
I know it has few uses like logging but what about initalizing and deinitializing.
Are there any problems doing that?
I have a scripting engine that I need to bind on startup to a library.
Libraries don't have main() so what should I use?
Regular functions or a Singleton.
Can this object be copied somehow:
```
class
{
public:
static void initialize();
static void deinitialize();
} bootstrap;
```
If not why do people hide the copy ctor, assignment operator and the ctor? | Libraries in C++ have a much simpler way to perform initialization and cleanup. It's the exact same way you'd do it for anything else. RAII.
Wrap everything that needs to be initialized in a class, and perform its initialization in the constructor. Voila, problems solved.
All the usual problems with singletons still apply:
* You *are* going to need more than one instance, even if you hadn't planned for it. If nothing else, you'll want it when unit-testing. Each test should initialize the library from scratch so that it runs in a clean environment. That's hard to do with a singleton approach.
* You're screwed as soon as these singletons start referencing each others. Because the actual initialization order isn't visible, you quickly end up with a bunch of circular references resulting in accessing uninitialized singletons or stack overflows or deadlocks or other fun errors *which could have been caught at compile-time if you hadn't been obsessed with making everything global*.
* Multithreading. It's usually a bad idea to force all threads to share the same instance of a class, becaus it forces that class to lock and synchronize **everything**, which costs a lot of performance, and may lead to deadlocks.
* Spaghetti code. You're hiding your code's dependencies every time you use a singleton or a global. It is no longer clear which objects a function depends on, because not all of them are visible as parameters. And because you don't need to add them as parameters, you easily end up adding far more dependencies than necessary. Which is why singletons are almost impossible to remove once you have them. | A singleton's purpose is to have only ONE instance of a certain class in your system.
The C'tor, D'tor and CC'tor are hidden, in order to have a single access point for receiving the only existing instance.
Usually the instance is static (could be allocated on the heap too) and private, and there's a static method (usually called GetInstance) which returns a reference to this instance.
The question you should ask yourself when deciding whether to have a singleton is : Do I really need to enforce having one object of this class?
There's also the inheritance problem - it can make things complicated if you are planning to inherit from a singleton.
Another problem is [How to kill a singleton](http://sourcemaking.com/design_patterns/to_kill_a_singleton) (the web is filled with articles about this issue)
In some cases it's better to have your private data held statically rather than having a singleton, all depends on the domain.
Note though, that if you're multi-threaded, static variables can give you a pain in the XXX...
So you should analyse your problem carefully before deciding on the design pattern you're going to use...
In your case, I don't think you need a singleton because you want the libraries to be initialized at the beginning, but it has nothing to do with enforcing having only one instance of your class. You could just hold a static flag (static bool Initialized) if all you want is to ensure initializing it only once.
Calling a method once is not reason enough to have a singleton. | Initializing a program using a Singleton | [
"",
"c++",
"design-patterns",
"singleton",
""
] |
I want to remove digits from a float to have a fixed number of digits after the dot, like:
```
1.923328437452 → 1.923
```
I need to output as a string to another function, not print.
Also I want to ignore the lost digits, not round them. | First, the function, for those who just want some copy-and-paste code:
```
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '{}'.format(f)
if 'e' in s or 'E' in s:
return '{0:.{1}f}'.format(f, n)
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
```
This is valid in Python 2.7 and 3.1+. For older versions, it's not possible to get the same "intelligent rounding" effect (at least, not without a lot of complicated code), but rounding to 12 decimal places before truncation will work much of the time:
```
def truncate(f, n):
'''Truncates/pads a float f to n decimal places without rounding'''
s = '%.12f' % f
i, p, d = s.partition('.')
return '.'.join([i, (d+'0'*n)[:n]])
```
# Explanation
The core of the underlying method is to convert the value to a string at full precision and then just chop off everything beyond the desired number of characters. The latter step is easy; it can be done either with string manipulation
```
i, p, d = s.partition('.')
'.'.join([i, (d+'0'*n)[:n]])
```
or the `decimal` module
```
str(Decimal(s).quantize(Decimal((0, (1,), -n)), rounding=ROUND_DOWN))
```
The first step, converting to a string, is quite difficult because there are some pairs of floating point literals (i.e. what you write in the source code) which both produce the same binary representation and yet should be truncated differently. For example, consider 0.3 and 0.29999999999999998. If you write `0.3` in a Python program, the compiler encodes it using the IEEE floating-point format into the sequence of bits (assuming a 64-bit float)
```
0011111111010011001100110011001100110011001100110011001100110011
```
This is the closest value to 0.3 that can accurately be represented as an IEEE float. But if you write `0.29999999999999998` in a Python program, the compiler translates it into *exactly the same value*. In one case, you meant it to be truncated (to one digit) as `0.3`, whereas in the other case you meant it to be truncated as `0.2`, but Python can only give one answer. This is a fundamental limitation of Python, or indeed any programming language without lazy evaluation. The truncation function only has access to the binary value stored in the computer's memory, not the string you actually typed into the source code.1
If you decode the sequence of bits back into a decimal number, again using the IEEE 64-bit floating-point format, you get
```
0.2999999999999999888977697537484345957637...
```
so a naive implementation would come up with `0.2` even though that's probably not what you want. For more on floating-point representation error, [see the Python tutorial](https://docs.python.org/3/tutorial/floatingpoint.html).
It's very rare to be working with a floating-point value that is so close to a round number and yet is *intentionally* not equal to that round number. So when truncating, it probably makes sense to choose the "nicest" decimal representation out of all that could correspond to the value in memory. Python 2.7 and up (but not 3.0) includes a [sophisticated algorithm to do just that](https://bugs.python.org/issue1580), which we can access through the default string formatting operation.
```
'{}'.format(f)
```
The only caveat is that this acts like a `g` format specification, in the sense that it uses exponential notation (`1.23e+4`) if the number is large or small enough. So the method has to catch this case and handle it differently. There are a few cases where using an `f` format specification instead causes a problem, such as trying to truncate `3e-10` to 28 digits of precision (it produces `0.0000000002999999999999999980`), and I'm not yet sure how best to handle those.
If you actually *are* working with `float`s that are very close to round numbers but intentionally not equal to them (like 0.29999999999999998 or 99.959999999999994), this will produce some false positives, i.e. it'll round numbers that you didn't want rounded. In that case the solution is to specify a fixed precision.
```
'{0:.{1}f}'.format(f, sys.float_info.dig + n + 2)
```
The number of digits of precision to use here doesn't really matter, it only needs to be large enough to ensure that any rounding performed in the string conversion doesn't "bump up" the value to its nice decimal representation. I think `sys.float_info.dig + n + 2` may be enough in all cases, but if not that `2` might have to be increased, and it doesn't hurt to do so.
In earlier versions of Python (up to 2.6, or 3.0), the floating point number formatting was a lot more crude, and would regularly produce things like
```
>>> 1.1
1.1000000000000001
```
If this is your situation, if you *do* want to use "nice" decimal representations for truncation, all you can do (as far as I know) is pick some number of digits, less than the full precision representable by a `float`, and round the number to that many digits before truncating it. A typical choice is 12,
```
'%.12f' % f
```
but you can adjust this to suit the numbers you're using.
---
1Well... I lied. Technically, you *can* instruct Python to re-parse its own source code and extract the part corresponding to the first argument you pass to the truncation function. If that argument is a floating-point literal, you can just cut it off a certain number of places after the decimal point and return that. However this strategy doesn't work if the argument is a variable, which makes it fairly useless. The following is presented for entertainment value only:
```
def trunc_introspect(f, n):
'''Truncates/pads the float f to n decimal places by looking at the caller's source code'''
current_frame = None
caller_frame = None
s = inspect.stack()
try:
current_frame = s[0]
caller_frame = s[1]
gen = tokenize.tokenize(io.BytesIO(caller_frame[4][caller_frame[5]].encode('utf-8')).readline)
for token_type, token_string, _, _, _ in gen:
if token_type == tokenize.NAME and token_string == current_frame[3]:
next(gen) # left parenthesis
token_type, token_string, _, _, _ = next(gen) # float literal
if token_type == tokenize.NUMBER:
try:
cut_point = token_string.index('.') + n + 1
except ValueError: # no decimal in string
return token_string + '.' + '0' * n
else:
if len(token_string) < cut_point:
token_string += '0' * (cut_point - len(token_string))
return token_string[:cut_point]
else:
raise ValueError('Unable to find floating-point literal (this probably means you called {} with a variable)'.format(current_frame[3]))
break
finally:
del s, current_frame, caller_frame
```
Generalizing this to handle the case where you pass in a variable seems like a lost cause, since you'd have to trace backwards through the program's execution until you find the floating-point literal which gave the variable its value. If there even is one. Most variables will be initialized from user input or mathematical expressions, in which case the binary representation is all there is. | ```
round(1.923328437452, 3)
```
See [Python's documentation on the standard types](http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex). You'll need to scroll down a bit to get to the round function. Essentially the second number says how many decimal places to round it to. | How to truncate float values? | [
"",
"python",
"floating-point",
""
] |
The following function
System.Threading.Thread.Sleep();
delay the thread in millisecond, and take the integer value as a parameter. Is there any method of thread delay in microsecond. Or can sleep function take the float values?
Thanks | Nope. To quote Will Dean from [85122](https://stackoverflow.com/questions/85122/sleep-less-than-one-millisecond)
> you can't meaningfully 'sleep' (i.e. relinquish your scheduled CPU) for such short periods. If you want to delay for some short time, then you need to spin, repeatedly checking a suitably high-resolution timer (e.g. the 'performance timer') and hoping that something of high priority doesn't pre-empt you anyway. | Sleep is not accurate to the millisecond in the first place. I think it's resolution is hardware dependent, and the smallest slice of time you can sleep will typically be around 20 ms. This has to do with Sleep actually releases what might be remaining of the current thread's timeslice; and allows another thread to run. The earliest time your thread will be able to run again, is after one thread scheduler timeslice has passed. Therefore the resolution is about 20 ms (assuming a timeslice on your system is 20 ms).
Since Windows is not a real-time OS; Sleep and other wait functions can never be fully deterministic.
Depending on your application, you could perhaps do a Sleep for the most of the time and then do a busy wait where timing is critical. Or rewrite the structure so that you measure time passed accurately (use System.Diagnostics.Stopwatch); but do not depend on being able to sleep for an accurate time period in the millisecond range.
The [first answer in this thread on MSDN](http://social.msdn.microsoft.com/Forums/en-US/clr/thread/facc2b57-9a27-4049-bb32-ef093fbf4c29) also explains it very nicely. | Time Delay in C# | [
"",
"c#",
".net",
""
] |
I've never used regexes in my life and by jove it looks like a deep pool to dive into. Anyway,
I need a regex for this pattern (AN is alphanumeric (a-z or 0-9), N is numeric (0-9) and A is alphabetic (a-z)):
```
AN,AN,AN,AN,AN,N,N,N,N,N,N,AN,AN,AN,A,A
```
That's five AN's, followed by six N's, followed by three AN's, followed finally by two A's.
If it makes a difference, the language I'm using is Java. | ```
[a-z0-9]{5}[0-9]{6}[a-z0-9]{3}[a-z]{2}
```
should work in most RE dialects for the tasks as you specified it -- most of them will also support abbreviations such as `\d` (digit) in lieu of `[0-9]` (but if alphabetics need to be lowercase, as you appear to be requesting, you'll probably need to spell out the `a-z` parts). | Replace each AN by [a-z0-9], each N by [0-9], and each A by [a-z]. | Simple regex required | [
"",
"java",
"regex",
""
] |
I want to close the dialog box when you click outside of the dialog, but I'm not sure how you test that in jquery/plain javascript.
Some have suggested using the blur event, but this doesn't seem to be supported by jquery dialog.
---
**EDIT** I have this question too but cannot make do with any of the currently supplied answers, since I cannot make my dialog boxes modal.
I need this so that I can register key handlers only when a dialog is top most, and de-register them as soon as another dialog is brought to the top.
Does anyone have a solution - ideally one that results in an event being raised each time some other dialog comes to the top? | Can you make your dialog modal? If so, then you can (probably) achieve what you're after by events on the modal overlay...
Completely hacky, untested idea, but it might just work...
Modal dialogs create events called click.dialog-overlay, etc... These are fired when the mouse is clicked outside the dialog, on the modal overlay. Hooking those events and closing the dialog **might** just do what you're trying to do... | # Pure jQueryUI no modal dialog.
## Example:
<http://jsfiddle.net/marcosfromero/x4GXy/>
## Code:
```
// Bind the click event to window
$(window).click(function(event) {
if (($(event.target).closest('.ui-dialog')).length>0) {
// if clicked on a dialog, do nothing
return false;
} else {
// if clicked outside the dialog, close it
// jQuery-UI dialog adds ui-dialog-content class to the dialog element.
// with the following selector, we are sure that any visible dialog is closed.
$('.ui-dialog-content:visible').dialog('close');
}
})
``` | How do you test that a modal jquery dialog has lost focus? | [
"",
"javascript",
"jquery",
"dialog",
""
] |
I am putting some heavy though into re-writing the data access layer in my software(If you could even call it that). This was really my first project that uses, and things were done in an improper manner.
In my project all of the data that is being pulled is being stored in an arraylist. some of the data is converted from the arraylist into an typed object, before being put backinto an arraylist.
Also, there is no central set of queries in the application. This means that some queries are copy and pasted, which I want to eliminate as well.This application has some custom objects that are very standard to the application, and some queries that are very standard to those objects.
I am really just not sure if I should create a layer between my objects and the class that reads and writes to the database. This layer would take the data that comes from the database, type it as the proper object, and if there is a case of multiple objects being returned, return a list of those object. Is this a good approach?
Also, if this is a good way of doing things, how should I return the data from the database? I am currently using SqlDataReader.read, and filling an array list. I am sure that this is not the best method to use here, i am just not real clear on how to improve this.
**The Reason for all of this, is I want to centralize all of the database operations into a few classes, rather than have them spread out amongst all of the classes in the project** | One thing comes to mind right off the bat. Is there a reason you use ArrayLists instead of generics? If you're using .NET 1.1 I could understand, but it seems that one area where you could gain performance is to remove ArrayLists from the picture and stop converting and casting between types.
Another thing you might think about which can help a lot when designing data access layers is an ORM. [NHibernate](https://www.hibernate.org/343.html) and [LINQ to SQL](http://weblogs.asp.net/scottgu/archive/2007/05/19/using-linq-to-sql-part-1.aspx) do this very well. In general, the N-tier approach works well for what it seems like you're trying to accomplish. For example, performing data access in a class library with specific methods that can be reused is far better than "copy-pasting" the same queries all over the place.
I hope this helps. | You should use an ORM. "Not doing so is stealing from your customers" - Ayende | Improving my data access layer | [
"",
"sql",
"vb.net",
""
] |
We've always been an Intel shop. All the developers use Intel machines, recommended platform for end users is Intel, and if end users want to run on AMD it's their lookout. Maybe the test department had an AMD machine somewhere to check we didn't ship anything completely broken, but that was about it.
Up until a few of years ago we just used the MSVC compiler and since it doesn't really offer a lot of processor tuning options beyond SSE level, noone worried too much about whether the code might favour one x86 vendor over another. However, more recently we've been using the Intel compiler a lot. Our stuff definitely gets some significant performance benefits from it (on our Intel hardware), and its vectorization capabilities mean less need to go to asm/intrinsics. However people are starting to get a bit nervous about whether the Intel compiler may actually not be doing such a good job for AMD hardware. Certainly if you step into the Intel CRT or IPP libraries you see a lot of cpuid queries to apparently set up jump tables to optimised functions. It seems unlikely Intel go to much trouble to do anything good for AMDs chips though.
Can anyone with any experience in this area comment on whether it's a big deal or not in practice ? (We've yet to actually do any performance testing on AMD ourselves).
**Update 2010-01-04**: Well the need to support AMD never became concrete enough for me to do any testing myself. There are some interesting reads on the issue [here](http://www.agner.org/optimize/blog/read.php?i=49), [here](http://www.brightsideofnews.com/print/2009/12/17/why-the-ftc-lawsuit-against-intel-has-substance.aspx) and [here](http://arstechnica.com/hardware/reviews/2008/07/atom-nano-review.ars/6) though.
**Update 2010-08-09**: It seems the Intel-FTC settlement has something to say about this issue - see "Compilers and Dirty Tricks" section of [this article](http://www.semiaccurate.com/2010/08/06/more-intel-dirt-cleaned-ftc/). | Buy an AMD box and run it on that. That seems like the only responsible thing to do, rather than trusting strangers on the internet ;)
Apart from that, I believe part of AMD's lawsuit against Intel is based on the claim that Intel's compiler specifically produces code that runs inefficiently on AMD processors. I don't know whether that's true or not, but AMD seems to believe so.
But even if they don't willfully do that, there's no doubt that Intel's compiler optimizes specifically for Intel processors and nothing else.
When that is said, I doubt it'd make a huge difference. AMD CPU's would still benefit from all the auto-vectorization and other clever features of the compiler. | I'm surely stating the obvious, if performance is crucial for your application, then you'd better do some testing - on all combinations of hardware/compiler. There are no guarantees. As outsiders, we can only give you our guesses/biases. Your software may have unique characteristics that are unlike what we've seen.
My experience:
I used to work at Intel, and developed an in-house (C++) application where performance was critical. We tried to use Intel's C++ compiler, and it **always** under performed gcc - even after doing profile runs, recompiling using the profiled information (which icc supposedly uses to optimize) and re-running on the exact same dataset (this was in 2005-2007, things may be different now). So, based on my experience, you might want to try gcc (in addition to icc and MSVC), it's possible you will get better performance that way and side-step the question. It shouldn't be too hard to switch compilers (if your build process is reasonable).
Now I work at a different company, and the IT folks do extensive hardware testing, and for a while Intel and AMD hardware was relatively comparable, but the latest generation of Intel hardware significantly out-performed the AMD. As a result, I believe they purchased significant amounts of Intel CPUs and recommend the same for our customers who run our software.
But, back to the question as to whether the Intel compiler specifically targets AMD hardware to run slowly. I doubt Intel bothers with that. It could be that certain optimizations that use knowledge about the internals of Intel CPU architecture or chipsets could run slower on AMD hardware, but I doubt they specifically target AMD hardware. | How much should I worry about the Intel C++ compiler emitting suboptimal code for AMD? | [
"",
"c++",
"optimization",
"compiler-construction",
"intel",
"amd-processor",
""
] |
I was looking at a job posting requesting a desired knowledge of: "Client side asynchronous frameworks". What do they mean by this with respect to Microsoft technologies, specifically .NET framework? | I think it refers to AJAX technologies, like [ASP.NET Ajax](http://www.asp.net/ajax/) and [jQuery](http://docs.jquery.com/Ajax). | That would be what is more commonly known as [AJAX](http://en.wikipedia.org/wiki/Ajax_(programming)). | What is meant by: "Client side asynchronous frameworks" | [
"",
"c#",
".net",
"multithreading",
"asynchronous",
""
] |
I need to reset a MySQL Field value automatically at midnight. It is a specific column in a specific row in a table. I know how to do this in PHP but I do not know how to execute the PHP Script at midnight without someone having to do it themselves. Do you have any viable solutions?
Edit:--------------------
Preferably without using Cron Jobs. | If you are running on linux you would use a [cronjob](http://en.wikipedia.org/wiki/Cron)
On most distros there is a command called crontab that schedules tasks for you and a specific format you need:
```
0 0 * * * php /path/to/file.php
```
**EDIT:**
Wrote this before you edited yours :p I'm not sure there is any other way. Do you have a specific reason not to use a cronjob?
You may not even need to specify the php part if the php file is marked as executable i.e
```
0 0 * * * /path/to/file.php
```
Just do "chmod +x /path/to/file.php" form the linux command line | There are web based cron services too. Basically you set up an account and then they visit an URL of your choosing at a regular interval. On your server you set up a page that does what you need to get done. Preferably give it a unlikely-to-find-name like myjob789273634ahhh8s2nhw8sghusgf874wfu.php. You get the idea. (Remember that PHP-scripts timeout after like 30secs.)
Here's a google search:
\*\*oops I'm new so I can't post URL apparently. Just search for "web based cron".
Good luck
/0 | Resetting a MySQL Field value without user execution | [
"",
"php",
"mysql",
""
] |
I have just recently battled a bug in Python. It was one of those silly newbie bugs, but it got me thinking about the mechanisms of Python (I'm a long time C++ programmer, new to Python). I will lay out the buggy code and explain what I did to fix it, and then I have a couple of questions...
The scenario: I have a class called A, that has a dictionary data member, following is its code (this is simplification of course):
```
class A:
dict1={}
def add_stuff_to_1(self, k, v):
self.dict1[k]=v
def print_stuff(self):
print(self.dict1)
```
The class using this code is class B:
```
class B:
def do_something_with_a1(self):
a_instance = A()
a_instance.print_stuff()
a_instance.add_stuff_to_1('a', 1)
a_instance.add_stuff_to_1('b', 2)
a_instance.print_stuff()
def do_something_with_a2(self):
a_instance = A()
a_instance.print_stuff()
a_instance.add_stuff_to_1('c', 1)
a_instance.add_stuff_to_1('d', 2)
a_instance.print_stuff()
def do_something_with_a3(self):
a_instance = A()
a_instance.print_stuff()
a_instance.add_stuff_to_1('e', 1)
a_instance.add_stuff_to_1('f', 2)
a_instance.print_stuff()
def __init__(self):
self.do_something_with_a1()
print("---")
self.do_something_with_a2()
print("---")
self.do_something_with_a3()
```
Notice that every call to `do_something_with_aX()` initializes a new "clean" instance of class A, and prints the dictionary before and after the addition.
The bug (in case you haven't figured it out yet):
```
>>> b_instance = B()
{}
{'a': 1, 'b': 2}
---
{'a': 1, 'b': 2}
{'a': 1, 'c': 1, 'b': 2, 'd': 2}
---
{'a': 1, 'c': 1, 'b': 2, 'd': 2}
{'a': 1, 'c': 1, 'b': 2, 'e': 1, 'd': 2, 'f': 2}
```
In the second initialization of class A, the dictionaries are not empty, but start with the contents of the last initialization, and so forth. I expected them to start "fresh".
What solves this "bug" is obviously adding:
```
self.dict1 = {}
```
In the `__init__` constructor of class A. However, that made me wonder:
1. What is the meaning of the "dict1 = {}" initialization at the point of dict1's declaration (first line in class A)? It is meaningless?
2. What's the mechanism of instantiation that causes copying the reference from the last initialization?
3. If I add "self.dict1 = {}" in the constructor (or any other data member), how does it not affect the dictionary member of previously initialized instances?
---
EDIT: Following the answers I now understand that by declaring a data member and not referring to it in the `__init__` or somewhere else as self.dict1, I'm practically defining what's called in C++/Java a static data member. By calling it self.dict1 I'm making it "instance-bound". | What you keep referring to as a bug is the [documented](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables), standard behavior of Python classes.
Declaring a dict outside of `__init__` as you initially did is declaring a class-level variable. It is only created once at first, whenever you create new objects it will reuse this same dict. To create instance variables, you declare them with `self` in `__init__`; its as simple as that. | When you access attribute of instance, say, self.foo, python will first find 'foo' in `self.__dict__`. If not found, python will find 'foo' in `TheClass.__dict__`
In your case, `dict1` is of class A, not instance. | Python Class Members Initialization | [
"",
"python",
"class",
"initialization",
""
] |
I am making a custom form object in Django which has an overrided \_\_init\_\_ method. The purpose of overriding the method is to dynamically generate drop-down boxes based on the new parameters.
For example,
```
class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, label_suffix=':', empty_permitted=False,
ticket=None):
if ticket:
self.__class__.State = State.GetTicketStateField(ticket.Type)
super(forms.BaseForm, self ).__init__(data=data, files=files,
auto_id=auto_id, prefix=prefix, initial=initial,
label_suffix=label_suffix, empty_permitted=empty_permitted)
```
This solution does not work. It appears that the fields are created before the \_\_init\_\_ is called. I would assume this problem would be pretty common. What would be the Django way of handling these classes of problems. | You can dynamically modify your form by using the `self.fields` dict. Something like this may work for you:
```
class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, ticket, *args, **kwargs):
super(TicketForm, self).__init__(*args, **kwargs)
self.fields['state'] = State.GetTicketStateField(ticket.Type)
``` | I found a solution [here](http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/). If there is a better solution, please post a reply.
```
class TicketForm(forms.Form):
Type = Type.GetTicketTypeField()
def __init__(self, ticket=None, *args, **kwargs):
super(TicketForm, self ).__init__(*args, **kwargs)
if ticket:
self.fields['State'] = State.GetTicketStateField(ticket.Type)
``` | Django: Overriding __init__ for Custom Forms | [
"",
"python",
"django",
""
] |
I have inherited a few programs from a previous developer who was a little sloppy with naming variables, methods and classes with different capitalization and sometimes underscores.
Is there a program or a way in visual studio to validate the naming of each variable, method, property, constant, class.... I would be fine with the standard C# conventions. | You could look at Microsoft StyleCop and FXCop | I use ReSharper 4.5 for that, which has this advantage, that it allows you to see non-comforming code as you write it.
You also can use NDepend and CQL to check your conventions in a very granular and flexible way. It's great as part of your build script.
Both tools cost money, both are worth it. | C# check or force naming conventions | [
"",
"c#",
"naming-conventions",
""
] |
One of our staff members has lost his mailbox but luckily has a dump of his email in mbox format. I need to somehow get all the messages inside the mbox file and squirt them into our tech support database (as its a custom tool there are no import tools available).
I've found [SharpMimeTools](http://anmar.eu.org/projects/sharpmimetools/) which breaks down a message but not allow you to iterate through a bunch of messages in a mbox file.
Does anyone know of a decent parser thats open without having to learn the RFC to write one out? | I don't know any parser, but mbox is really a very simple format. A new email begins on lines starting with "From " (From+Space) and an empty line is attached to the end of each mail. Should there be any occurence of "From " at the beginning of a line in the email itself, this is quoted out (by prepending a '>').
Also see [Wikipedia's entry on the topic](http://en.wikipedia.org/wiki/Mbox#Family). | I'm working on a MIME & mbox parser in C# called [MimeKit](http://github.com/jstedfast/MimeKit).
It's based on earlier MIME & mbox parsers I've written (such as [GMime](http://spruce.sourceforge.net/gmime)) which were insanely fast (could parse every message in an 1.2GB mbox file in about 1 second).
I haven't tested MimeKit for performance yet, but I am using many of the same techniques in C# that I used in C. I suspect it'll be slower than my C implementation, but since the bottleneck is I/O and MimeKit is written to do optimal (4k) reads like GMime is, they should be pretty close.
The reasons you are finding your current approach to be slow (StreamReader.ReadLine(), combining the text, then passing it off to SharpMimeTools) are because of the following reasons:
1. StreamReader.ReadLine() is not a very optimal way of reading data from a file. While I'm sure StreamReader() does internal buffering, it needs to do the following steps:
A) Convert the block of bytes read from the file into unicode (this requires iterating over the bytes in the byte[] read from disk to convert the bytes read from the stream into a unicode char[]).
B) Then it needs to iterate over its internal char[], copying each char into a StringBuilder until it finds a '\n'.
So right there, with just reading lines, you have at least 2 passes over your mbox input stream. Not to mention all of the memory allocations going on...
2. Then you combine all of the lines you've read into a single mega-string. This requires another pass over your input (copying every char from each string read from ReadLine() into a StringBuilder, presumably?).
We are now up to 3 iterations over the input text and no parsing has even happened yet.
3. Now you hand off your mega-string to SharpMimeTools which uses a SharpMimeMessageStream which... (/facepalm) is a ReadLine()-based parser that sits on top of another StreamReader that does charset conversion. That makes 5 iterations before anything at all is even parsed. SharpMimeMessageStream also has a way to "undo" a ReadLine() if it discovers it has read too far. So it is reasonable to assume that he is scanning over *some* of those lines at least twice. Not to mention all of the string allocations going on... ugh.
4. For each header, once SharpMimeTools has its line buffer, it splits into field & value. That's another pass. We are up to 6 passes so far.
5. SharpMimeTools then uses string.Split() (which is a pretty good indication that this mime parser is not standards compliant) to tokenize address headers by splitting on ',' and parameterized headers (such as Content-Type and Content-Disposition) by splitting on ';'. That's another pass. (We are now up to 7 passes.)
6. Once it splits those it runs a regex match on each string returned from the string.Split() and then more regex passes per rfc2047 encoded-word token before finally making another pass over the encoded-word charset and payload components. We're talking at least 9 or 10 passes over much of the input by this point.
I give up going any farther with my examination because it's already more than 2x as many passes as GMime and MimeKit need and I *know* my parsers could be optimized to make at least 1 less pass than they do.
Also, as a side-note, any MIME parser that parses strings instead of byte[] (or sbyte[]) is never going to be very good. The problem with email is that so many mail clients/scripts/etc in the wild will send undeclared 8bit text in headers and message bodies. How can a unicode string parser *possibly* handle that? Hint: it can't.
```
using (var stream = File.OpenRead ("Inbox.mbox")) {
var parser = new MimeParser (stream, MimeFormat.Mbox);
while (!parser.IsEndOfStream) {
var message = parser.ParseMessage ();
// At this point, you can do whatever you want with the message.
// As an example, you could save it to a separate file based on
// the message subject:
message.WriteTo (message.Subject + ".eml");
// You also have the ability to get access to the mbox marker:
var marker = parser.MboxMarker;
// You can also get the exact byte offset in the stream where the
// mbox marker was found:
var offset = parser.MboxMarkerOffset;
}
}
```
**2013-09-18 Update:** I've gotten MimeKit to the point where it is now usable for parsing mbox files and have successfully managed to work out the kinks, but it's not nearly as fast as my C library. This was tested on an iMac so I/O performance is not as good as it would be on my old Linux machine (which is where GMime is able to parse similar sized mbox files in ~1s):
```
[fejj@localhost MimeKit]$ mono ./mbox-parser.exe larger.mbox
Parsed 14896 messages in 6.16 seconds.
[fejj@localhost MimeKit]$ ./gmime-mbox-parser larger.mbox
Parsed 14896 messages in 3.78 seconds.
[fejj@localhost MimeKit]$ ls -l larger.mbox
-rw-r--r-- 1 fejj staff 1032555628 Sep 18 12:43 larger.mbox
```
As you can see, GMime is still quite a bit faster, but I have some ideas on how to improve the performance of MimeKit's parser. It turns out that C#'s `fixed` statements are quite expensive, so I need to rework my usage of them. For example, [a simple optimization](https://github.com/jstedfast/MimeKit/commit/a6384b0defe509198616573f03557d33c9b9feac) I did yesterday shaved about 2-3s from the overall time (if I remember correctly).
**Optimization Update:** Just improved performance by another 20% by replacing:
```
while (*inptr != (byte) '\n')
inptr++;
```
with:
```
do {
mask = *dword++ ^ 0x0A0A0A0A;
mask = ((mask - 0x01010101) & (~mask & 0x80808080));
} while (mask == 0);
inptr = (byte*) (dword - 1);
while (*inptr != (byte) '\n')
inptr++;
```
**Optimization Update:** I was able to finally make MimeKit as fast as GMime by switching away from my use of Enum.HasFlag() and using direct bit masking instead.
MimeKit can now parse the same mbox stream in 3.78s.
For comparison, SharpMimeTools takes more than 20 *minutes* (to test this, I had to split the emails apart into separate files because SharpMimeTools can't parse mbox files).
**Another Update:** I've gotten it down to 3.00s flat via various other tweaks throughout the code. | Reading an mbox file in C# | [
"",
"c#",
"email",
"mime",
"mbox",
""
] |
I want to enhance an application, but there is no 3:e party API available.
So basically the idea is to draw graphics/text on top of the applications windows.
There are problems with z order, clipping, and directing mouse clicks either to my application or the other application.
What is an elegant way of doing this?
Example image here. It is a trading application where my application wants to add extra information into the trading application's windows.
[URL=<http://img104.imageshack.us/my.php?image=windowontop.png][/URL]> | There are no nice ways to do this, but one approach that may work for you is to hook the application in question using SetWindowsHookEx(...) to add a GetMsgProc, which draws your overlay in response to WM\_PAINT messages. The basic idea is that you're drawing YOUR graphics right after the application finishes its own drawing.
In your main app:
```
....
HMODULE hDllInstance = LoadLibrary("myFavoriteDll");
HOOKPROC pOverlayHook = (HOOKPROC)GetProcAddress(hDllInstance, "OverlayHook");
SetWindowsHookEx(WH_GETMESSAGE, pOverlayHook, hDllInstance, threadId);
```
Off in a DLL somewhere:
```
LRESULT CALLBACK OverlayHook(int code, WPARAM wParam, LPARAM lParam)
{
//Try and be the LAST responder to WM_PAINT messages;
//Of course, if some other application tries this all bets are off
LRESULT retCode = CallNextHookEx(NULL, code, wParam, lParam);
//Per GetMsgProc documentation, don't do anything fancy
if(code < 0) return retCode;
//Assumes that target application only draws when WM_PAINT message is
//removed from input queue.
if(wParam == PM_NOREMOVE) return retCode;
MSG* message = (MSG*)lParam;
//Ignore everything that isn't a paint request
if(message->message != WM_PAINT) return retCode;
PAINTSTRUCT psPaint;
BeginPaint(message->hwnd, &psPaint);
//Draw your overlay here
...
EndPaint(message->hwnd, &psPaint);
return retCode;
}
```
This is all win32 so your C# code will be p/invoke heavy and correspondingly quite ugly. Your DLL must be unmanaged as well (if you intend to inject into a process other than your own), making this an even nastier solution.
This would solve your issue with z-order and clipping issues, as you're rendering into the window itself. However, if the application you're targeting does any drawing outside of the WinProc responding to WM\_PAINT things fall apart; this is not an entirely uncommon occurence. | You might want to draw it on top of directX for games
<http://spazzarama.com/2011/03/14/c-screen-capture-and-overlays-for-direct3d-9-10-and-11-using-api-hooks/> | How to draw graphics/text on top of another application | [
"",
"c#",
"windows",
"winapi",
"graphics",
""
] |
Let's say I instantiate an object in Javascript like this:
```
var myObj = new someObject();
```
Now, is it possible to obtain the var object's name as string `'myObj'` from within one of the class methods?
---
### Additional details (edited):
The reason why I would like to get the name of the variable holding reference to the object is that my new `myObj` would create a new clickable `DIV` on the page that would need to call a function `myObj.someFunction()`. As I insert the new `DIV` I need to know the name of the variable holding reference to the object. Is there maybe a better way of doing this?
---
You are right, sorry for the mixup in terminology.
The reason why I would like to get the name of the variable holding reference to the object is that my new myObj would create a new clickable DIV on the page that would need to call a function myObj.someFunction(). As I insert the new DIV I need to know the name of the variable holding reference to the object. Is there maybe a better way of doing this? | Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:
```
function myClass() {
this.myName = function () {
// search through the global object for a name that resolves to this object
for (var name in this.global)
if (this.global[name] == this)
return name
}
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"
```
Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.
**edit**: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:
```
function myConstructor () {
this.count = 0
this.clickme = function () {
this.count += 1
alert(this.count)
}
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
// This is the crucial part. We don't construct an onclick handler by creating a
// string, but instead we pass in a function that does what we want. In order to
// refer to the object, we can't use this directly (since that will refer to the
// div when running event handler), but we create an anonymous function with an
// argument and pass this in as that argument.
newDiv.onclick = (function (obj) {
return function () {
obj.clickme()
}
})(this)
newDiv.appendChild(contents)
document.getElementById("frobnozzle").appendChild(newDiv)
}
window.onload = function () {
var myVar = new myConstructor()
}
``` | **Short answer:** No. myObj isn't the name of the object, it's the name of a variable holding a reference to the object - you could have any number of other variables holding a reference to the same object.
Now, if it's your program, then you make the rules: if you want to say that any given object will only be referenced by one variable, ever, and diligently enforce that in your code, then just set a property on the object with the name of the variable.
That said, i doubt what you're asking for is actually what you really want. Maybe describe your problem in a bit more detail...?
---
**Pedantry:** JavaScript doesn't have classes. `someObject` is a constructor function. Given a reference to an object, you can obtain a reference to the function that created it using the [constructor property](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Object/constructor).
---
### In response to the additional details you've provided:
The answer you're looking for can be found here: [JavaScript Callback Scope](https://stackoverflow.com/questions/183214/javascript-callback-scope) (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS). You just need to wrap the call to the object member in a closure that preserves access to the context object. | How to get class object's name as a string in Javascript? | [
"",
"javascript",
"class",
""
] |
I must be going out of my mind, because my unit tests are failing because the following code is throwing a null ref exception:
```
int pid = 0;
if (parentCategory != null)
{
Console.WriteLine(parentCategory.Id);
pid = parentCategory.Id;
}
```
The line that's throwing it is:
```
pid = parentCategory.Id;
```
The console.writeline is just to debug in the NUnit GUI, but that outputs a valid int.
*Edit:* It's single-threaded so it can't be assigned to null from some other thread, and the fact the the Console.WriteLine successfully prints out the value shows that it shouldn't throw.
*Edit:* Relevant snippets of the Category class:
```
public class Category
{
private readonly int id;
public Category(Category parent, int id)
{
Parent = parent;
parent.PerformIfNotNull(() => parent.subcategories.AddIfNew(this));
Name = string.Empty;
this.id = id;
}
public int Id
{
get { return id; }
}
}
```
Well if anyone wants to look at the full code, it's on Google Code at <http://code.google.com/p/chefbook/source/checkout>
I think I'm going to try rebooting the computer... I've seen pretty weird things fixed by a reboot. Will update after reboot.
*Update:* Mystery solved. Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered. | Looks like NUnit shows the error line as the last successfully executed statement... Copy/pasted test into new console app and ran in VS showed that it was the line after the if statement block (not shown) that contained a null ref. Thanks for all the ideas everyone. +1 to everyone that answered. | Based on all the info so far, I think either "the line that's throwing is" is wrong (what makes you think that), or possibly your 'sources' are out of sync with your built assemblies.
This looks impossible, so some 'taken for granted assumption' is wrong, and it's probably the assumption that "the source code you're looking at matches the process you're debugging". | How can this code throw a NullReferenceException? | [
"",
"c#",
"nunit",
""
] |
HTML Javascript question
to get the selected value of a input-select I can use
```
<select id="gender" name="gender" class="style12">
<option selected="selected">ALL</option>
<option>Male Only</option>
<option>Female Only</option>
</select>
document.getElementById('gender').value
```
is there any easy way for me to get the selected label (i.e. ALL / Male Only / Female Only) with javascript?
Thanks a lot for reading. | ```
var el = document.getElementById('gender');
var text = el.options[el.selectedIndex].innerHTML;
``` | suggested jQuery version:
```
jQuery("#gender").find("option[value='" + jQuery("#gender").val() + "']").text()
``` | How to get the selected label from a html <select>? | [
"",
"javascript",
"html",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.