Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I need a way to insert new articles straight into my MediaWiki database without damaging the wiki installation.
I'm guessing if I knew what tables/attributes MediaWiki inserts to when creating a new article then I could fill them in myself.
Does anyone know a better way or have any suggestions? | Out of many bots and APIs available for MediaWiki, a simple place to begin is the [MediaWiki Bulk Page creator](http://meta.wikimedia.org/wiki/MediaWiki_Bulk_Page_Creator).
It is a simple PHP script, relying on the Snoopy class library, that can create several pages from a simple text format.
Before getting started, make sure you read [Creating a Bot](http://en.wikipedia.org/wiki/Wikipedia:Creating_a_bot) first. it contains critical details on how to set up bot access to your wiki. | I am the author of the Bulk Page Creator, nice to see it is still being used!!!
My latest MediaWiki Import tool creates pages from a CSV data file and page template. It generates Mediawiki XML Import files as suggested by Adrian.
Check it out
[Mediawiki CSV Import](http://mwcsvimport.pronique.com/) | Inserting articles straight into MediaWiki database | [
"",
"sql",
"database",
"wiki",
"mediawiki",
"wikipedia",
""
] |
I can extract the month and day by using `Day(Date())`, `Month(Date())`. I can't extract hours, with `HOUR(Date())`. I get the following error.
```
'HOUR' is not a recognized built-in function name.
```
How can I extract hours? | ```
SELECT DATEPART(HOUR, GETDATE());
```
[`DATEPART` documentation](http://msdn.microsoft.com/en-us/library/ms174420%28loband%29.aspx) | ... you can use it on any granularity type i.e.:
```
DATEPART(YEAR, [date])
DATEPART(MONTH, [date])
DATEPART(DAY, [date])
DATEPART(HOUR, [date])
DATEPART(MINUTE, [date])
```
(note: I like the [ ] around the date reserved word though. Of course that's in case your column with timestamp is labeled "date") | Extracting hours from a DateTime (SQL Server 2005) | [
"",
"sql",
"t-sql",
"datetime",
"sql-server-2005",
"hour",
""
] |
I have a process id in Python. I know I can kill it with os.kill(), but how do I check if it is alive ? Is there a built-in function or do I have to go to the shell? | Use `subprocess` module to spawn process.
There is **proc.poll()** function - it returns `None` if process is still alive, otherwise it returns process returncode.
**<http://docs.python.org/library/subprocess.html>** | `os.kill` does not kill processes, it sends them signals (it's poorly named).
If you send signal 0, you can determine whether you are allowed to send other signals. An error code will indicate whether it's a permission problem or a missing process.
See `man 2 kill` for more info.
Also, if the process is your child, you can get a `SIGCHLD` when it dies, and you can use one of the `wait` calls to deal with it. | How do I check if a process is alive in Python on Linux? | [
"",
"python",
"process",
""
] |
A function to return human readable size from bytes size:
```
>>> human_readable(2048)
'2 kilobytes'
>>>
```
How to do this? | Addressing the above "too small a task to require a library" issue by a straightforward implementation (using f-strings, so Python 3.6+):
```
def sizeof_fmt(num, suffix="B"):
for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
if abs(num) < 1024.0:
return f"{num:3.1f}{unit}{suffix}"
num /= 1024.0
return f"{num:.1f}Yi{suffix}"
```
Supports:
* all currently known [binary prefixes](https://en.wikipedia.org/wiki/Binary_prefix#Specific_units_of_IEC_60027-2_A.2_and_ISO.2FIEC_80000)
* negative and positive numbers
* numbers larger than 1000 Yobibytes
* arbitrary units (maybe you like to count in Gibibits!)
Example:
```
>>> sizeof_fmt(168963795964)
'157.4GiB'
```
by [Fred Cirera](https://web.archive.org/web/20111010015624/http://blogmag.net/blog/read/38/Print_human_readable_file_size) | A library that has all the functionality that it seems you're looking for is [`humanize`](https://pypi.python.org/pypi/humanize). `humanize.naturalsize()` seems to do everything you're looking for.
Example code (`python 3.10`)
```
import humanize
disk_sizes_list = [1, 100, 999, 1000,1024, 2000,2048, 3000, 9999, 10000, 2048000000, 9990000000, 9000000000000000000000]
for size in disk_sizes_list:
natural_size = humanize.naturalsize(size)
binary_size = humanize.naturalsize(size, binary=True)
print(f" {natural_size} \t| {binary_size}\t|{size}")
```
Output
```
1 Byte | 1 Byte |1
100 Bytes | 100 Bytes |100
999 Bytes | 999 Bytes |999
1.0 kB | 1000 Bytes |1000
1.0 kB | 1.0 KiB |1024
2.0 kB | 2.0 KiB |2000
2.0 kB | 2.0 KiB |2048
3.0 kB | 2.9 KiB |3000
10.0 kB | 9.8 KiB |9999
10.0 kB | 9.8 KiB |10000
2.0 GB | 1.9 GiB |2048000000
10.0 GB | 9.3 GiB |9990000000
9.0 ZB | 7.6 ZiB |9000000000000000000000
``` | Get human readable version of file size? | [
"",
"python",
"code-snippets",
"filesize",
""
] |
Does anyone know of an existing browser/OS useragent string grid? It's hard to test, and I would really like a broad sampling of useragent strings, if possible. If no such grid exists, mind posting your useragent string?
Given the idiosyncrocies of the browser/operating system combinations, this information is essential for successful web development.
Thanks! | Not a grid but, [this site](http://www.useragentstring.com/pages/useragentstring.php) seems pretty comprehensive. | I would strongly suggest against relying on user-agent strings in any kind of JS app. You will get nothing but problems. Browsers have new versions, some change spoof the user-agent string etc.
A good example was that various sites broke when Opera 10 was released, because they were sniffing the user agent string and read 10 as 1.
Instead, you should use feature detection - test if the browser supports what you're trying to do.
There is really no good reason to sniff the user agent string, other than collecting usage statistics. | Javascript useragent grid? | [
"",
"javascript",
"cross-platform",
"user-agent",
""
] |
Can anyone recommend whether I should do something like:
```
os = new GzipOutputStream(new BufferedOutputStream(...));
```
or
```
os = new BufferedOutputStream(new GzipOutputStream(...));
```
Which is more efficient? Should I use BufferedOutputStream at all? | > What order should I use `GzipOutputStream` and `BufferedOutputStream`
For object streams, I found that wrapping the buffered stream around the gzip stream for both input and output was almost always *significantly* faster. The smaller the objects, the better this did. Better or the same in all cases then no buffered stream.
```
ois = new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(fis)));
oos = new ObjectOutputStream(new BufferedOutputStream(new GZIPOutputStream(fos)));
```
*However*, for text and straight byte streams, I found that it was a toss up -- with the gzip stream around the buffered stream being only slightly better. But better in all cases then no buffered stream.
```
reader = new InputStreamReader(new GZIPInputStream(new BufferedInputStream(fis)));
writer = new OutputStreamWriter(new GZIPOutputStream(new BufferedOutputStream(fos)));
```
I ran each version 20 times and cut off the first run and averaged the rest. I also tried buffered-gzip-buffered which was slightly better for objects and worse for text. I did not play with buffer sizes at all.
---
For the object streams, I tested 2 serialized object files in the 10s of megabytes. For the larger file (38mb), it was 85% faster on reading (0.7 versus 5.6 seconds) but actually slightly slower for writing (5.9 versus 5.7 seconds). These objects had some large arrays in them which may have meant larger writes.
```
method crc date time compressed uncompressed ratio
defla eb338650 May 19 16:59 14027543 38366001 63.4%
```
For the smaller file (18mb), it was 75% faster for reading (1.6 versus 6.1 seconds) and 40% faster for writing (2.8 versus 4.7 seconds). It contained a large number of small objects.
```
method crc date time compressed uncompressed ratio
defla 92c9d529 May 19 16:56 6676006 17890857 62.7%
```
---
For the text reader/writer I used a 64mb csv text file. The gzip stream around the buffered stream was 11% faster for reading (950 versus 1070 milliseconds) and slightly faster when writing (7.9 versus 8.1 seconds).
```
method crc date time compressed uncompressed ratio
defla c6b72e34 May 20 09:16 22560860 63465800 64.5%
``` | [GZIPOutputStream](http://docs.oracle.com/javase/7/docs/api/index.html?java/util/zip/GZIPOutputStream.html) already comes with a built-in buffer. So, there is no need to put a BufferedOutputStream right next to it in the chain. gojomo's excellent answer already provides some guidance on where to place the buffer.
The default buffer size for GZIPOutputStream is only 512 bytes, so you will want to increase it to 8K or even 64K via the constructor parameter. The default buffer size for BufferedOutputStream is 8K, which is why you can measure an advantage when combining the default GZIPOutputStream and BufferedOutputStream. That advantage can also be achieved by properly sizing the GZIPOutputStream's built-in buffer.
So, to answer your question: *"Should I use BufferedOutputStream at all?"* → No, in your case, you should not use it, but instead set the GZIPOutputStream's buffer to at least 8K. | What order should I use GzipOutputStream and BufferedOutputStream | [
"",
"java",
"gzipoutputstream",
""
] |
Is there free and good line-level profiler for PHP? I'm using xdebug and it's relatively good but it gives me function level output and sometimes it's hard to see where exactly all the time spent in the function goes. | Not free, but the [SD PHP Profiler](http://www.semanticdesigns.com/Products/Profilers/PHPProfiler.html) provides information about the relative costs of each block of PHP code, not just functions: | Zend Platform will give you some more precise profiling information. Its that or using webgrind and zend studio / Eclipse profiler for you performance information. | Is there free and good line-level profiler for PHP? | [
"",
"php",
"profiler",
""
] |
I'm trying to programatically get a list of installed fonts in C or Python. I need to be able to do this on OS X, does anyone know how? | Python with PyObjC installed (which is the case for Mac OS X 10.5+, so this code will work without having to install anything):
```
import Cocoa
manager = Cocoa.NSFontManager.sharedFontManager()
font_families = list(manager.availableFontFamilies())
```
(based on htw's answer) | Why not use the Terminal?
**System Fonts:**
```
ls -R /System/Library/Fonts | grep ttf
```
**User Fonts:**
```
ls -R ~/Library/Fonts | grep ttf
```
**Mac OS X Default fonts:**
```
ls -R /Library/Fonts | grep ttf
```
If you need to run it inside your C program:
```
void main()
{
printf("System fonts: ");
execl("/bin/ls","ls -R /System/Library/Fonts | grep ttf", "-l",0);
printf("Mac OS X Default fonts: ");
execl("/bin/ls","ls -R /Library/Fonts | grep ttf", "-l",0);
printf("User fonts: ");
execl("/bin/ls","ls -R ~/Library/Fonts | grep ttf", "-l",0);
}
``` | List of installed fonts OS X / C | [
"",
"python",
"c",
"macos",
"fonts",
""
] |
I have a RichTextBox and I want to save the text to a file. Each line of the RichTextBox are ended with CR+LF ("\n\r") but when i save it to a file, the lines only contains the LF char at the end.
If I copy the content to the clipboard instead of a file all goes right (The content of the clipboar has CR+LF at the end of each line, I can see it when I paste in Notepad++). txtClass is the RichTextBox.
private void btnToClipboard\_Click(object sender, EventArgs e)
{
//Works as desired
Clipboard.SetText(txtClass.Text);
}
```
private void btnToFile_Click(object sender, EventArgs e)
{
//Don't work as desired
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter SW = new System.IO.StreamWriter(saveFileDialog1.FileName, false, Encoding.ASCII);
SW.Write(txtClass.Text);
SW.Close();
}
}
```
At this moment, I also tried with
```
SW.NewLine = "\r\n";
SW.Newline = Environment.NewLine
```
and with all Enconding avalilables.
If I use
SW.Write("Line One\r\nLineTwo\r\nLineThree") also works fine.
Thanks for your help | Thanks to Peter Lindholm, who gave me the correct answer in a comment.
> Did you try the SaveFile method
> located on the RichTextBox itself?
> <http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.savefile(VS.71).aspx> | I had the same issue - but didn't want to save as a RichTextBox - just a standard simple txt file that could easily be read and edited in notepad.
The issue is for some reason the StreamWriter class does NOT write the \n into the file (still not sure why - you would think it would) :)
So a simple solution is to manually replace \n with \r\n and works perfect as expected.
See code snipit below:
```
if ((myStream = ScriptFileSaveDB.OpenFile()) != null)
{
using (StreamWriter sr = new StreamWriter(myStream))
{
//Since \n (newlines) are not being written correctly as \r\n
//Go thru Text and replace all "\n" with \r\n
tempStr = ScriptProgramWindowRTB.Text;
tempStr = tempStr.Replace("\n", "\r\n");
sr.Write(tempStr);
}
``` | Writing the content of a RichTextBox to a file | [
"",
"c#",
"richtextbox",
"iostream",
"newline",
""
] |
Executor seems like a clean abstraction. When would you want to use Thread directly rather than rely on the more robust executor? | To give some history, Executors were only added as part of the java standard in Java 1.5. So in some ways Executors can be seen as a new better abstraction for dealing with Runnable tasks.
A bit of an over-simplification coming... - Executors are threads done right so use them in preference. | I use Thread when I need some pull based message processing. E.g. a Queue is take()-en in a loop in a separate thread. For example, you wrap a queue in an expensive context - lets say a JDBC connection, JMS connection, files to process from single disk, etc.
Before I get cursed, do you have some scenario?
**Edit**:
As stated by others, the `Executor` (`ExecutorService`) interface has more potential, as you can use the `Executors` to select a behavior: scheduled, prioritized, cached etc. in Java 5+ or a j.u.c backport for Java 1.4.
The executor framework has protection against crashed runnables and automatically re-create worker threads. One drawback in my opinion, that you have to explicitly `shutdown()` and `awaitTermination()` them before you exit your application - which is not so easy in GUI apps.
If you use bounded queues you need to specify a `RejectedExecutionHandler` or the new runnables get thrown away.
You might have a look at [Brian Goetz et al: Java Concurrency in Practice (2006)](http://jcip.net/) | When should we use Java's Thread over Executor? | [
"",
"java",
"multithreading",
"concurrency",
"executor",
""
] |
Is there a difference between ++x and x++ in java? | ++x is called preincrement while x++ is called postincrement.
```
int x = 5, y = 5;
System.out.println(++x); // outputs 6
System.out.println(x); // outputs 6
System.out.println(y++); // outputs 5
System.out.println(y); // outputs 6
``` | yes
++x increments the value of x and then returns x
x++ returns the value of x and then increments
example:
```
x=0;
a=++x;
b=x++;
```
after the code is run both a and b will be 1 but x will be 2. | Is there a difference between x++ and ++x in java? | [
"",
"java",
"syntax",
"operators",
"increment",
""
] |
I'm trying to write Unicode characters (♠) using `System.out`, and a question mark (`?`) gets printed instead.
How can I have proper Unicode characters displayed instead of question marks?
I'm using IntelliJ IDEA on Windows, and trying to print from within the IDE. | Is the file encoding configured correctly? See that "Settings | File Encodings" uses UTF-8. Printing ♠ works for me when I have IDE encoding and all files set to UTF-8. Recompiling may be needed after changing the encoding. | Go to `Help` > `Edit Custom VM options...` then add the following option:
```
-Dconsole.encoding=UTF-8
-Dfile.encoding=UTF-8
```
I'm not sure if both are necessary but it worked for me. You need to restart IntelliJ for changes to be applied.
I had already tried changing every encoding setting in Intellij, setting those options in Gradle and changing the system encoding, this is the only one that worked. | Unicode characters appear as question marks in IntelliJ IDEA console | [
"",
"java",
"intellij-idea",
"unicode",
"console",
"jvm",
""
] |
I'm actually creating websites for fun and some of my friends told me that I could be more efficient if I could create the output of the page with a php class that would represent the whole page.
I was wondering how you people would do it.
Thanks | I'd suggest looking into some PHP frameworks, such as Cake which is good for beginners, or Symfony or Zend Framework if you're more skilled. Those will streamline your PHP development a lot. | I am not a OO programmer .. but, as a proof of concept, and as per your question, you can do/try something like this.
```
class Page {
public $meta_title;
public $meta_keywords;
public $html_body;
public function displayPage() {
$page ='
<html>
<head>
<title>'.$this->meta_title.'</title>
<meta name="keywords" content="'.$this->meta_keywords.'" />
</head>
<body>
'.$this->html_body.'
</body>
</html>
';
echo $page;
}
}
```
Then you just use this Page class as ..
```
$page = new Page();
$page->meta_title ="Hello world!";
$page->meta_keywords = "some text keywords";
$page->body = '<h1>Contact Us </h1>
<p>you can contact us at blah ... blah .. etc.</p>
<address>Dummy Address </address>
';
$page->displayPage();
```
Please note that you can add so many things into to it like .. class variables (type array) to define stylesheets, javascripts files .. then you just loop over it to define these files dynamically for individual pages.
You can amend the display page function so that it accomodate left, right, or top navigation bar. Then you can also have variables like $show\_right\_bar, $show\_left\_bar to control which pages display which side navigation bar. So you can amend and extend to whatever your requirements are.
Alternatively, you can try some php frameworks, which are much more evolved solutions, but that really depends on your programming skills and your requirements.
Hope this helps. | Page generation from PHP class | [
"",
"php",
"class",
"code-generation",
""
] |
I am receiving long string of checked html checkbox values (Request.Form["mylist"] return Value1,Value2,Value3....) on the form post in ASP.NET 2.0 page.
Now I simply want to loop these but I don't know what is the best practice to loop this array of string. I am trying to do something like this:
```
foreach (string Item in Request.Form["mylist"]){
Response.Write(Request.Form["mylist"][Item] + "<hr>");
}
```
But it does not work. | You have to split the comma separated string. Try
```
string myList = Request.Form["myList"];
if(string.isNullOrEmpty(myList))
{
Response.Write("Nothing selected.");
return;
}
foreach (string Item in myList.split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries))
{
Response.Write(item + "<hr>");
}
``` | I recommend to do not use Split in Form values to prevent splitting values with commas.
```
string myList = Request.Form.GetValues("myList");
foreach (var Item in myList)
{
Response.Write(item + "<hr>");
}
``` | checkbox array loop in c# | [
"",
"c#",
"asp.net",
"checkbox",
"foreach",
""
] |
I was thinking of using a Double as the key to a HashMap but I know floating point comparisons are unsafe, that got me thinking. Is the equals method on the Double class also unsafe? If it is then that would mean the hashCode method is probably also incorrect. This would mean that using Double as the key to a HashMap would lead to unpredictable behavior.
Can anyone confirm any of my speculation here? | **Short answer:** Don't do it
**Long answer:** Here is how the key is going to be computed:
The actual key will be a `java.lang.Double` object, since keys must be objects. Here is its `hashCode()` method:
```
public int hashCode() {
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
```
The `doubleToLongBits()` method basically takes the 8 bytes and represent them as long. So it means that small changes in the computation of double can mean a great deal and you will have key misses.
If you can settle for a given number of points after the dot - multiply by 10^(number of digits after the dot) and convert to int (for example - for 2 digits multiply by 100).
It will be much safer. | I think you are right. Although the hash of the doubles are ints, the double could mess up the hash. That is why, as Josh Bloch mentions in Effective Java, when you use a double as an input to a hash function, you should use [doubleToLongBits()](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Double.html#doubleToLongBits(double)). Similarly, use floatToIntBits for floats.
In particular, to use a double as your hash, following Josh Bloch's recipe, you would do:
```
public int hashCode() {
int result = 17;
long temp = Double.doubleToLongBits(the_double_field);
result = 37 * result + ((int) (temp ^ (temp >>> 32)));
return result;
}
```
This is from Item 8 of Effective Java, "Always override hashCode when you override equals". It can be found in [this pdf of the chapter from the book](http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf).
Hope this helps. | Double in HashMap | [
"",
"java",
"hashcode",
""
] |
I need to build a class in this form
```
namespace BestCompanyEver
{
public class PersonInfo
{
public string Name{get;set;}
public int Age{get;set;}
}
}
```
From a table Person that has columns Name and Age.
Are there any ready to use solutions for this?
I know I can implement this with T4 or Codesmith, but there should be somebody who already did it. | I found some nice T4 template I could use. Its from a project on codeplex.
[LINQ to SQL templates for T4](http://l2st4.codeplex.com/)
The template is hard to read an it took me a while to simplify it.
Before you can use it you have to download an include (CSharpDataClasses.tt ) from the project.
Here is my template ():
```
<# // L2ST4 - LINQ to SQL templates for T4 v0.82 - http://www.codeplex.com/l2st4
// Copyright (c) Microsoft Corporation. All rights reserved.
// This source code is made available under the terms of the Microsoft Public License (MS-PL)
#><#@ template language="C#v3.5" hostspecific="True"
#><#@ include file="L2ST4.ttinclude"
#><#@ output extension=".generated.cs"
#><# // Set options here
var options = new {
DbmlFileName = Host.TemplateFile.Replace(".tt",".dbml"), // Which DBML file to operate on (same filename as template)
SerializeDataContractSP1 = false, // Emit SP1 DataContract serializer attributes
FilePerEntity = true, // Put each class into a separate file
StoredProcedureConcurrency = false, // Table updates via an SP require @@rowcount to be returned to enable concurrency
EntityFilePath = Path.GetDirectoryName(Host.TemplateFile) // Where to put the files
};
var code = new CSharpCodeLanguage();
var data = new Data(options.DbmlFileName);
var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = options.EntityFilePath };
data.ContextNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedContextNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
data.EntityNamespace = (new string[] { manager.GetCustomToolNamespace(data.DbmlFileName), data.SpecifiedEntityNamespace, manager.DefaultProjectNamespace }).FirstOrDefault(s => !String.IsNullOrEmpty(s));
manager.StartHeader();
manager.EndHeader();
var tableOperations = new List<TableOperation>();
foreach(var table in data.Tables)
tableOperations.AddRange(table.Operations);
foreach(Table table in data.Tables)
foreach(OperationType operationType in Enum.GetValues(typeof(OperationType)))
if (!tableOperations.Any(o => (o.Table == table) && (o.Type == operationType))) {}
if (!String.IsNullOrEmpty(data.ContextNamespace)) {}
foreach(Table table in data.Tables) {
foreach(TableClass class1 in table.Classes) {
manager.StartBlock(Path.ChangeExtension(class1.Name + "Info" ,".cs"));
if (!String.IsNullOrEmpty(data.EntityNamespace)) {#>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace <#=data.EntityNamespace#>
{
<# }
#> <#=code.Format(class1.TypeAttributes)#> class <#=class1.Name#>Info
{
<# int dataMemberIndex = 1;
if (class1.Columns.Count > 0) {
#><# foreach(Column column in class1.Columns) {#>
private <#=code.Format(column.StorageType)#> <#= "_" + char.ToLower(column.Member[0]) + column.Member.Substring(1) #><# if (column.IsReadOnly) {#> = default(<#=code.Format(column.StorageType)#>)<#}#>;
<#=code.Format(column.MemberAttributes)#><#=code.Format(column.Type)#> <#=column.Member#>
{
get { return <#= "_" + char.ToLower(column.Member[0]) + column.Member.Substring(1) #>; }
set {<#= "_" + char.ToLower(column.Member[0]) + column.Member.Substring(1) #> = value;}
}
<# }
}
#>
}
}
<#
manager.EndBlock();
}
}
manager.StartFooter();
manager.EndFooter();
manager.Process(options.FilePerEntity);#>
``` | What about [Entity Framework](http://msdn.microsoft.com/en-us/library/bb399572.aspx)? | Generate entity class from database table | [
"",
"c#",
".net",
"t4",
""
] |
I'm trying to write a valid mysql statement that would allow me to update multiple columns in one record with values provided as python variables.
My statement would look like this:
```
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s" % (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update)
cursor.close ()
db.commit()
db.close()
```
While trying to execute the query, I keep receiving information that there is an error in my SQL syntax. I can't locate it though.
Could someone point out my mistake or show me how it should be written? | You are using string formatting, while what you SHOULD be doing is using a parametrized query. Do it like this:
```
cursor.execute("UPDATE table_name SET field1=%s, ..., field10=%s WHERE id=%s", (var1,... var10, id))
``` | Please, have these notes into consideration:
* you should make sure the user and password are correct
* The number of place holder must match the number of values
* the type of values you are using matches the column's type in your table
please try the following code:
```
db = MySQLdb.connect(host="localhost", user="user", passwd="password", db="dbname")
cursor = db.cursor()
sql_update = "UPDATE table_name SET field1=%s, field2=%s, field3=%s, field4=%s, field5=%s, field6=%s, field7=%s, field8=%s, field9=%s, field10=%s WHERE id=%s"
val = (var1, var2, var3, var4, var5, var6, var7, var8, var9, var10, id)
cursor.execute(sql_update, val)
db.commit()
cursor.close ()
db.close()
``` | PYTHON: Update MULTIPLE COLUMNS with python variables | [
"",
"python",
"mysql",
"variables",
""
] |
I know that 2d arrays are arrays of arrays. To get a row you can do:
```
rowArray = my2Darray[row]
```
Since each row can be a different size, I'm assuming it's not built in to get a column from a 2D array. It leads me to believe you'd have to do something like:
```
for(int row = 0; row < numRows; row++)
{
colArray[row] = m2Darray[row][columnOfInterest];
}
```
Is this correct? Is it the only way? | If you are locked down to using a 2d array, then yes, this is it afaik. However, a suggestion that may help you (if possible):
Wrap the array in a class that handles the column fetching.
Good luck. | Commons math has some tools you might want to check out:
```
double[][] data = new double[10][10];
BigMatrix matrix = MatrixUtils.createBigMatrix(data);
matrix.getColumnAsDoubleArray(0);
```
[Commons Math Library](http://commons.apache.org/math/ "Commons Math") | How to get a column from a 2D java array? | [
"",
"java",
"arrays",
"multidimensional-array",
""
] |
I'm interested in playing around with GUIs and I've been trying to set up Qt for Visual Studio 2008 and MinGW but have failed miserably—in that at times I'd compile the library and it still wouldn't work and others the compile would fail. Can anyone recommend a good guide to set up Qt (or another GUI toolkit if setting up Qt just doesn't work well for beginners). No preference for IDE really, just want to start coding already :)
**Edit** I tried both answers and they were both great, the QtCreator is a fast way to get started with Qt. And 20th Century Boy's blogpost was a thorough guide to setting up Qt with VS08 that I could even follow (answering the original question). Thanks and happy coding :) | I have covered Qt and VS 2008 integration in my blog. Have a look at it here...
<http://cplusplus-mortals.blogspot.com/2009/04/qt-part-3-configuration-for-visual.html> | [Qt Creator](http://www.qtsoftware.com/products/developer-tools) is probably the most straightforward way to get started with Qt. | Beginner's Guide to Setting Up Qt for C++ | [
"",
"c++",
"user-interface",
"qt",
"installation",
""
] |
The bus company I use runs an awful website ([Hebrew](http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=he&state=),[English](http://mslworld.egged.co.il/eggedtimetable/WebForms/wfrmMain.aspx?width=1024&company=1&language=en&state=)) which making a simple "From A to B timetable today" query a nightmare. I suspect they are trying to encourage the usage of the costly SMS query system.
I'm trying to harvest the entire timetable from the site, by submitting the query for every possible point to every possible point, which would sum to about 10k queries. The query result appears in a popup window. I'm quite new to web programming, but familiar with the basic aspects of python.
1. What's the most elegant way to parse the page, select a value fro a drop-down menu, and press "submit" using a script?
2. How do I give the program the contents of the new pop-up as input?
Thanks! | [Twill](http://twill.idyll.org/) is a simple scripting language for Web browsing. It happens to sport a [python api](http://twill.idyll.org/python-api.html).
> twill is essentially a thin shell around the mechanize package. All twill commands are implemented in the commands.py file, and pyparsing does the work of parsing the input and converting it into Python commands (see parse.py). Interactive shell work and readline support is implemented via the cmd module (from the standard Python library).
An example of "pressing" submit from the above linked doc:
```
from twill.commands import go, showforms, formclear, fv, submit
go('http://issola.caltech.edu/~t/qwsgi/qwsgi-demo.cgi/')
go('./widgets')
showforms()
formclear('1')
fv("1", "name", "test")
fv("1", "password", "testpass")
fv("1", "confirm", "yes")
showforms()
submit('0')
``` | I would suggest you use [mechanize](http://wwwsearch.sourceforge.net/mechanize/). Here's a code snippet from their page that shows how to submit a form :
```
import re
from mechanize import Browser
br = Browser()
br.open("http://www.example.com/")
# follow second link with element text matching regular expression
response1 = br.follow_link(text_regex=r"cheese\s*shop", nr=1)
assert br.viewing_html()
print br.title()
print response1.geturl()
print response1.info() # headers
print response1.read() # body
response1.close() # (shown for clarity; in fact Browser does this for you)
br.select_form(name="order")
# Browser passes through unknown attributes (including methods)
# to the selected HTMLForm (from ClientForm).
br["cheeses"] = ["mozzarella", "caerphilly"] # (the method here is __setitem__)
response2 = br.submit() # submit current form
# print currently selected form (don't call .submit() on this, use br.submit())
print br.form
``` | Automatically pressing a "submit" button using python | [
"",
"python",
"scripting",
"form-submit",
"data-harvest",
""
] |
In C++ you specify internal linkage by wrapping your class and function definitions inside an unnamed namespace. You can also explicitly instantiate templates, but to be standards conforming any explicit instantiations of the templates must occur in the same namespace. AFAICT this should compile, but GCC fails on it:
```
namespace foo {
template<class T>
class bar {};
}
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
```
With the error:
```
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace 'foo')
```
Which is interesting because the unnamed namespace should just be specifying linkage, not really functioning as a namespace, and the global namespace definitely encloses foo, since it encloses every namespace. But even this doesn't work!:
```
template<class T>
class bar {};
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
```
Which fails with the same error, just listing the global namespace instead:
```
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace '::')
```
:/ | An anonymous namespace is logically equivalent to
```
namespace _TU_specific_unique_generated_name
{
// ...
}
using namespace _TU_specific_unique_generated_name;
```
A namespace, anonymous or otherwise, has no effect on the linkage of its members. In particular members of an anonymous namespace do not magically get internal linkage. | First: You are explicitly instantiating a class template, you are not defining a new class template. What
```
template class bar<int>;
```
says is "please instantiate the class template bar for type int here". You cannot do that in another namespace, just as you cannot partially specialise a class template in another namespace. In particular, the template to be explicitly instantiated must have been defined, and in your example, there's no (anonymous namespace)::bar<>, only foo::bar<>.
Second: The anonymous namespace is a real namespace (it's distinct in every translation unit, though). It also doesn't magically change linkage. Everything declared inside namespace {} has still the default linkage, just like at any other namespace scope. IIRC, it was even added to allow for translation unit-private, yet external-linkage objects. | Why can't I explicitly instantiate a class template in an unnamed namespace if it was declared in another namespace? | [
"",
"c++",
"namespaces",
"global",
"linkage",
"unnamed-namespace",
""
] |
I'm trying to use the @Test(expected = RuntimeException.class) annotation in
order to test for an expected exception. My code is as follows:
```
@Test(expected = RuntimeException.class)
public void testSaveThrowsRuntimeException(){
User user = domain.save(null);
}
```
and my save method simple like this :
```
public User save(User newUser) {
if(newUser == null) {
throw new RuntimeException();
}
//saving code goes here
}
```
after debugging the code I found that code throwing the exception as expected but its getting eaten somewhere in between in spring framework classes.
I tried the same with old way (try catch block) but still I am not able to catch that exception in test and test keeps throwing errors in runafter method of Junit :
```
org.springframework.transaction.UnexpectedRollbackException: JTA transaction unexpectedly rolled back (maybe due to a timeout); nested exception is javax.transaction.RollbackException
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1031)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:709)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:678)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener$TransactionContext.endTransaction(TransactionalTestExecutionListener.java:504)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.endTransaction(TransactionalTestExecutionListener.java:277)
at org.springframework.test.context.transaction.TransactionalTestExecutionListener.afterTestMethod(TransactionalTestExecutionListener.java:170)
at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:344)
at org.springframework.test.context.junit4.SpringMethodRoadie.runAfters(SpringMethodRoadie.java:307)
at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:338)
at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:142)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:45)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
Caused by: javax.transaction.RollbackException
at org.objectweb.jotm.TransactionImpl.commit(TransactionImpl.java:245)
at org.objectweb.jotm.Current.commit(Current.java:488)
at org.springframework.transaction.jta.JtaTransactionManager.doCommit(JtaTransactionManager.java:1028)
... 23 more
```
And I am sure this is because of that RuntimeException I am throwing in save but not able catch it or pass the test with expected clause.
anybody have any idea whats going wrong? | Here's a work-around I found to with Junit 4.5 - separate the @Transactional and @ExpectedException into nested functions.
I guess the problem is something to do with the aop stuff spring puts around a @Transactional method.
```
@Test
@ExpectedException(org.springframework.dao.DataIntegrityViolationException.class)
public void Test10UniqueName()
{
DoTest10UniqueName();
}
@Transactional
public void DoTest10UniqueName()
{
final String NAME = "NAME";
ProductCategoryDAO dao = DAOFactory.getProductCategoryDAO();
ProductCategory test1 = new ProductCategory();
test1.setName(NAME);
ProductCategory test2 = new ProductCategory();
test2.setName(NAME);
dao.save(test1);
dao.save(test2);
}
``` | Turned out that my first answer was wrong. Both @Test(expected=...) and @ExpectedException work, but there is some incompability between [the Spring TestContext and Junit 4.5](http://jira.springframework.org/browse/SPR-5145). Using Junit 4.4 solved the problem for me. Finally. | Junit4 : expected=Exception not working with SPRING | [
"",
"java",
"spring",
"junit",
""
] |
I am attempting to clean up some dodgy xml attributes with Regular expressions.
My input string is this
```
<TD X:NUM class=xl101P24_2>I Want to send a FAX:but not </TD>
```
My intended output string is this
```
<TD class=xl101P24_2>I Want to send a FAX:but not </TD>
```
My code now looks like this
```
public static Regex regex1 = new Regex(
"<\\w*\\s*(X:\\w*)",
RegexOptions.IgnoreCase
| RegexOptions.CultureInvariant
| RegexOptions.IgnorePatternWhitespace
| RegexOptions.Compiled
);
public void doRegex()
{
string InputText = @"<TD X:NUM class=xl101P24_2>I Want to send a FAX:but not </TD>";
string result = regex1.Replace(InputText,"");
//result now = " class=xl101P24_2>I Want to send a FAX:but not </TD>"
}
```
so I need to do the replace but on only want to replace the numbered sub-match i.e. the 'X:NUM'. How do I do this???
Michael | You should use a look-ahead construct (*match prefix but exclude it*). This way, the first part (the "`<TD`" part) will not be matched and also not replaced:
```
"(?<=<\\w*)\\s*(X:\\w*)"
``` | Another way to acheive this is to use a replacement string to replace the whole match with only the first group ignoring the second group containing the crap.
```
string sResult = Regex.Replace(sInput, @"(<\w*\s*)(X:\w*\s*)", "$1")
```
This does not require any look-aheads and so should be quicker (a simple run showed it to be an order of magnitude quicker).
Changing the regex to have a + after the second group will remove all X: attributes, not only the first one (if this is relevant).
```
string sResult = Regex.Replace(sInput, @"(<\w*\s*)(X:\w*\s*)+", "$1")
``` | C# Regex Replace but Replace only a numbered Subgroup | [
"",
"c#",
"regex",
""
] |
I try to store the PHP floating point value 63.59072952118762 into a double precision column in postgres. Postgres stores the value as 63.59073. Does anyone know why? 8 byte should be more than enough for that value. I've tried with the data type numeric, which works when specifying the precision, but that shouldn't really be necessary.
**Update:** The same problem is present when trying to store 63.5907295, so the suggestion that something happens with the double before it's getting stored seems realistic.
**Update II (partly solved)**: The line where I assign the double parameter looks like this:
```
$stmt->bindParam(4, $this->latitude);
```
The thing I didn't know is that PDO defaults its param type to string. I changed it to PDO::PARAM INT in lack of a better alternative (PARAM DOUBLE was not an option), and got 10 digits precision in the double stored in postgres (some progress, at least). I've checked that the numeric type works well, so it seems that numeric is the way to go when using PDO and doubles that has to have a precision of more than 10 decimals.
Anyways, as someone has mentioned, I don't know if it's a must for me to have this kind of precision, but I think the problem in itself deserved to be investigated. | * How do you determine what PostgreSQL is storing?
* How do you send the data to PostgreSQL?
* How do you get the data back again?
* How do you display it?
* What type is the column in the database?
There are many, many places on the path between PHP and PostgreSQL where there could be confusion about how to represent the data.
---
It is important to explain how data is inserted into the DBMS. Using a literal value in the INSERT statement leads to a different set of problems from using bound parameters. If you wrote the value out in the SQL:
```
INSERT INTO SomeTable(SomeColumn) VALUES(63.xxxxxxxxx);
```
and the data was truncated, you'd have a problem down in PostgreSQL. If you bind the variable, you have to be sure to understand what PHP and the PDO PostgresSQL modules do with the value - is it sent as a double, or as a string, and which code deals with the conversion, and so on.
You run into analogous issues with Perl + DBI + DBD::YourDBMS (DBD::Pg in your case). | Consider using the [DECIMAL/NUMERIC](http://www.postgresql.org/docs/8.1/interactive/datatype.html#DATATYPE-NUMERIC-DECIMAL) type if you need that much precision | Why won't postgresql store my entire (PHP) float value? | [
"",
"php",
"postgresql",
"precision",
"math",
""
] |
Which of these two platforms/ecosystems are better for writing web applications/websites?
I am not interested in language features, but rather in the available tools like: Monorail, MVC.NET, NHibernate, etc. These kinds of tools are usually used to build modern, data-driven, AJAX enabled websites.
Assume the choice of platform is up to you. Operating system does not matter. | Neither. It all depends on your personal preference and what you're comfortable with. You'll get the job done with both.
**EDIT**
To more directly address the tools issue you raise after your edit, you can compare things like that fairly directly:
```
+--------------------+------------+-----------+
| Tool \ Environment | .NET | Java |
+--------------------+------------+-----------+
| Web framework | .NET MVC | Struts |
| ORM Mapper | NHibernate | Hibernate |
| Unit testing | NUnit | JUnit |
+--------------------+------------+-----------+
```
...and as a matter of fact, a lot of the tools (NHibernate and NUnit are both examples) originated in the Java world before being ported and utilized in .NET land. | It depends... which one are you most proficient at? That's the one. | Should I use Java or .NET for web development? | [
"",
"java",
".net",
""
] |
Here is a simple form I am using to send XML data in admin\_xml.php
```
<form name="review" action="admin_xml.php" method="post">
<textarea name="xml" cols="40" rows="10"></textarea>
<input class="submit" type="submit" value="Submit Request">
</form>
```
---
Here is the XML which I enter in order to retrieve the data from MySQL Database
```
<?xml version="1.0" encoding="UTF-8"?>
<GetOrdersIds>
<Credentials>
<Username>my_username</Username>
<Password>my_password</Password>
</Credentials>
<Criterions>
<OrderNumber></OrderNumber>
<StartDate>2009-01-01</StartDate>
<EndDate>2009-07-01</EndDate>
</Criterions>
</GetOrdersIds>
```
---
Here is the php code which extracts the tags from the xml:
```
<?php
$text_all = "<?xml version=\"1.0\"?>\r\n<GetOrdersIds version=\"1.0\">\r\n<Credentials>\r\n<Username>my_username</Username>\r\n<Password>my_password</Password>\r\n</Credentials>\r\n<Criterions>\r\n<OrderNumber></OrderNumber>\r\n<StartDate>2009-01-01</StartDate>\r\n<EndDate>2009-07-01</EndDate>\r\n</Criterions>\r\n</GetOrdersIds>";
$field = "Criterions";
$result = substr($text_all, strpos($text_all, "<".$field.">")+strlen("<".$field.">"), strpos($text_all, "</".$field.">")-strlen("<".$field.">")-strpos($text_all, "<".$field.">"));
?>
```
The result from the above php code is:
```
<OrderNumber></OrderNumber>
<StartDate>2009-01-01</StartDate>
<EndDate>2009-07-01</EndDate>
```
When the script is run, the php code goes through my mysql data, and extracts all orders between the Start Date and the End Date given above.
---
Is there a better way of improving the following php code, so that it performs the same function:
```
$result = substr($text_all, strpos($text_all, "<".$field.">")+strlen("<".$field.">"), strpos($text_all, "</".$field.">")-strlen("<".$field.">")-strpos($text_all, "<".$field.">"));
```
This is the code which searches through the xml data and retrieves all the tags.
UPDATE :
Can anyone list the $result code in SimpleXML? | Some temp vars will help and also make it easier to read.
```
$result = substr($text_all, strpos($text_all, "<".$field.">")+strlen("<".$field.">"), strpos($text_all, "</".$field.">")-strlen("<".$field.">")-strpos($text_all, "<".$field.">"));
```
Can be rewritten to.
```
$tagLen = strlen('<'.$field.'>');
$openTag = strpos($text_all, '<'.$field.'>');
$closeTag = strpos($text_all, '</'.$field.'>', $openTag);
$result = substr($text_all, $openTag + $tagLen, $closeTag - $tagLen - $openTag);
```
or use [SimpleXML](http://docs.php.net/simplexml)
```
$doc = simplexml_load_string($text_all);
echo $doc->Criterions->asXML();
```
If you want the individual values use this.
```
$doc = simplexml_load_string($text_all);
echo $doc->Criterions->OrderNumber;
echo $doc->Criterions->StartDate;
echo $doc->Criterions->EndDate;
```
if you want the element in XML then use asXML():
```
$doc = simplexml_load_string($text_all);
echo $doc->Criterions->OrderNumber->asXML();
echo $doc->Criterions->StartDate->asXML();
echo $doc->Criterions->EndDate->asXML();
``` | With [SimpleXML](http://docs.php.net/simplexml):
```
<?php
$xmlSTR = '<?xml version="1.0" encoding="UTF-8"?>
<GetOrdersIds>
<Credentials>
<Username>my_username</Username>
<Password>my_password</Password>
</Credentials>
<Criterions>
<OrderNumber></OrderNumber>
<StartDate>2009-01-01</StartDate>
<EndDate>2009-07-01</EndDate>
</Criterions>
</GetOrdersIds>';
$xml = new SimpleXMLElement($xmlSTR);
echo $xml->Credentials->Username;
//To see the entire structure print_r($xml); as php can access objects as arrays
``` | How to improve the following code in PHP | [
"",
"php",
"mysql",
"xml",
""
] |
Given this code:
```
var arrayStrings = new string[1000];
Parallel.ForEach<string>(arrayStrings, someString =>
{
DoSomething(someString);
});
```
Will all 1000 threads spawn almost simultaneously? | No, it won't start 1000 threads - yes, it will limit how many threads are used. Parallel Extensions uses an appropriate number of cores, based on how many you physically have *and* how many are already busy. It allocates work for each core and then uses a technique called *work stealing* to let each thread process its own queue efficiently and only need to do any expensive cross-thread access when it really needs to.
Have a look at the [PFX Team Blog](http://blogs.msdn.com/pfxteam/) for *loads* of information about how it allocates work and all kinds of other topics.
Note that in some cases you can specify the degree of parallelism you want, too. | On a single core machine... Parallel.ForEach partitions (chunks) of the collection it's working on between a number of threads, but that number is calculated based on an algorithm that takes into account and appears to continually monitor the work done by the threads it's allocating to the ForEach. So *if the body part of the ForEach calls out to long running IO-bound/blocking functions which would leave the thread waiting around, the algorithm will spawn up more threads and repartition the collection between them*. If the threads complete quickly and don't block on IO threads for example, such as simply calculating some numbers, *the algorithm will ramp up (or indeed down) the number of threads to a point where the algorithm considers optimum for throughput (average completion time of each iteration)*.
Basically the thread pool behind all the various Parallel library functions, will work out an optimum number of threads to use. The number of physical processor cores forms only part of the equation. There is NOT a simple one to one relationship between the number of cores and the number of threads spawned.
I don't find the documentation around the cancellation and handling of synchronizing threads very helpful. Hopefully MS can supply better examples in MSDN.
Don't forget, the body code must be written to run on multiple threads, along with all the usual thread safety considerations, the framework does not abstract that factor... yet. | Does Parallel.ForEach limit the number of active threads? | [
"",
"c#",
".net",
"multithreading",
"parallel-processing",
"parallel.foreach",
""
] |
I've been reading a little about encryption recently and am interested in protecting a licence file from tampering. Now this may not be the best way to do it, in which case I'm open to suggestions. But one way I was thinking of protecting it is to simply encrypt it.
However if I were to use encryption I'd need to use symmetric key, but this raises the question. If I store a key in the source code, with such tools as reflector, is it really worth it? It seems a fairly trivial task to obtain the initalization vector, salt, key etc and therefore break the encryption. Is there a way to protect a key in source? Or is this the completely wrong approach? | If you want to prevent tampering, you want signing/hashing, not encryption. Similar theory - but it means you can **validate** the file with the public key in the app, without requiring the private key that you keep on your server (and use to issue licenses).
Search for cryptographic hashing / signing. | Anything on the client side of the system can be compromised.
If you encrypt your file you must also somehow place the decryption key in your program. Anyone with a hex editor will be able to step through your code to find this key and then decrypt your license file and also create keys for your system.
Internet activation would be a good way to go, but I would see if you can find third parties to do this for you as they will have been down these roads before.
That said running your license file through some AES 256 encryption can't hurt :). | Encryption to protect files from changes | [
"",
"c#",
"encryption",
"reverse-engineering",
""
] |
What is the difference between the following statements?
Statement 1:
```
var=2**2*3
```
Statement 2:
```
var2=2*2*3
```
I see no difference.
This raises the following question.
Why is Statement 1 used if we can use Statement 2? | Try:
```
2**3*2
```
and
```
2*3*2
```
to see the difference.
`**` is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2. | Double stars (`**`) are exponentiation. So "2 times 2" and "2 to the power 2" are the same. Change the numbers and you'll see a difference. | What's the difference between "2*2" and "2**2" in Python? | [
"",
"python",
"syntax",
""
] |
I have a static util class that does some string manipulation on a bit sensitive data.
Prior to use of this class I need to initialize certain static variables with values, such as usernames/password, that I prefer to store in a `.properties` file.
I am not very familiar with how loading of `.properties` file work in Java, especially outside of \*Spring DI \*container.
Anyone can give me a hand/insight on how this can be done?
Thank you!
*Addition:* `.properties` file precise location is unknown, but it will be on the classpath. Sorta like `classpath:/my/folder/name/myproperties.propeties` | First, obtain an `InputStream` from which the properties are to be loaded. This can come from a number of locations, including some of the most likely:
* A [`FileInputStream`](http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html#FileInputStream(java.lang.String)), created with a file name that is hard-coded or specified via a [system property.](http://java.sun.com/javase/6/docs/api/java/lang/System.html#getProperty(java.lang.String,%20java.lang.String)) The name could be relative (to the current working directory of the Java process) or absolute.
* A resource file (a file on the classpath), obtained through a call to `getResourceAsStream` on the [`Class`](http://java.sun.com/javase/6/docs/api/java/lang/Class.html#getResourceAsStream(java.lang.String)) (relative to the class file) or [`ClassLoader`](http://java.sun.com/javase/6/docs/api/java/lang/ClassLoader.html#getResourceAsStream(java.lang.String)) (relative to the root of the class path). Note that these methods return null if the resource is missing, instead of raising an exception.
* A [`URL`](http://java.sun.com/javase/6/docs/api/java/net/URL.html#openStream()), which, like a file name, could be hard-coded or specified via a system property.
Then create a new `Properties` object, and pass the `InputStream` to its [`load()`](http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.InputStream)) method. Be sure to close the stream, regardless of any exceptions.
In a class initializer, checked exceptions like `IOException` must be handled. An unchecked exception can be thrown, which will prevent the class from being initialized. That, in turn, will usually prevent your application from running at all. In many applications, it might be desirable to use default properties instead, or fallback to another source of configuration, such as prompting a use in an interactive context.
Altogether, it might look something like this:
```
private static final String NAME = "my.properties";
private static final Properties config;
static {
Properties fallback = new Properties();
fallback.put("key", "default");
config = new Properties(fallback);
URL res = MyClass.getResource(NAME);
if (res == null) throw new UncheckedIOException(new FileNotFoundException(NAME));
URI uri;
try { uri = res.toURI(); }
catch (URISyntaxException ex) { throw new IllegalArgumentException(ex); }
try (InputStream is = Files.newInputStream(Paths.get(uri))) { config.load(is); }
catch (IOException ex) { throw new UncheckedIOException("Failed to load resource", ex); }
}
``` | 1. Check out [java.util.Properties](http://java.sun.com/javase/6/docs/api/java/util/Properties.html).
2. You can use a static initializer. So on the top of the class you can do:
```
static {
Properties props = new Properties();
InputStream steam = ...; // open the file
props.load(stream);
// process properties content
String username = props.getProperty("username");
}
``` | Load java properties inside static initializer block | [
"",
"java",
"properties",
""
] |
I'm testing CodeIgniter, and trying to create a simple blog. The video tutorial on the [CodeIgniter site](http://codeigniter.com/tutorials/watch/blog/) is nice, but very incomplete. I'm not too familiar with the MVC structure, and I am wondering exactly how a model is used. For instance, I'm currently doing the "admin" portion of my blog, which allows you to create, delete, and modify entries. The view only contains xhtml, and the controller takes care of the rest. What should be in the model? Does everything database related occur in the model (i.e. inserts, updates, selects, etc.)? | Depends who you ask.
Some people like to put as much as possible in the model (validation, data retrieval, etc), and have the controller just poke it to get the data it needs, which it then hands over to the view.
Think about it like this: if you have more than one controller accessing a single model, then shouldn't common things between them be in a common place (as long as that common thing actually has something to do with the model)? | The Model should contain everything database related, and perform all of the basic CRUD operations (Create, Get, Update, Delete).
The Controller should handle all communication between the model and the view. So for example, if you have a form for adding a new post, you should have a view for that form, which is called from a controller. The Controller would check to see if anything has been submitted, and if something has, call the create/insert method from the Post Model. | Blog in CodeIgniter : Where Does the Model start, and the Controller End? | [
"",
"php",
"model-view-controller",
"codeigniter",
""
] |
Forgive me if this is a naïve question, however I am at a loss today.
I have a simple division calculation such as follows:
```
double returnValue = (myObject.Value / 10);
```
Value is an int in the object.
I am getting a message that says Possible Loss of Fraction. However, when I change the double to an int, the message goes away.
Any thoughts on why this would happen? | When you divide two int's into a floating point value the fraction portion is lost. If you cast one of the items to a float, you won't get this error.
So for example turn 10 into a 10.0
```
double returnValue = (myObject.Value / 10.0);
``` | You're doing integer division if `myObject.Value` is an int, since both sides of the `/` are of integer type.
To do floating-point division, one of the numbers in the expression must be of floating-point type. That would be true if myObject.Value were a double, or any of the following:
```
double returnValue = myObject.Value / 10.0;
double returnValue = myObject.Value / 10d; //"d" is the double suffix
double returnValue = (double)myObject.Value / 10;
double returnValue = myObject.Value / (double)10;
``` | Possible Loss of Fraction | [
"",
"c#",
"math",
""
] |
I need to write the local time information , the exception message to a php log file. I don't know why I can't get the format correct. The script I use is this:
```
error_log('['.date("F j, Y, g:i a").']'.$msg." <br>", 3, $phperrorPath);
```
There are two problem with this:
1. The date is not written in local time, instead it's default to the GMT+0 time; I want to write the machine time information to the log
2. After the file is written, it's not break to another line.
How to modify this code? | Set your local time using [`date_default_timezone_set`](http://www.php.net/manual/en/function.date-default-timezone-set.php):
```
date_default_timezone_set('UTC');
```
Adding the e and O format parameters to the [`date`](http://php.net/manual/en/function.date.php) call will give you the timezone identifier and GMT offset:
```
date("F j, Y, g:i a e O")
```
Add a "\n" to the end of the string:
```
//I've left in the HTML line break
error_log('['.date("F j, Y, g:i a e O").']'.$msg."<br /> \n", 3, $phperrorPath);
```
Lines will not be concatenated when using "3" as the second argument to [`error_log`](http://php.net/manual/en/function.error-log.php), and using "0" will write the output to the default location specified in php.ini. "2" is no longer an option, so I *think* manually concatenating the line break is the way to go. See:
<http://php.net/manual/en/function.error-log.php>
Also, take a look at [localtime](http://php.net/manual/en/function.localtime.php) | As for "2" I suspect that is because you are using the HTML formatting line break instead of the file line break **\n**. Maybe that's worth a try. | Write to error log with local time information and a line break at the end | [
"",
"php",
""
] |
In general reflection in a base class can be put to some good and useful ends, but I have a case here where I'm between a rock and a hard place... Use Reflection, or expose public Factory classes when they really should be private semantically speaking (ie. not just anyone should be able to use them). I suppose some code is in order here:
```
public abstract class SingletonForm<TThis> : Form
where TThis : SingletonForm<TThis>
{
private static TThis m_singleton;
private static object m_lock = new object();
private static ISingletonFormFactory<TThis> m_factory;
protected SingletonForm() { }
public static TThis Singleton
{
get
{
lock (m_lock)
{
if (m_factory == null)
{
foreach (Type t in typeof(TThis).GetNestedTypes(BindingFlags.NonPublic))
{
foreach (Type i in t.GetInterfaces())
{
if (i == typeof(ISingletonFormFactory<TThis>))
m_factory = (ISingletonFormFactory<TThis>)Activator.CreateInstance(t);
}
}
if (m_factory == null)
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"{0} does not implement a nested ISingletonFormFactory<{0}>.",
typeof(TThis).ToString()));
}
if (m_singleton == null || m_singleton.IsDisposed)
{
m_singleton = m_factory.GetNew();
}
return m_singleton;
}
}
}
}
```
Now, this code works for me, but is it a horrible kludge and/or a really bad idea? The other option is passing in the Factory's type as a type paramater, but then due to visiblity limitations, the Factory class must be public which means anyone can call it to make instances when they shouldn't be. | When dealing with generics, you frequently have to use reflection. In that regard I think you're fine.
That said, I see two forms of code smell here. They may be due to code sanitation, however, so I'll just comment on them:
First, your static property is of a generic item. I'm 99.999% sure this will not even compile. If it does, it's bad form.
Second, you appear are returning a new instance for every call to `Bar`. This is also considered bad form for a getter. I would instead have a method called CreateBar() or something similar. | This situation is also better handled with custom attributes where you can explicitly define the type to use.
```
[AttributeUsage( AttributeTargets.Class, AllowMultiple = false )]
public sealed class SingletonFactoryAttribute : Attribute
{
public Type FactoryType{get;set;}
public SingletonFormAttribute( Type factoryType )
{
FactoryType = factoryType;
}
}
```
Your singleton property now becomes
```
public static TThis Singleton
{
get
{
lock (m_lock)
{
if (m_factory == null)
{
var attr = Attribute.GetCustomAttribute(
typeof( TThis ),
typeof( SingletonFactoryAttribute ) )
as SingletonFactoryAttribute;
if (attr == null)
throw new InvalidOperationException(string.Format(
CultureInfo.InvariantCulture,
"{0} does not have a SingletonFactoryAttribute.",
typeof(TThis).ToString()));
m_factory = Activator.CreateInstance( attr.FactoryType );
}
if (m_singleton == null || m_singleton.IsDisposed)
{
m_singleton = m_factory.GetNew();
}
return m_singleton;
}
}
}
``` | Is Reflection in a base class a bad design idea? | [
"",
"c#",
"reflection",
"abstract-class",
""
] |
i want to format date to string in hql select, for example i have purchasing data with transaction date in it:
```
class Purchase {
private Date datePurchase
}
```
and i want to select date in a certain format, for example yyyyMMdd, can i do that in hql?
actually i can iterate through all purchase data returned by query, and start to format the date using SimpleDateFormat, but i don't want do that, i want to do it in hql, is it posible?
fyi, i just want to return the id and date string only, not all Purchase field.
thak you all for any help. | You could use a [TypeConverter](http://i-proving.com/space/Technologies/Hibernate/User+Types+in+Hibernate) and return a string or use another getter where you would return the date in the appropriate format. | The date data will be returned to your application at instances of the Date class. Using the DateFormat classes you can format the date into any format you want.
It's not the database's job to prepare your data for presentation. | Format date in hql query | [
"",
"java",
"hibernate",
"hql",
""
] |
First of all, before I begin, I am using VC++ 2008 professional, running an Intel core2 on windows OS. I also know that this code will NEVER be executed on anything other than a core2/corei7 running Windows.
I have a while loop with 2 conditions that looks something like this:
note: this is a much simplified version.
```
while((a != b) && (array[a] < c))
```
If the first condition `(a != b)` generates a false, will the second condition even be evaluated? or will the loop just terminate right there?
I did a few tests and it seems that it is indeed true.
However, here is the catch. When and if first condition evaluates false, the second condition WILL generate an access violation if it is evaluated. However, from what i can see, once the first condition is evaluated as false, the program doesn't bother to evaluate the second condition and quits the loop, thus saving me.
The problem is that I can't quite get rid of the access violation problem without making my very nice and neat code suddenly blow up on me. However, due to the little "bug" (i know it's a compiler optimization, not a bug), I seem to be able to get away from it. I also know this is probably not good programming practice to do, but to be honest, in my situation, if it works, I'm already ahead of the game.
My question is, will this "bug" or programming malpractice come back and bite me some day? Even when considering that I tested the hell out of this section and WILL ONLY EVER USE IT THIS ONE TIME? | The second condition will not be evaluated unless the first one has been evaluated to true. You can count on this. Millions lines of code work because this is how C and C++ do short-curcuit logical expressions evaluation.
You can use it and count on it. If the first expression evaluates to false the second will not even *start* evaluating. | This is not a bug. C++ uses short-circuit evaluation, so the second condition will never be evaluated when the first condition is false. | Condition order in while loop | [
"",
"c++",
"loops",
"conditional-statements",
""
] |
i have a textbox associated with a calendar extender and a masked edit extender in a asp.net 3.5 project. i would like to clear the texbox when OnBlur...i have tried using the code below but it not working! any ideas guy?
```
document.getElementById('txtDtTo').value ="";
``` | There are many reported problems with the OnBlur event firing, the code to clear the text box looks fine. Why do you need it empty when it loses focus? You could use the OnChange event instead however if I understand your proposed logic correctly you'll always have an empty text box! | ```
$('#<%= txtDtTo.ClientID %>').val('');
``` | how to clear a textbox with calendar extender in javascript? | [
"",
"asp.net",
"javascript",
"textbox",
"calendarextender",
""
] |
I have a text file that looks a bit like:
```
random text random text, can be anything blabla %A blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
random text random text, %C can be anything blabla blabla
```
When I `readlines()` it in, it becomes a list of sentences. Now I want this list to be sorted by the letter after the `%`. So basically, when the sort is applied to the above, it should look like:
```
random text random text, can be anything blabla %A blabla
random text random text, %C can be anything blabla blabla
random text random text, can be anything blabla %D blabla
random text random text, can be anything blabla blabla %F
random text random text, can be anything blabla blabla
```
Is there a good way to do this, or will I have to break each string in to tubles, and then move the letters to a specific column, and then sort using `key=operator.itemgetter(col)`?
Thank you | ```
In [1]: def grp(pat, txt):
...: r = re.search(pat, txt)
...: return r.group(0) if r else '&'
In [2]: y
Out[2]:
['random text random text, can be anything blabla %A blabla',
'random text random text, can be anything blabla %D blabla',
'random text random text, can be anything blabla blabla %F',
'random text random text, can be anything blabla blabla',
'random text random text, %C can be anything blabla blabla']
In [3]: y.sort(key=lambda l: grp("%\w", l))
In [4]: y
Out[4]:
['random text random text, can be anything blabla %A blabla',
'random text random text, %C can be anything blabla blabla',
'random text random text, can be anything blabla %D blabla',
'random text random text, can be anything blabla blabla %F',
'random text random text, can be anything blabla blabla']
``` | what about this? hope this helps.
```
def k(line):
v = line.partition("%")[2]
v = v[0] if v else 'z' # here z stands for the max value
return v
print ''.join(sorted(open('data.txt', 'rb'), key = k))
``` | Sort a list of strings based on regular expression match | [
"",
"python",
"sorting",
""
] |
I am looking for the best or any way to set the Album Art of mp3s using PHP.
Suggestions? | Album art is a data frame identified as “Attached picture” due ID3v2 specification, and
getID3() now is only one way to write all possible data frames in ID3v2 with pure PHP.
Look at this source:
<http://getid3.sourceforge.net/source/write.id3v2.phps>
Search for this text in the source:
```
// 4.14 APIC Attached picture
```
there's a piece of code responsible for writing album art.
Another way, that seems to be not as slow as pure PHP, is to use some external application, that will be launched by PHP script. If your service designed to work under a high load, binary compiled tool will be a better solution. | A better (faster) way to do this would be through an external application and the PHP exec() function to fun a command. I would recommend [eyeD3](http://eyed3.nicfit.net/). | setting album art of a mp3 with php | [
"",
"php",
"id3",
""
] |
Im trying to write a single byte at a certain location in a file. This is what im using at the moment:
```
BinaryWriter bw = new BinaryWriter(File.Open(filename, FileMode.Open));
bw.BaseStream.Seek(0x6354C, SeekOrigin.Begin);
bw.Write(0xB0);
bw.Close();
```
The problem is that BinaryWriter.Write(args) writes a four-byte signed integer at the position. I wish to only write one byte at the particular location. And then later possibly two bytes else where, how I specify how many bytes to write? | There is absolutely no need to use a high-level BinaryWriter just to write a simple byte to a stream - It's more efficient and tidy just to do this:
```
Stream outStream = File.Open(filename, FileMode.Open);
outStream.Seek(0x6354C, SeekOrigin.Begin);
outStream.WriteByte(0xb0);
```
(In general you also shouldn't really Seek after attaching a BinaryWriter to your stream - the BinaryWriter should be in control of the stream, and changing things "behind its back" is a bit dirty) | change
```
bw.Write(0xB0);
```
to
```
bw.Write((byte)0xB0);
``` | C# How to write one byte at an offset? | [
"",
"c#",
"io",
"byte",
""
] |
Well, I am abit confuse using these \r,\n,\t etc things. Because I read online (php.net), it seems like works, but i try it, here is my simple code:
```
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo $str . $str2;
?>
```
But the outcome is "My name is jingle I am a boy"
Either I put the \r\n in the var or in the same line as echo, the outcome is the same. Anyone knows why? | Because you are outputting to a browser, you need to use a `<br />` instead, otherwise wrap your output in `<pre>` tags.
Try:
```
<?php
$str = "My name is jingle <br />";
$str2 = "I am a boy";
echo $str . $str2;
?>
```
Or:
```
<?php
$str = "My name is jingle \n\r";
$str2 = "I am a boy";
echo '<pre>' .$str . $str2 . '</pre>';
?>
```
Browsers will not `<pre>serve` non-HTML formatting unless made explicit using `<pre>` - they are interested only in HTML. | Well in your example you've got `\n\r` rather than `\r\n` - that's rarely a good idea.
Where are you seeing this outcome? In a web browser? In the source of a page, still in a web browser? What operating system are you using? All of these make a difference.
Different operating systems use different line terminators, and HTML/XML doesn't care much about line breaking, in that the line breaks in the source just mean "whitespace" (so you'll get a space between words, but not necessarily a line break). | PHP, why sometimes "\n or \r" works but sometimes doesnt? | [
"",
"php",
"string",
""
] |
Do you know an integrated tool that will generate the call graph of a function from Python sources? I need one that is consistent and can run on Windows OS. | You could try with [PyCallGraph](http://pycallgraph.slowchop.com/)
From its documentation:
> Python Call Graph works with Linux,
> Windows and Mac OS X.
Otherwise, you can directly do it on your own, using the traceback module:
```
import traceback
traceback.print_stack()
``` | PyCallGraph produces the dynamic graph resulting from the specific execution of a Python program and not the static graph extracted from the source code. Does anybody know of a tool which produces the static graph? | How can I extract the call graph of a function from Python source files? | [
"",
"python",
"windows",
"call-graph",
""
] |
I need to trigger a block of code after 20 minutes from the `AlarmManager` being set.
Can someone show me sample code on how to use an `AlarmManager` in ِAndroid?
I have been playing around with some code for a few days and it just won't work. | "Some sample code" is not that easy when it comes to `AlarmManager`.
Here is a snippet showing the setup of `AlarmManager`:
```
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
```
In this example, I am using `setRepeating()`. If you want a one-shot alarm, you would just use `set()`. Be sure to give the time for the alarm to start in the same time base as you use in the initial parameter to `set()`. In my example above, I am using `AlarmManager.ELAPSED_REALTIME_WAKEUP`, so my time base is `SystemClock.elapsedRealtime()`.
[Here is a larger sample project](https://github.com/commonsguy/cw-omnibus/tree/master/AlarmManager/Scheduled) showing this technique. | There are some good examples in the android sample code
> .\android-sdk\samples\android-10\ApiDemos\src\com\example\android\apis\app
The ones to check out are:
* AlarmController.java
* OneShotAlarm.java
First of, you need a receiver, something that can listen to your alarm when it is triggered. Add the following to your AndroidManifest.xml file
```
<receiver android:name=".MyAlarmReceiver" />
```
Then, create the following class
```
public class MyAlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
```
Then, to trigger an alarm, use the following (for instance in your main activity):
```
AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, 30);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(), pendingIntent);
```
.
---
Or, better yet, make a class that handles it all and use it like this
```
Bundle bundle = new Bundle();
// add extras here..
MyAlarm alarm = new MyAlarm(this, bundle, 30);
```
this way, you have it all in one place (don't forget to edit the `AndroidManifest.xml`)
```
public class MyAlarm extends BroadcastReceiver {
private final String REMINDER_BUNDLE = "MyReminderBundle";
// this constructor is called by the alarm manager.
public MyAlarm(){ }
// you can use this constructor to create the alarm.
// Just pass in the main activity as the context,
// any extras you'd like to get later when triggered
// and the timeout
public MyAlarm(Context context, Bundle extras, int timeoutInSeconds){
AlarmManager alarmMgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, MyAlarm.class);
intent.putExtra(REMINDER_BUNDLE, extras);
PendingIntent pendingIntent =
PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar time = Calendar.getInstance();
time.setTimeInMillis(System.currentTimeMillis());
time.add(Calendar.SECOND, timeoutInSeconds);
alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
pendingIntent);
}
@Override
public void onReceive(Context context, Intent intent) {
// here you can get the extras you passed in when creating the alarm
//intent.getBundleExtra(REMINDER_BUNDLE));
Toast.makeText(context, "Alarm went off", Toast.LENGTH_SHORT).show();
}
}
``` | Android: How to use AlarmManager | [
"",
"java",
"android",
"alarmmanager",
"android-alarms",
"android-1.5-cupcake",
""
] |
I have a single hexadecimal character, say
```
char c = 'A';
```
What's the proper way of converting that to its integer value
```
int value =??;
assert(a == 10);
```
Doesn't matter really for now if **a** is an int or a byte. | i don't see why you should have to convert to string... in fact this is what parseInt uses:
[public static int digit(char ch, int radix)](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Character.html#digit(char,%20int))
```
int hv = Character.digit(c,16);
if(hv<0)
//do something else because it's not hex then.
``` | ```
int value;
try {
value = Integer.parseInt(Character.toString(c), 16);
}
catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a hex char");
}
``` | Convert a single hex character to its byte value in java | [
"",
"java",
"hex",
""
] |
From a brief look using Reflector, it looks like `String.Substring()` allocates memory for each substring. Am I correct that this is the case? I thought that wouldn't be necessary since strings are immutable.
My underlying goal was to create a `IEnumerable<string> Split(this String, Char)` extension method that allocates no additional memory. | One reason why most languages with immutable strings create new substrings rather than refer into existing strings is because this will interfere with garbage collecting those strings later.
What happens if a string is used for its substring, but then the larger string becomes unreachable (except through the substring). The larger string will be uncollectable, because that would invalidate the substring. What seemed like a good way to save memory in the short term becomes a memory leak in the long term. | Not possible without poking around inside .net using String classes. You would have to pass around references to an array which was mutable and make sure no one screwed up.
.Net will create a new string every time you ask it to. Only exception to this is interned strings which are created by the compiler (and can be done by you) which are placed into memory once and then pointers are established to the string for memory and performance reasons. | Why does .NET create new substrings instead of pointing into existing strings? | [
"",
"c#",
".net",
"string",
"memory",
"string-interning",
""
] |
I have a class C. Class E extends it.
```
E e = new E();
C c = new C();
```
Why is
```
e = (E) c;
```
Upon further review: though numeric conversions have the same syntax as casting objects, some confusion arose. At any event, the above does not give a compilation, but rather a runtime error - so a class can be casted to subclass in some instances (otherwise the code would not compile). Any examples that anyone can give where the above works?
And also:
```
K extends M
K k = new K();
```
`((M) k).getClass()` gives `K`. Why is that? It was casted to the more general `M`!
Suppose I have a doIt() method implemented in both M and K. executing
```
((M) k).doIt();
```
gives M's or K's doIt()?
Thanks! | Consider a real-world example:
```
public class Dog extends Animal
```
All dogs are animals, but not all animals are dogs. Hence...
```
public class Cat extends Animal
```
Casting an Animal to a Dog can only be done if the Animal in question is indeed a Dog. Otherwise it would force the Universe to infer properties unique to a dog (wagging tail, barking, etc.) onto an Animal. That Animal might well be a Cat with properties unique to it (purring, rigorous regime of self-cleaning, etc.). If the cast is not possible then a ClassCastException is thrown at runtime.
Nobody wants a dog that purrs.
---
> ((M) k).getClass() gives K. Why is that? It was casted to the more general M!
You've casted k to M, but all classes have a getClass() method. k's class is always K, regardless of whather you cast its reference to M or not. If you cast a Dog to an Animal and ask it what animal it is it'll still answer that it's a dog.
In fact, casting to a superclass is redundant. A Dog already is an Animal and it has all the methods of an Animal as well as its own. Many Code Analysis tools such as FindBugs will notify you of redundant casts so you can remove them.
---
> Suppose I have a doIt() method implemented in both M and K. executing
>
> ((M) k).doIt();
>
> gives M's or K's doIt()?
K's doIt() for the same reasons as above. The cast operates on the reference; it doesn't transform an object to a different type.
---
> Can you give an example of when casting (Dog doggy = (Dog) myAnimal) makes sense?
Sure can. Imagine a method that receives a list of animals for processing. All the dogs need to be taken for a walk, and all the cats need to be played with using a bird-shaped toy. To do this we call the `takeForWalk()` method that only exists on Dog, or the `play()` method which only exists on Cat.
```
public void amuseAnimals( List<Animal> animals ) {
for ( Animal animal : animals ) {
if ( animal instanceof Dog ) {
Dog doggy = (Dog)animal;
doggy.takeForWalk( new WalkingRoute() );
} else if ( animal instanceof Cat ) {
Cat puss = (Cat)animal;
puss.play( new BirdShapedToy() );
}
}
}
``` | You can't cast objects in Java.
You can cast references in Java.
Casting a reference doesn't change anything about the object it refers to. It only produces a reference of a different type pointing to the same object as the initial reference.
Casting primitive values is different from casting references. In this case the values *do* change. | Question about Java polymorphism and casting | [
"",
"java",
"casting",
"polymorphism",
""
] |
I have a dynamic text file that picks content from a database according to the user's query. I have to write this content into a text file and zip it in a folder in a servlet. How should I do this? | Look at this example:
```
StringBuilder sb = new StringBuilder();
sb.append("Test String");
File f = new File("d:\\test.zip");
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(f));
ZipEntry e = new ZipEntry("mytext.txt");
out.putNextEntry(e);
byte[] data = sb.toString().getBytes();
out.write(data, 0, data.length);
out.closeEntry();
out.close();
```
This will create a zip in the root of `D:` named `test.zip` which will contain one single file called `mytext.txt`. Of course you can add more zip entries and also specify a subdirectory like this:
```
ZipEntry e = new ZipEntry("folderName/mytext.txt");
```
You can find more information about compression with Java [here](https://docs.oracle.com/javase/8/docs/api/java/util/zip/package-summary.html). | Java 7 has ZipFileSystem built in, that can be used to create, write and read file from zip file.
[Java Doc: ZipFileSystem Provider](https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html)
```
Map<String, String> env = new HashMap<>();
// Create the zip file if it doesn't exist
env.put("create", "true");
URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, env)) {
Path externalTxtFile = Paths.get("/codeSamples/zipfs/SomeTextFile.txt");
Path pathInZipfile = zipfs.getPath("/SomeTextFile.txt");
// Copy a file into the zip file
Files.copy(externalTxtFile, pathInZipfile, StandardCopyOption.REPLACE_EXISTING);
}
``` | How to create a zip file in Java | [
"",
"java",
"zip",
""
] |
I would like to share my Oracle SQL Developer configuration across my several computers that use Dropbox.
How can I do this? | Here's what I did.
```
#!/bin/bash
# share sqldeveloper config via dropbox
# this is for sqldeveloper 1.5.4, change your paths as necessary
# strace or dtruss sqldeveloper to see what config files are accessed
ITEMS="
o.ide.11.1.1.0.22.49.48/preferences.xml
o.ide.11.1.1.0.22.49.48/settings.xml
o.jdeveloper.cvs.11.1.1.0.22.49.48/preferences.xml
o.jdeveloper.subversion.11.1.1.0.22.49.48/preferences.xml
o.jdeveloper.vcs.11.1.1.0.22.49.48/preferences.xml
o.sqldeveloper.11.1.1.59.40/preferences.xml
o.sqldeveloper.11.1.1.59.40/product-preferences.xml
"
INST=~/Library/Application\ Support/SQL\ Developer/system1.5.4.59.40
DROP=~/Dropbox/Library/SQL\ Developer/system1.5.4.59.40
# note, you can zap your configuration if you are not careful.
# remove these exit lines when you're sure you understand what's
# going on.
exit
# copy from real folder to dropbox
for i in $ITEMS; do
echo uncomment to do this once to bootstrap your dropbox
#mkdir -p "`dirname "$DROP/$i":`"
#cp -p "$INST/$i" "$DROP/$i"
done
exit
# link from dropbox to real folder
for i in $ITEMS; do
rm "$INST/$i"
ln -s "$DROP/$i" "$INST/$i"
done
``` | In case anyone comes here looking for the location of user configured options like me, they are hiding here:
```
%appdata%\SQL Developer\
```
This is useful to know when copying your preferences to a new computer. If you are looking for the connection settings, search for `connections.xml` in that directory. There are also some other configuration files here that you may need:
```
sqldeveloper.conf – <sqldeveloper dir>\sqldeveloper\bin\
ide.conf – <sqldeveloper dir>\ide\bin\
```
This is for Oracle SQL Developer 3. | Oracle SQL Developer: sharing configuration via Dropbox | [
"",
"sql",
"oracle",
"oracle-sqldeveloper",
"dropbox",
""
] |
I'm trying to insert a new row, but if the key already exists, I want to update the row ONLY if a certain other value is in the table is different. Is this possible in a mysql query/statement?
My table consist of the following columns: hat, mittens, name, last\_update
hat+mittens make up the unique index (say the values for "hat" and "mittens" are colors)
Let's assume this is already in the table:
```
1. hat=blue mittens=green name=george last_update=tuesday
2. hat=red mittens=green name=bill last_update=monday
```
On a new key, I want to insert as usual. On duplicate key, I want to do an update ONLY IF the name changes, otherwise ignore. The reason for this is that I want to preserve the last\_update value (timestamp).
```
hat=yellow mittens=purple name=jimmy -- insert new row
hat=blue mittens=green name=george -- ignore
hat=blue mittens=green name=betty -- update row
```
Is this possible without using separate statements to first look up the existing row, compare values and then issue an update if necessary? If so, what would be the syntax?
---
Thanks for your responses. I tried all of them. Indeed, using just a simple UPDATE statement like
```
update tbl set name='george' where hat='blue' and mittens='green'
```
results in no rows being updated. But, using either
```
INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name='george';
```
or
```
INSERT INTO tbl (hat, mittens, name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name=CASE WHEN name <> VALUES(name) THEN VALUES(name) ELSE name END;
```
somehow results in the row being updated (and the timestamp changed).
FWIW, this is the table I'm using:
```
CREATE TABLE `tbl` (
`hat` varchar(11) default NULL,
`mittens` varchar(11) default NULL,
`name` varchar(11) default NULL,
`stamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
UNIQUE KEY `clothes` (`hat`,`mittens`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
```
MySQL is version 4.1.22 (perhaps this matters?)
Again, my appreciation for all of the replies. | You can use normal sql constructs in the [ON DUPLICATE KEY](http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html) syntax. So in order to do conditional updates during an insert you can do the following:
```
INSERT INTO tbl (hat, mittens, name)
VALUES ('yellow','purple','jimmy')
ON DUPLICATE KEY UPDATE name = CASE WHEN name <> VALUES(name)
THEN VALUES(name) ELSE name END;
```
This will change the value to what you provided to the insert statement when it's different from what's in the row and will set the value to be what it already is if it hasn't changed and will result in MySQL not doing anything to the row preserving the last\_update timestamp as Quassnoi pointed out.
If you wanted to make 100% sure that you weren't relying on the behavior of MySQL where it doesn't update a row if you set a value to itself you can do the following to force the timestamp:
```
INSERT INTO tbl (hat, mittens, name)
VALUES ('yellow','purple','jimmy')
ON DUPLICATE KEY UPDATE name = CASE WHEN name <> VALUES(name)
THEN VALUES(name) ELSE name END
, last_update = CASE WHEN name <> VALUES(name)
THEN now() ELSE last_update END;
```
This will only update the `last_update` to `now()` when the name has changed else it will tell MySQL to retain the value of `last_update`.
Also, in the ON DUPLICATE KEY section of the statement you can refer to the columns in the table by their name and you can get the values that you provided to the insert statement values section using the [VALUES(column\_name)](http://dev.mysql.com/doc/refman/5.1/en/miscellaneous-functions.html#function_values) function.
---
The following is a log that shows that the last statement provided works even on 4.1 where the others don't work due to a bug that was fixed in version 5.0.
```
C:\mysql\bin>mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1 to server version: 4.1.22-community
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> show databases;
+----------+
| Database |
+----------+
| mysql |
| test |
+----------+
2 rows in set (0.00 sec)
mysql> use test;
Database changed
mysql> show tables;
Empty set (0.00 sec)
mysql> CREATE TABLE `tbl` (
-> `hat` varchar(11) default NULL,
-> `mittens` varchar(11) default NULL,
-> `name` varchar(11) default NULL,
-> `stamp` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
-> UNIQUE KEY `clothes` (`hat`,`mittens`)
-> ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
Query OK, 0 rows affected (0.01 sec)
mysql> INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george');
Query OK, 1 row affected (0.00 sec)
mysql> select * from tbl;
+------+---------+--------+---------------------+
| hat | mittens | name | stamp |
+------+---------+--------+---------------------+
| blue | green | george | 2009-06-27 12:15:16 |
+------+---------+--------+---------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name='george';
Query OK, 2 rows affected (0.00 sec)
mysql> select * from tbl;
+------+---------+--------+---------------------+
| hat | mittens | name | stamp |
+------+---------+--------+---------------------+
| blue | green | george | 2009-06-27 12:15:30 |
+------+---------+--------+---------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO tbl (hat, mittens, name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name=CASE WHEN name <> VALUES(name) THEN VALUES(name) ELSE name END;
Query OK, 2 rows affected (0.00 sec)
mysql> select * from tbl;
+------+---------+--------+---------------------+
| hat | mittens | name | stamp |
+------+---------+--------+---------------------+
| blue | green | george | 2009-06-27 12:15:42 |
+------+---------+--------+---------------------+
1 row in set (0.00 sec)
mysql> INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george') ON DUPLICATE KEY UPDATE name = CASE WHEN name <> VALUES(name) THEN VALUES(name) ELSE name END, stamp = CASE WHEN name <> VALUES(name) THEN now() ELSE stamp END;
Query OK, 2 rows affected (0.00 sec)
mysql> select * from tbl;
+------+---------+--------+---------------------+
| hat | mittens | name | stamp |
+------+---------+--------+---------------------+
| blue | green | george | 2009-06-27 12:15:42 |
+------+---------+--------+---------------------+
1 row in set (0.00 sec)
mysql>
```
---
Let me know if you have any questions.
HTH,
-Dipin | You need [INSERT ... ON DUPLICATE KEY UPDATE](http://dev.mysql.com/doc/refman/5.1/en/insert-on-duplicate.html) syntax.
Your query would look like this:
```
INSERT INTO tbl (hat,mittens,name) VALUES ('blue','green','george')
ON DUPLICATE KEY UPDATE name='george';
```
If you had a record with blue/green/george for hat/mittens/name already, no UPDATE would actually be performed, and your timestamp would not be updated. If however you had a record with blue/green/betty, then 'betty' would be overwritten with 'george', and your timestamp would be updated. | conditional on duplicate key update | [
"",
"sql",
"mysql",
""
] |
I'm trying to batch insert data into SQL 2008 using `SqlBulkCopy`.
Here is my table:
```
IF OBJECT_ID(N'statement', N'U') IS NOT NULL
DROP TABLE [statement]
GO
CREATE TABLE [statement](
[ID] INT IDENTITY(1, 1) NOT NULL,
[date] DATE NOT NULL DEFAULT GETDATE(),
[amount] DECIMAL(14,2) NOT NULL,
CONSTRAINT [PK_statement] PRIMARY KEY CLUSTERED
(
[ID] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
```
Here is my code:
```
private DataTable GetTable()
{
var list = new List<DataColumn>();
list.Add(new DataColumn("amount", typeof(SqlDecimal)));
list.Add(new DataColumn("date", typeof(SqlDateTime)));
var table = new DataTable("statement");
table.Columns.AddRange(list.ToArray());
var row = table.NewRow();
row["amount"] = (SqlDecimal)myObj.Amount; // decimal Amount { get; set; }
row["date"] = (SqlDateTime)myObj.Date; // DateTime Date { get; set }
table.Rows.Add(row);
return table;
}
private void WriteData()
{
using (var bulk = new SqlBulkCopy(strConnection, SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls))
{
//table.Columns.ForEach(c => bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName)));
bulk.BatchSize = 25;
bulk.DestinationTableName = "statement";
bulk.WriteToServer(GetTable()); // a table from GetTable()
}
}
```
So I'm getting error:
> The given value of type `SqlDateTime` from the data source cannot be converted to type `date` of the specified target column.
Why?? How can I fix that? Help me, please! | Using your original table script, the following code works.
```
private static DataTable GetTable()
{
var list = new List<DataColumn>();
list.Add(new DataColumn("amount", typeof(Double)));
list.Add(new DataColumn("date", typeof(DateTime)));
var table = new DataTable("statement");
table.Columns.AddRange(list.ToArray());
var row = table.NewRow();
row["amount"] = 1.2d;
row["date"] = DateTime.Now.Date;
table.Rows.Add(row);
return table;
}
private static void WriteData()
{
string strConnection = "Server=(local);Database=ScratchDb;Trusted_Connection=True;";
using (var bulk = new SqlBulkCopy(strConnection, SqlBulkCopyOptions.KeepIdentity & SqlBulkCopyOptions.KeepNulls))
{
bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping("amount", "amount"));
bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping("date", "date"));
bulk.BatchSize = 25;
bulk.DestinationTableName = "statement";
bulk.WriteToServer(GetTable());
}
}
```
As already stated by Amal, you need the column mappings because of the Identity column. | The SQL Date type is different to the SQL DateTime type. I think the date column in your table needs to be of type DateTime, based on the way you are using it.
[SQL Date Type](http://msdn.microsoft.com/en-us/library/bb630352.aspx)
[SQL DateTime type](http://msdn.microsoft.com/en-us/library/ms187819.aspx)
Update:
I think Marc's answer should work, but you probably need to specify the SqlBulkCopyColumnMappings from your source DataTable to the destination, otherwise it might be getting the mapping wrong because the structure of your input table does not match the output table exactly ie order of date and row columns swapped.
eg
```
var amount = new SqlBulkCopyColumnMapping("amount", "amount");
var date = new SqlBulkCopyColumnMapping("date", "date");
bulk.ColumnMappings.Add(amount);
bulk.ColumnMappings.Add(date);
``` | Error inserting data using SqlBulkCopy | [
"",
"c#",
"sql-server",
"datetime",
"ado.net",
"sqlbulkcopy",
""
] |
I'm trying to set the CSS style of an object with the following:
```
document.getElementById(obj).style='font-weight:bold; color:#333;';
```
but it's not working. Does anyone have any idea why? | You need to set the underlying `cssText` of the style as folows:
```
document.getElementById('xx').style.cssText='font-weight:bold; color:#333;';
``` | you can separate
```
document.getElementById(obj).style.fontWeight='bold';
document.getElementById(obj).style.color='#333';
``` | Why doesn't the following Javascript code (to set CSS style) work? | [
"",
"javascript",
"css",
""
] |
I'm investigating encodings in PHP5. Is there some way to get a raw hex dump of a string? i.e. a hex representation of each of the bytes (not characters) in a string? | ```
echo bin2hex($string);
```
or:
```
for ($i = 0; $i < strlen($string); $i++) {
echo str_pad(dechex(ord($string[$i])), 2, '0', STR_PAD_LEFT);
}
```
`$string` is the variable which contains input. | For debugging work with binary protocols, I needed a more traditional HEX dump, so I wrote this function:
```
function hex_dump($data, $newline="\n")
{
static $from = '';
static $to = '';
static $width = 16; # number of bytes per line
static $pad = '.'; # padding for non-visible characters
if ($from==='')
{
for ($i=0; $i<=0xFF; $i++)
{
$from .= chr($i);
$to .= ($i >= 0x20 && $i <= 0x7E) ? chr($i) : $pad;
}
}
$hex = str_split(bin2hex($data), $width*2);
$chars = str_split(strtr($data, $from, $to), $width);
$offset = 0;
foreach ($hex as $i => $line)
{
echo sprintf('%6X',$offset).' : '.implode(' ', str_split($line,2)) . ' [' . $chars[$i] . ']' . $newline;
$offset += $width;
}
}
```
This produces a more traditional HEX dump, like this:
```
hex_dump($data);
=>
0 : 05 07 00 00 00 64 65 66 61 75 6c 74 40 00 00 00 [.....default@...]
10 : 31 42 38 43 39 44 30 34 46 34 33 36 31 33 38 33 [1B8C9D04F4361383]
20 : 46 34 36 32 32 46 33 39 32 46 44 38 43 33 42 30 [F4622F392FD8C3B0]
30 : 45 34 34 43 36 34 30 33 36 33 35 37 45 35 33 39 [E44C64036357E539]
40 : 43 43 38 44 35 31 34 42 44 36 39 39 46 30 31 34 [CC8D514BD699F014]
```
Note that non-visible characters are replaced with a period - you can change the number of bytes per line ($width) and padding character ($pad) to suit your needs. I included a $newline argument, so you can pass `"<br/>"` if you need to display the output in a browser. | How can I get a hex dump of a string in PHP? | [
"",
"php",
"string",
"encoding",
"character-encoding",
"hex",
""
] |
Python is the language I know the most, and strangely I still don't know why I'm typing "self" and not "this" like in Java or PHP.
I know that Python is older than Java, but I can't figure out where does this come from. Especially since you can use any name instead of "self": the program will work fine.
So where does this convention come from? | Smalltalk-80, released by Xerox in 1980, used `self`. Objective-C (early 1980s) layers Smalltalk features over C, so it uses `self` too. Modula-3 (1988), Python (late 1980s), and Ruby (mid 1990s) also follow this tradition.
C++, also dating from the early 1980s, chose `this` instead of `self`. Since Java was designed to be familiar to C/C++ developers, it uses `this` too.
Smalltalk uses the metaphor of objects sending messages to each other, so "self" just indicates that the object is sending a message to itself. | Check the [history of Python](http://python-history.blogspot.com/2009/02/adding-support-for-user-defined-classes.html) for user defined classes:
> Instead, one simply defines a function whose first argument corresponds to the instance, which by convention is named "self." For example:
```
def spam(self,y):
print self.x, y
```
> This approach resembles something I
> had seen in Modula-3, which had
> already provided me with the syntax
> for import and exception handling.
It's a choice as good as any other. You might ask why C++, Java, and C# chose "this" just as easily. | Why do pythonistas call the current reference "self" and not "this"? | [
"",
"python",
""
] |
So yea, I suck with regular expressions. Needs to be done with php. Thanks.
I need to be able to pull out "xx" (will always be 2 lowercase alphabetic chars) and "a12" (can be anything but will always be .php).
```
String:
http://foo.bar.com/some_directory/xx/a12.php?whatever=youwant
``` | Since he's looking for a **PHP** solution and not just PCRE, I think something like this might be a bit more comprehensive:
```
$src = 'http://foo.bar.com/some_directory/xx/a12.php?whatever=youwant';
preg_match( '/([a-z]{2})\/([^\/]+)\.php/', $src, $matches );
/* grab "xx" */
$first = $matches[1];
/* grab "a12" */
$second = $matches[2];
``` | ```
"([a-z]{2})\/([^/]+)\.php"
```
make sure you are capturing matches. xx will be in group 1, a12 will be in group 2 | Help with getting values through regex (php) | [
"",
"php",
"regex",
""
] |
Is it possible to access a parent member in a child class...
```
class MainClass {
class A { Whatever }
class B {
List<A> SubSetList;
public void AddNewItem(A NewItem) {
Check MasterListHere ????
}
}
List<A> MasterList;
}
```
So... my main class will have a master list. It will also have a bunch of instances of B. In each instance of B, I want to add new A's to the particular B, but only if they exist in the Master List. I toyed with making the MasterList static and it works ... until I have more than one instance of MainClass... which I will have.
I could pass a reference to MasterList to each instance of B, but I will eventually have multiple of these "MasterLists" and i don't want to have to pass lots of references if i don't have to. | You can use something like this:
```
class B {
private MainClass instance;
public B(MainClass instance)
{
this.instance = instance;
}
List SubSetList;
public void AddNewItem(A NewItem) {
Check MasterListHere ????
}
}
``` | In C# there is actually no implicit reference to the instance of the enclosing class, so you need to pass such a reference, and a typical way of doing this is through the nested class' constructor. | C# Nested Class Access Parent Member | [
"",
"c#",
"oop",
""
] |
Consider this at the windows commandline.
```
scriptA.py | scriptB.py
```
I want to send a dictionary object from scriptA.py to scriptB.py by pickle:ing it and sending it over a pipe. But I don't know how to accomplish this.
I've read some posts about this subject here, but usually there's answers along these line:
```
Popen( "scriptA.py"´, ..., and so on )
```
But I don't actually know the name of "scriptA.py". I just want to get hold of the ready pipe object and send/receive the databuffer.
I've tried sys.stdout/stdout, but I get file-descriptor errors and basically haven't tried that track very far.
The process is simple:
scriptA.py:
* (1) Pickle/Serialize dictionary into stringbuffer
* (2) Send stringbuffer over pipe
scriptB.py
* (3) Receive stringbuffer from pipe
* (4) Unpickle/Deserialize stringbuffer into dictionary | When you say this to a shell
```
scriptA.py | scriptB.py
```
The shell connects them with a pipe. You do NOTHING and it works perfectly.
Everything that `scriptA.py` writes to sys.stdout goes to `scriptB.py`
Everything that `scriptB.py` reads from sys.stdin came from `scriptA.py`
They're already connected.
So, how do you pass a dictionary from stdout in A to stdin in B?
1. [Pickle](http://docs.python.org/library/pickle.html). `scriptA.py` dumps the dictionary to stdout. `scriptB.py` loads the dictionary from stdin.
2. [JSON](http://docs.python.org/library/json.html). `scriptA.py` dumps the dictionary to stdout. `scriptB.py` loads the dictionary from stdin.
This is already built-in to Python and takes very, very little code.
In scriptA, `json.dump( {}, sys.stdout )` or `pickle.dump( {}, sys.stdout )`
In scriptB, `json.load( sys.stdin )` or `pickle.load( sys.stdin )` | The pipe just puts stdout of A to stdin of B.
A does:
```
import sys
sys.stdout.writelines(output)
```
B just does:
```
import sys
input = sys.stdin.readlines()
``` | Using pipes to communicate data between two anonymous python scripts | [
"",
"python",
"windows",
"pipe",
""
] |
I seem to remember that Regular Expressions in DotNet have a special mechanism that allows for the correct matching of nested structures, like the grouping in "`( (a ( ( c ) b ) ) ( d ) e )`".
What is the python equivalent of this feature? Can this be achieved using regular expressions with some workaround? (Though it seems to be the sort of problem that current implementations of regex aren't designed for) | You can't do this generally using Python regular expressions. (.NET regular expressions have been extended with "balancing groups" which is what allows nested matches.)
However, PyParsing is a very nice package for this type of thing:
```
from pyparsing import nestedExpr
data = "( (a ( ( c ) b ) ) ( d ) e )"
print nestedExpr().parseString(data).asList()
```
The output is:
```
[[['a', [['c'], 'b']], ['d'], 'e']]
```
More on PyParsing:
* <http://pyparsing.wikispaces.com/Documentation> | Regular expressions *cannot* parse nested structures. Nested structures are not regular, by definition. They cannot be constructed by a regular grammar, and they cannot be parsed by a finite state automaton (a regular expression can be seen as a shorthand notation for an FSA).
Today's "regex" engines sometimes support some limited "nesting" constructs, but from a technical standpoint, they shouldn't be called "regular" anymore. | Matching Nested Structures With Regular Expressions in Python | [
"",
"python",
"regex",
"recursive-regex",
""
] |
I have a "simple" task. I have an existing project with a web service written in C# which has a method that will send a huge XML file to the client. (This is a backup file of data stored on the server that needs to be sent somewhere else.) This service also had some additional authentication/authorization set up.
And I have an existing Delphi 2007 application for WIN32 which calls the web service to extract the XML data for further processing. It's a legacy system that runs without a .NET installation.
Only problem: the XML file is huge (at least 5 MB) and needs to be sent as a whole. Due to system requirements I cannot just split this up into multiple parts. And I'm not allowed to make major changes to either the C# or the Delphi code. (I can only change the method call on both client and server.) And I'm not allowed to spend more than 8 (work) hours to come up with a better solution or else things will just stay unchanged.
The modification I want to add is to compress the XML data (which reduces it to about 100 KB) and then send it to the client as a binary stream. The Delphi code should then accept this incoming stream and de compress the XML data again. Now, with a minimum of changes to the existing code, how should this be done?
(And yes, I wrote the original client and server in the past and it was never meant to send that much data at once. Unfortunately, the developer who took it over from me had other ideas, made several dumb changes, did more damage and left the company before my steel-tipped boot could connect to his behind so now I need to fix a few things. Fixing this web service has a very low priority compared to the other damage that needs to be restored.)
---
The server code is based on legacy ASMX stuff, the client code is the result of the Delphi SOAP import with some additional modifications.
The XML is a daily update for the 3000+ users which happens to be huge in it's current design. We're working on this but that takes time. There are more important items that need to be fixed first, but as I said, there's a small amount of time available to fix this problem quickly. | This sounds like a good candidate for an HttpHandler
My good links are on my work computer (I'll add them when I get to work), but you can look to see if it will be a good fit.
-- edit --
Here are the links...
<http://www.ddj.com/windows/184416694>
<http://visualstudiomagazine.com/articles/2006/08/01/create-dedicated-service-handlers.aspx?sc_lang=en&sc_mode=edit> | What is the problem with a 5MB file in a soap message? I have written a document server that runs over soap and this server has no problem with large files.
If the size is a problem for you I would just compress and decompress the xml data. This can easily be done with one of the many (free) available components for compression of a TStream descendant. | Sending a binary stream through SOAP | [
"",
"c#",
".net",
"delphi",
"winapi",
"soap",
""
] |
I can do this in C++ and Python, but I haven't quite figured it out on java.
My class has a 'MessageReceived' function that my network loop executes when a message comes in. I want the user to be able to write a method in their own class that they want to have run by MessageReceived, but I can't figure out how to pass and execute a method in Java. I can work around it by inheriting the class and overriding MessageReceived, but I'm hoping I can avoid forcing the user to do that. | You'd want the [Observer Pattern](http://en.wikipedia.org/wiki/Observer_pattern "Wikipedia Article") for allowing other objects to be notified when a message is received.
It's not clear what you're really asking or what problems you have. Is it with design, or is it with actually loading the classes written by the user, or dynamically configuration of the user classes, or something else ? | The easiest way would be to create an interface that defines the method to be called. That way you can always run the method via Reflection (since you know the method name).
What you are talking about is called "eval" and Java does not have the ability to perform eval like a functional language.
Stupid example using reflection:
```
String classname = "MyClass";
Class klass = Class.forName(classname);
Class paramTypes[] = {Integer.TYPE, Float.TYPE};
Method method = klass.getMethod("methodToRun", paramTypes);
method.invoke(new Integer(1), new Float(1.2f));
``` | Run user's Java method on network message | [
"",
"java",
""
] |
When running the following class the ExecutionService will often deadlock.
```
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorTest {
public static void main(final String[] args) throws InterruptedException {
final ExecutorService executor = Executors.newFixedThreadPool(10);
final HashMap<Object, Object> map = new HashMap<Object, Object>();
final Collection<Callable<Object>> actions = new ArrayList<Callable<Object>>();
int i = 0;
while (i++ < 1000) {
final Object o = new Object();
actions.add(new Callable<Object>() {
public Object call() throws Exception {
map.put(o, o);
return null;
}
});
actions.add(new Callable<Object>() {
public Object call() throws Exception {
map.put(new Object(), o);
return null;
}
});
actions.add(new Callable<Object>() {
public Object call() throws Exception {
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
iterator.next();
}
return null;
}
});
}
executor.invokeAll(actions);
System.exit(0);
}
}
```
So why does this happen? Or better yet - how can I write a test to ensure that implementations of an custom abstract map are thread safe? (Some implementations have multiple maps, another delegates to a cache implementation etc)
Some background:
this occurs under Java 1.6.0\_04 and 1.6.0\_07 on Windows. I know that the problem comes from sun.misc.Unsafe.park():
* I can reproduce the problem on my Core2 Duo 2.4Ghz laptop but not while running in debug
* I can debug on my Core2 Quad at work, but I've hung it over RDP, so won't be able to get
a stack trace until tomorrow
Most answers below are about the non-thread safety of HashMap, but I could find no locked threads in HashMap - it was all in the ExecutionService code (and Unsafe.park()). I shall closely examine the threads tomorrow.
All this because a custom abstract Map implementation was not thread-safe so I set about ensuring that all implementations would be thread-safe. In essence, I'm wanting to ensure that my understanding of ConcurrentHashMap etc are exactly what I expect, but have found the ExecutionService to be strangely lacking... | You're using an well-known not-thread-safe class and complaining about deadlock. I fail to see what the issue is here.
Also, how is the `ExecutionService`
```
strangely lacking
```
?
It's a common misconception that by using *e.g.* a `HashMap` you will at most get some stale data. See [a beautiful race condition](http://mailinator.blogspot.com/2009/06/beautiful-race-condition.html) about how you can blow up your JVM by doing just that.
Understanding why this happens is a very tricky process and requires knowledge of the internals of both the JVM and the class libraries.
As for the ConcurrentHashMap, just read the [javadoc](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ConcurrentHashMap.html) - it should clarify your questions. If not, take a look at [Java Concurrency in Practice](http://jcip.net/).
---
**Update:**
I managed to reproduce your situation, but it's not a deadlock. One of the `actions` never completes execution. The stack trace is:
```
"pool-1-thread-3" prio=10 tid=0x08110000 nid=0x22f8 runnable [0x805b0000]
java.lang.Thread.State: RUNNABLE
at ExecutorTest$3.call(ExecutorTest.java:36)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:619)
```
It looks like the exact case I linked to - the HashMap gets resized and due to the internal mechanics of resizing the iterator gets stuck in an infinite loop.
When this happens, `invokeAll` never returns and the program hangs. But it's neither a deadlock, nor a livelock, but a *race condition*. | What do you understand by deadlock?
There are at least two problems with the code. The `HashMap` is used from multiple threads simultaneously and so can get into an infinite loop. You are iterating the the entry set whilst potentially changing the underlying data structure (even if each individual operation was synchronized `hasNext`/`next` would not be atomic).
Also note that the versions of 1.6.0 up to date with the latest Synhronized Security Release (SSR) are 1.6.0\_13 and 1.6.0\_14. | Why does ExecutorService deadlock when performing HashMap operations? | [
"",
"java",
"concurrency",
"hashmap",
""
] |
Is there a way to find ILDASM.exe from [Visual Studio 2008](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2008)?
I know the location "C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin", but I want it through Visual Studio 2008. | I'm not sure what you mean by "wanting it through Visual Studio", but you can easily add it to the Visual Studio Tools menu with the "Tools `->` External Tools" dialog. | If you have the SDK:
```
C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin
```
Personally, though, I'd use [.NET Reflector](http://en.wikipedia.org/wiki/.NET_Reflector) instead...
I tend to associate this with bin/exe via the "Open With..." dialog in the [Solution Explorer](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Other_tools); add it to that, job done. | ILDASM.exe through Visual Studio 2008 | [
"",
"c#",
"visual-studio-2008",
""
] |
Can I use `yield return` when the return type is an `IGrouping<TKey, TElement>` or an `IDictionary<TKey, TValue>`? | `yield return` works for exactly 4 cases:
* `IEnumerable`
* `IEnumerable<T>`
* `IEnumerator`
* `IEnumerator<T>`
This is because it has to build a state machine internally; a dictionary (etc) wouldn't be possible with this. You can of course just `return` a suitable type instead. | You could however return `IEnumerable<KeyValuePair<K,V>>` that would be similar to a dictionary. You would then yield return KeyValuePairs. You could even wrap this with another method that creates a dictionary out of the return. The only thing the first method would not guarantee is uniqueness in the keys. | yield return works only for IEnumerable<T>? | [
"",
"c#",
".net",
"ienumerable",
""
] |
I have a table with 5 string columns, all can be NULLs. After I read the data from this table, I want to convert any null values into empty strings. The reason is that I need to compare these columns with columns in another table of the same schema (using conditional split), and null values would cause the comparison to evaluate to NULL.
Is there any functionality in SSIS that allows me to convert NULL's to empty strings, or just not having to deal with NULL's at all? | You can use a Derived Column transform. I don't have VS open now, but you'd use something like:
```
IIF(ISNULL(column)?"":column)
```
as the expression, and have it replace the original column.
---
**UPDATE**: As suggested below, the `IIF` should be removed.
```
ISNULL(column)?"":column
``` | The correct syntax is (ISNULL(column)?"":column) without the IIF | SSIS Null Value Questions | [
"",
"sql",
"sql-server",
"ssis",
""
] |
With regards this example from Code Complete:
```
Comparison Compare(int value1, int value2)
{
if ( value1 < value2 )
return Comparison_LessThan;
else if ( value1 > value2 )
return Comparison_GreaterThan;
else
return Comparison_Equal;
}
```
You could also write this as:
```
Comparison Compare(int value1, int value2)
{
if ( value1 < value2 )
return Comparison_LessThan;
if ( value1 > value2 )
return Comparison_GreaterThan;
return Comparison_Equal;
}
```
Which is more optimal though? (readability, etc aside) | Readability aside, the compiler should be smart enough to generate identical code for both cases. | "Readability, etc aside" I'd expect the compiler to produce identical code from each of them.
You can test that though, if you like: your C++ compiler probably has an option to generate a listing file, so you can see the assembly/opcodes generated from each version ... or, you can see the assembly/opcodes by using your debugger to inspect the code (after you start the executable). | if - else vs if and returns revisited (not asking about multiple returns ok or not) | [
"",
"c++",
""
] |
I have two database one with relationship(no data) and another with out Relationship (with data)
and i want to insert data from one database to another database
i am not able import data i got the error for forgien key.
Is there any way for this ? | You could disable all the foreign key constraints on the database, import your data and then re-apply the constraints.
[Here's away of removing all the constraints](https://stackoverflow.com/questions/159038/can-foreign-key-constraints-be-temporarily-disabled-using-tsql) | You need to copy the data over in the correct order, starting with data at the bottom of the "tree".
e.g.
TableA, TableB, TableC
If TableA references a record in TableB which in turn references a record in TableC then you should import the data in this order:
1) TableC
2) TableB
3) TableA | Database Relationship | [
"",
"sql",
"sql-server",
""
] |
```
<input type="button" value="Back" onClick="window.navigate('http://www.google.com')">
```
This works on IE8, but not firefox or opera. Anyone know why and how to fix it? | If you check [the documentation for that method](http://msdn.microsoft.com/en-us/library/ms536638(VS.85).aspx), you will see the quite common:
*There is no public standard that applies to this method.*
This means that it's a non-standard feature that most likely only works in Internet Explorer.
This will work:
```
<input type="button" value="Back" onclick="window.location.href='http://www.google.com';">
```
If you are using XHTML:
```
<input type="button" value="Back" onclick="window.location.href='http://www.google.com';" />
``` | .navigate() only works in IE.
Try setting the window.location.
```
window.location.href = 'http://www.google.com'
``` | button javascript works on IE but not firefox window.navigate() | [
"",
"javascript",
"html",
"internet-explorer-8",
""
] |
How can I prevent the firing of multiple events of the same kind triggered by a single action?
For example, I have a `ListView` containing some items. When I select or deselect all items, the `SelectedIndexChanged` event is fired once for each item. Rather, I would like to receive a single event indication the user's action (selection/deselection of items), regardless of the number of items.
Is there any way to achieve this? | You can't change the `ListView` code, and subclassing it doesn't provide many options.
I would suggest that you simply add a small delay (200ms or similar) to your code - i.e. you only do the calculation a little while after the last update. Something like:
```
using System;
using System.Windows.Forms;
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
ListView list;
TextBox txt;
Timer tmr = new Timer();
tmr.Interval = 200;
Form form = new Form {
Controls = {
(txt = new TextBox { Dock = DockStyle.Fill, Multiline = true}),
(list = new ListView { Dock = DockStyle.Right, View = View.List,
Items = { "abc", "def" , "ghi", "jkl", "mno" , "pqr"}})
}
};
list.SelectedIndexChanged += delegate {
tmr.Stop();
tmr.Start();
};
tmr.Tick += delegate {
tmr.Stop();
txt.Text += "do work on " + list.SelectedItems.Count + " items"
+ Environment.NewLine;
};
Application.Run(form);
}
}
``` | Only by by coming at the problem from a slightly different direction. E.g. subscribe loss of focus.
In the end, the application or runtime cannot raise an event on "all selection changes done" without actually using something else because there is no way for the application to predict whether the user will perform another click on the control while it retains focus.
Even using focus, the user could switch back to that control. | Prevent events from firing multiple times from single action | [
"",
"c#",
"winforms",
"events",
""
] |
I need to do a sort of "timeout" or pause in my method for 10 seconds (10000 milliseconds), but I'm not sure if the following would work as i do not have multi-threading.
```
Thread.Sleep(10000);
```
I will try to use that current code, but I would appreciate if someone could explain the best and correct way of doing this, especially if the above code does not work properly. Thanks!
**UPDATE**: This program is actually a console application that in the function in question is doing many HTTPWebRequests to one server, so I wish to delay them for a specified amount of milliseconds. Thus, no callback is required - all that is needed is an "unconditional pause" - basically just the whole thing stops for 10 seconds and then keeps going. I'm pleased that C# still considers this as a thread, so Thread.Sleep(...) would work. Thanks everybody! | You may not have *multi*-threading, but you're still executing within a thread: all code executes in a thread.
Calling `Thread.Sleep` will indeed pause the current thread. Do you really want it to unconditionally pause for 10 seconds, or do you want to be able to be "woken up" by something else happening? If you're only actually using one thread, calling `Sleep` may well be the best way forward, but it will depend on the situation.
In particular, if you're writing a GUI app you *don't* want to use `Thread.Sleep` from the UI thread, as otherwise your whole app will become unresponsive for 10 seconds.
If you could give more information about your application, that would help us to advise you better. | Thread.Sleep is fine, and AFAIK the proper way. Even if you are not Multithreaded: There is always at least one Thread, and if you send that to sleep, it sleeps.
Another (**bad**) way [is a spinlock](http://en.wikipedia.org/wiki/Spinlock), something like:
```
// Do never ever use this
private void DoNothing(){ }
private void KillCPU()
{
DateTime target = DateTime.Now.AddSeconds(10);
while(DateTime.Now < target) DoNothing();
DoStuffAfterWaiting10Seconds();
}
```
This is sadly still being used by people and while it will halt your program for 10 seconds, it will run at 100% CPU Utilization (Well, on Multi-Core systems it's one core). | Pausing a method for set # of milliseconds | [
"",
"c#",
"multithreading",
"timeout",
""
] |
I am using Sql Server 2008. My Stored Procedure accepts almost 150 parameters. Is there anything wrong with that performance-wise? | Nothing wrong performance wise but it smells as something that could be better done with dynamic SQL. Hard to tell without seeing the code. | when you are using SQL Server 2008 you can use the new Table parameter.
If the parameters are the same, you can easily use the table parameter.
Here is link to the [MSDN](http://msdn.microsoft.com/en-us/library/bb675163.aspx).
Here is [another link](http://blogs.microsoft.co.il/blogs/bursteg/archive/2007/12/02/sql-server-2008-table-valued-parameters.aspx), a bit more explained
Enjoy. | Sql Stored Procedure With a Lot of Parameters | [
"",
"sql",
"sql-server-2008",
"stored-procedures",
""
] |
UPDATE1: I have reinstalled Visual Studio and I am still having this problem. My guess is there is a problem with my environment.
Update2: Diving in.
I attached windbg to devenv and set a breakpoint in windbg for msenv!\_tailMerge\_WINMM\_dll and traced through.
This is trying to load winmm.dll using the LoadLibrary API. I can see that LoadLibrary is failing and GetLastError is returning 5 which is "access denied".
now, why would vs be denied access to winmm.dll?
---Begin Original---
I am currently having a serious issue with Visual Studio 2005 SP1 Intellisense in C++. I have an all native solution with on project. Whenever I, or the editor, attempt to invoke intellisense auto-complete pow, Visual Studio crashes. I even tried this with a brand new console app. `Ctrl` + `Space` in the empty main and Visual Studio crashes.
I googled for help on this but to no avail. I have tried deleting the ncb file but no luck on that front either.
I am currently working with Intellisense turned off as shown in this article:
[Visual Studio 2005 - 'Updating IntelliSense' hang-up](https://stackoverflow.com/questions/69729/visual-studio-2005-updating-intellisense-hang-up)
And I have no crashes, but it sure would be nice to have intellisense back
Call stack from a crash dump.
```
7c812a6b kernel32!RaiseException+0x53
502717a6 msenv!__delayLoadHelper2+0x139
50675186 msenv!_tailMerge_WINMM_dll+0xd
505ac3c3 msenv!CTextViewIntellisenseHost::UpdateCompletionStatus+0x1a7
505acb50 msenv!CEditView::UpdateCompletionStatus+0x30
505dcfad msenv!CEditView::CViewInterfaceWrapper::UpdateCompletionStatus+0x2a
02ae47fc vcpkg!CCompletionList::DoCompletion+0x444
02ade2ce vcpkg!CAutoComplete::PostProcess+0x240
02ade07f vcpkg!CAutoComplete::OnACParseDone+0x3e
02adac2d vcpkg!CMemberListWorkItem::OnCompleted+0x9d
029eb4e3 vcpkg!CWorkItem::ProcessPendingWorkItemCompletedCalls+0x117
029f8b4f vcpkg!CParserManager::OnIdle+0x183
0299961a vcpkg!CVCPackage::OnIdle+0x48
5014b288 msenv!ATL::CComAggObject<CTextBuffer>::QueryInterface+0x43
5a9d2394 VCProject!ATL::CComPtr<IOleInPlaceFrame>::~CComPtr<IOleInPlaceFrame>+0x24
5a9d2880 VCProject!ATL::CComObject<CVCArchy>::Release+0x10
774fd420 ole32!CRetailMalloc_GetSize+0x21
5009422b msenv!CMsoCMHandler::FContinueIdle+0x23
5009422b msenv!CMsoCMHandler::FContinueIdle+0x23
``` | What a bizarre problem.
I finally figured it out using procmon from sysinternals:
<http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx>
My sounds were somehow changed to windows default sounds after a recent trip to IT. This caused visual studio to play a clicking sound when intellisense happens. In order to play this sound winmm.dll must be loaded up, which is located c:\windows\system32\winmm.dll.
I suppose through debugging foray winmm.dll symbols were downloaded to a **FOLDER** called C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\winmm.dll. Of course this folder looked mighty tasty to Visual Studio, so when it tried to load the winmm.dll folder as a dll file POW!!!
I deleted the folder, and some other .dll folders :) and all is well.
Thanks for your help. | I would try the following set of steps to try and fix the problem
* Reset All Settings: Tools -> Import / Export Settings -> Reset All Settings
* Delete HKCU:\Software\Micosoft\VisualStudio\9.0 and then restart VS
* Repair the VS installation through Add Remove Programs
* Disable all 3rd party plugins | Intellisense auto-complete is causing VC++ in Visual Studio 2005 SP1 to crash | [
"",
"c++",
"visual-studio",
"visual-studio-2005",
"intellisense",
""
] |
I've got a rather large SQL Server 2005 database that is under constant development. Every so often, I either get a new developer or need to deploy wide-scale schema changes to the production server.
My main concern is deploying schema + data updates to developer machines from the "master" development copy.
Is there some built-in functionality or tools for publishing schema + data in such a fashion? I'd like it to take as little time as possible. Can it be done from within SSMS?
Thanks in advance for your time | I suggest using RedGate's tools (this is not advertisment, but real life experience with them) that can deploy schema changes and/or data:
* SQL Compare for schema changes
* SQL Data Compare for data changes
I used these tools in the past (others as well) and they really helped with development staging process. These tools aren't free but their price is more than acceptable for any development team.
Check [RedGate web site](http://www.redgate.com) | I know this was answered ages ago but check out
<http://en.wikipedia.org/wiki/Microsoft_SQL_Server_Compare_Tools>
It shows a number of free and paid compare tools.
For example a free tool listed is SQL Server Compare by Yes Soft
<http://www.yessoft.com/software/sqlservercompare/sqlservercompare.htm>
[](https://i.stack.imgur.com/as1Op.jpg)
(source: [yessoft.com](http://www.yessoft.com/software/sqlservercompare/screenshot1.jpg))
> Information Provided on the site:
> -List of free tools
> -List of paid tools
> -Features of the tools: Compare, Generate Sync Script, Synchronize,
> Licensing
**Upside:** 5 free tools are listed, 21 paid tools listed.
**Downside:** It is wikipedia. And the links seems to point to wikipedia pages instead of the actual homepages but if you google you will find them. | SQL Server 2005 - Syncing development/production databases | [
"",
"sql",
"sql-server",
"sql-server-2005",
"synchronization",
""
] |
I’m used to having try/catch blocks in every method. The reason for this is so that I can catch every exception at the point of infraction and log it. I understand, from my reading and conversations with others, that this isn’t a popular view. One should only catch what one is prepared to handle. However, if I don’t catch at the point of infraction, then it would be possible to never log that infraction and know about it. Note: When I do catch and don’t handle, I still throw. This allows me to let the exception propagate to something that will handle it, yet still let me log it at the point of infraction.
So... How does one avoid try/catch in every method, yet still log the error at the point at which it occurred? | No, don't catch everything. Exceptions propagate higher up on the stack. All you have to do is make sure that the exception is caught before it gets to the top of the stack.
This means, for instance, that you should surround the code of an event handler with a try/catch block. An event handler may be the "top of the stack". Same for a ThreadStart handler or a callback from an asynchronous method.
You also want to catch exceptions on layer boundaries, though in that case, you might just want to wrap the exception in a layer-specific exception.
In the case of ASP.NET, you may decide to allow ASP.NET Health Monitoring to log the exception for you.
But you certainly don't ever need to catch exceptions in every method. That's a major anti-pattern. I would loudly object to you checking in code with that kind of exception handling. | You can see everything at stack trace - no need to try/catch every method.
Stick to few rules:
1. Use try/catch only if you want to use a custom exception type
2. Define a new exception type only if upper levels needs to know that
3. Try/catch at top level instead of doing that for each method | General Exception Handling Strategy for .NET | [
"",
"c#",
".net",
"exception",
"exception-logging",
""
] |
Can anyone explain the following PHP Code ?
```
function get_param($param_name, $param_type = 0)
{
global $HTTP_POST_VARS, $HTTP_GET_VARS;
$param_value = "";
if (isset($_POST)) {
if (isset($_POST[$param_name]) && $param_type != GET)
$param_value = $_POST[$param_name];
elseif (isset($_GET[$param_name]) && $param_type != POST)
$param_value = $_GET[$param_name];
} else {
if (isset($HTTP_POST_VARS[$param_name]) && $param_type != GET)
$param_value = $HTTP_POST_VARS[$param_name];
elseif (isset($HTTP_GET_VARS[$param_name]) && $param_type != POST)
$param_value = $HTTP_GET_VARS[$param_name];
}
return strip($param_value);
}
function strip($value)
{
if (get_magic_quotes_gpc() == 0) {
return $value;
} else {
return stripslashes($value);
}
}
```
---
**UPDATE**
It is used like this:
```
$xml = get_param('xml');
``` | The code gets the value from the get and post data arrays. It also strips slashes on php installations that have magic quotes enabled. It looks like the function is made for backwards compatibility with older version of PHP. I wouldn't use this unless you are required to support older versions of PHP.
You don't need to make any changes for this to work in PHP 5, however I would just do the following:
For Get data:
```
if(isset($_GET['param_name'])){
// What ever you want to do with the value
}
```
For Post data:
```
if(isset($_POST['param_name'])){
// What ever you want to do with the value
}
```
You should also read up on [Magic Quotes](http://ca.php.net/manual/en/info.configuration.php#ini.magic-quotes-gpc) since it was not deprecated till PHP 5.3.0 and you may need to be concerned about it.
The updated function could also be written as:
```
function get_param($param_name, $param_type = 0)
{
$param_value = "";
if (isset($_POST[$param_name]) && $param_type != GET){
$param_value = $_POST[$param_name];
}
elseif (isset($_GET[$param_name]) && $param_type != POST){
$param_value = $_GET[$param_name];
}
return strip($param_value);
}
```
Strip can be left alone. | ```
function get_param($param_name, $param_type = 0)
```
This returns a parameter value, with a given type, POST, or GET, *which is optional*. The value is stripped of slashes.
```
function strip($value)
```
This returns the parameter without slashes.
I agree with the other comments that this code was written prior to 2003, and should not be used, unless for supporting old code. | Can anyone explain the following PHP Code? | [
"",
"php",
""
] |
I'm trying to write a stored procedure in SQL that will :
Make a select query from table1 that will return multiple values
Insert new values in table2 (1 new record in table2 for each record returned by the select on table1).
I would use a foreach in C# but I know that SQL doesn't work that way. What's the correct way of doing this?
Thanks! | ```
INSERT INTO tabl2 (name, id)
SELECT name, id FROM table1
```
**EDIT**
I should add, that loops can indeed be very useful in SQL, so you may want to know how to do that as well. Here's one example:
```
DECLARE @temp TABLE (ix int identity(1,1), id int, name varchar(100))
INSERT INTO @temp SELECT id, name FROM table1
DECLARE @i int, @max int
SELECT
@i = 0
@max = MAX(ix)
FROM
@temp
WHILE @i < @max
BEGIN
SET @i = @i + 1
-- LOGIC HERE...
END
``` | SQL is a set-based language. What you do is express the result you want as a query - that returns a 'set' which is then inserted into the new table.
You CAN use a CURSOR which is row-by-row based but that really is a last resort. Very very rarely have I found that to be the only way.
maybe if you posted soem more detail about your problem we can help! | What to use in SQL instead of a "Foreach" loop | [
"",
"sql",
"stored-procedures",
""
] |
I'm pretty proficient in PHP, but want to try something new.
I'm also know a bit of Python, enough to do the basics of the basics, but haven't used in a web design type situation.
I've just written this, which works:
```
#!/usr/bin/python
def main():
print "Content-type: text/html"
print
print "<html><head>"
print "<title>Hello World from Python</title>"
print "</head><body>"
print "Hello World!"
print "</body></html>"
if __name__ == "__main__":
main()
```
Thing is, that this seems pretty cumbersome. Without using something huge like django, what's the best way to write scripts that can process get and post? | Your question was about basic CGI scripting, looking at your example, but it seems like everyone has chosen to answer it with "use my favorite framework". Let's try a different approach.
If you're looking for a direct replacement for what you wrote above (ie. CGI scripting), then you're probably looking for the [cgi](http://docs.python.org/library/cgi.html) module. It's a part of the Python standard library. Complimentary functionality is available in [urllib](http://docs.python.org/library/urllib.html) and [urllib2](http://docs.python.org/library/urllib2.html). You might also be interested in [BaseHTTPServer](http://docs.python.org/library/basehttpserver.html) and [SimpleHTTPServer](http://docs.python.org/library/simplehttpserver.html), also part of the standard library.
Getting into more interesting territory, [wsgiref](http://docs.python.org/library/wsgiref.html) gives you the basics of a [WSGI](http://www.wsgi.org/wsgi/) interface, at which point you probably want to start thinking about more "frameworky" (is that a word?) things like web.py, Django, Pylons, CherryPy, etc, as others have mentioned. | As far as full frameworks go I believe Django is relatively small.
If you *really* want lightweight, though, check out [web.py](http://webpy.org/), [CherryPy](http://www.cherrypy.org/), [Pylons](http://pylonshq.com/) and [web2py](http://www.web2py.com/).
I think the crowd favorite from the above is Pylons, but I am a Django man so I can't say much else.
For more on lightweight Python frameworks, check out [this question](https://stackoverflow.com/questions/68986/whats-a-good-lightweight-python-mvc-framework). | Writing a website in Python | [
"",
"python",
""
] |
Does anyone know exactly what happens when you change your Zend site at, say, `foo.com/` to `foo.com/subfolder/` ? I notice that routing breaks and either I am not using `front_controller.setBaseUrl()` properly or it has no effect. I am unable to find any formal documentation at the Zend site about this issue. | The most likely cause of your problem is that you need to set the `RewriteBase` parameter in your `.htaccess` file.
Assuming your rewrite rules look something like this:
```
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
```
And assuming you are moving your site into the `subfolder` subfolder, add the following line to your re-write rules, just under `RewriteEngine on`.
```
RewriteBase /subfolder
```
Your complete rewrite rules should look like so:
```
RewriteEngine on
RewriteBase /subfolder
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]
```
PS: The Front Controller/Request Object/Router will 99% of the time correctly determine the `baseUrl` automagically. Try *not* explicitly setting it. If the above changes to your rewrite rules do not work, only then attempt to override.
You can, at any time get the `baseUrl` that was determined be the request with the following:
```
var_dump(Zend_Controller_Front::getInstance()->getBaseUrl());
``` | [Configuring your URL Rewriter](http://framework.zend.com/wiki/display/ZFDEV/Configuring+Your+URL+Rewriter) | What happens to the Zend Framework routing tables when you change the site to a subfolder? | [
"",
"php",
"zend-framework",
""
] |
I'm porting my application from 32 bit to 64 bit. Currently, the code compiles under both architectures, but the results are different. For various reasons, I'm using floats instead of doubles. I assume that there is some implicit upconverting from float to double happening on one machine and not the other. Is there a way to control for this, or specific gotchas I should be looking for?
edited to add:
32 bit platform
```
gcc (GCC) 4.1.2 20070925 (Red Hat 4.1.2-33)
Dual-Core AMD Opteron(tm) Processor 2218 HE
```
64 bit platform
```
gcc (Ubuntu 4.3.3-5ubuntu4) 4.3.3
Intel(R) Xeon(R) CPU
```
Applying the -mfpmath=387 helps somewhat, after 1 iteration of the algorithm the values are the same, but beyond that they fall out of sync again.
I should also add that my concern isn't that the results aren't identical, it's that porting to a 64 bit platform has uncovered a 32 bit dependency of which I was not aware. | There is no inherent need for floats and doubles to behave differently between 32-bit and 64-bit code but frequently they do. The answer to your question is going to be platform and compiler specific so you need to say what platform you are porting from and what platform you are porting to.
On intel x86 platforms 32-bit code often uses the x87 co-processor instruction set and floating-point register stack for maximum compatibility whereas on amb64/x86\_64 platforms, the SSE\* instructions and xmm\* registers and are often used instead. These have different precision characteristics.
Post edit:
Given your platform, you might want to consider trying the -mfpmath=387 (the default for i386 gcc) on your x86\_64 build to see if this explains the differing results. You may also want to look at the settings for all the -fmath-\* compiler switches to ensure that they match what you want in both builds. | Your compiler is probably using SSE opcodes to do most of its floating point arithmetic on the 64 bit platform assuming x86-64, whereas for compatibility reasons it probably used the FPU before for a lot of its operations.
SSE opcodes offer a lot more registers and consistency (values always remain 32 bits or 64 bits in size), while the FPU uses 80 bit intermediate values when possible. So you were most likely benefitting from this improved intermediate precision before. (Note the extra precision can cause inconsistent results like x == y but cos(x) != cos (y) depending on how far apart the computations occur!)
You may try to use -mfpmath=387 for your 64 bit version since you are compiling with gcc and see if your results match your 32 bit results to help narrow this down. | 64 bit floating point porting issues | [
"",
"c++",
"c",
"floating-point",
"64-bit",
"portability",
""
] |
I have recently found a bug that causes a NullPointerException. The exception is caught and logged using a standard slf4j statement. Abridged code below:
```
for(Action action : actions.getActions()) {
try {
context = action.execute(context);
} catch (Exception e) {
logger.error("...", e);
break;
}
}
```
As you can see, nothing fancy. However, of all the exception logging statements that we have, just this one does not print a stack trace. All it prints is the message (represented as "...") and the name of the exception class (java.lang.NullPointerException).
Since the stack trace on an exception is lazy loaded, I thought maybe there is a instruction reordering issue of some sort and decided to call e.getStackTrace() before the log statement. This made no difference.
So I decided to restart with the debug agent enabled. However, because I even attached to the process, I noticed that now the stack traces were printing. So clearly the presence of the debug agent caused some additional debug information to become available.
I have since then fixed the root cause of the exception. But I would like to learn why the stack trace was unavailable without a debugger. Anyone know?
Clarification: *this is not a logging issue*. Imagine the same try/catch clause, but in the catch, I print the value of:
```
e.getStackTrace().length
```
Without a debugger this prints '0', with a debugger it prints a positive number (9 in this case).
More info: this is happening on JDK 1.6.0\_13, 64bit, amd64, linux 2.6.9 | Is it possible that this code is in an inner loop? Then then JIT compiler might be compiling the call stack for this to native code, losing the stack information. Then when you attach the debugger it disables the JIT, making the information available again.
The other manual exceptions keep displaying the information as the JIT is not optimising.
It looks like this can sometimes happen for others from a comment in this class source code at line 102:
<http://logging.apache.org/log4j/1.2/xref/org/apache/log4j/spi/LocationInfo.html> | With the JVM flag -XX:-OmitStackTraceInFastThrow you can disable the performance optimization of the JVM for this use case. IF this parameter is given, which disables the flag, the stacktrace will be available.
For more information please have a look at the following release notes:
"The compiler in the server VM now provides correct stack backtraces for all "cold" built-in exceptions. For performance purposes, when such an exception is thrown a few times, the method may be recompiled. After recompilation, the compiler may choose a faster tactic using preallocated exceptions that do not provide a stack trace. To disable completely the use of preallocated exceptions, use this new flag: -XX:-OmitStackTraceInFastThrow." <http://java.sun.com/j2se/1.5.0/relnotes.html> | NullPointerException stack trace not available without debug agent | [
"",
"java",
"logging",
"stack-trace",
"nullpointerexception",
""
] |
[Alex's answer](https://stackoverflow.com/questions/1044705/unable-to-solve-a-python-error-message/1044754#1044754) has the following line when translated to English
```
print "%2d. %8.2f %8.2f %8.2f" % (
i, payment, interest, monthPayment)
```
I am unsure about the line
```
"%2d. %8.2f %8.2f %8.2f" % #Why do we need the last % here?
```
It seems to mean the following
1. apply %2d. to i
2. apply %8.2f to payment
3. apply %8.2f to interest
4. apply %8.2f to monthPayment
The %-words seem to mean the following
1. %2d.: a decimal presentation of two decimals
2-4. %8.2f: a floating point presentation of two decimals
I am not sure why we use the 8 in %8.2f.
**How do you understand the challenging line?** | The 8 in 8.2 is the width
"Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger"
The 2 is the number of decimal places
The final % just links the format string (in quotes) with the list of arguments (in brackets).
It's a bit confusing that they chose a % to do this - there is probably some deep python reason.
edit: Apparently '%' is used simply because '%' is used inside the format - which is IMHO stupid and guaranteed to cause confusion. It's like requiring an extra dot at the end of a floating point number to show that it's floating point! | The last % is an operator that takes the string before it and the tuple after and applies the formatting as you note. See the [Python tutorial](http://docs.python.org/library/stdtypes.html#index-586) for more details. | Unable to understand a line of Python code exactly | [
"",
"python",
"syntax",
""
] |
I'm relatively new to C++ (about one year of experience, on and off). I'm curious about what led to the decision of `type * name` as the syntax for defining pointers. It seems to me that the syntax should be `type & name` as the `&` symbol is used everywhere else in code to refer to the variable's memory address. So, to use the traditional example of `int` pointers:
```
int a = 1;
int * b = &a;
```
would become
```
int a = 1;
int & b = &a
```
I'm sure there's some reason for this that I'm just not seeing, and I'd love to hear some input from C++ veterans.
Thanks,
-S | C++ adopts the C syntax. As revealed in "[The Development of the C Language](http://cm.bell-labs.com/cm/cs/who/dmr/chist.html)" (by Dennis Ritchie) C uses `*` for pointers in type declarations because it was decided that type syntax should follow use.
> For each object of [a compound type], there was already a way to mention the underlying object: index the array, call the function, use the indirection operator [`*`] on the pointer. Analogical reasoning led to a declaration syntax for names mirroring that of the expression syntax in which the names typically appear. Thus,
>
> ```
> int i, *pi, **ppi;
> ```
>
> declare an integer, a pointer to an integer, a pointer to a pointer to an integer. The syntax of these declarations reflects the observation that i, \*pi, and \*\*ppi all yield an int type when used in an expression.
Here's a more complex example:
```
int *(*foo)[4][];
```
This declaration means an expression `*(*foo)[4][0]` has type `int`, and from that (and that `[]` has higher precedence than unary `*`) you can decode the type: foo is a pointer to an array of size 4 of array of pointers to ints.
This syntax was adopted in C++ for compatibility with C. Also, don't forget that C++ has a use for & in declarations.
```
int & b = a;
```
The above line means a reference variable refering to another variable of type `int`. The difference between a reference and pointer roughly is that references are initialized only, and you can not change where they point, and finally they are always dereferenced automatically.
```
int x = 5, y = 10;
int& r = x;
int sum = r + y; // you do not need to say '*r' automatically dereferenced.
r = y; // WRONG, 'r' can only have one thing pointing at during its life, only at its infancy ;)
``` | I think that Dennis Ritchie answered this in **[The Development of the C Language](http://cm.bell-labs.com/cm/cs/who/dmr/chist.html)**:
> For each object of such a composed
> type, there was already a way to
> mention the underlying object: index
> the array, call the function, use the
> indirection operator on the pointer.
> Analogical reasoning led to a
> declaration syntax for names mirroring
> that of the expression syntax in which
> the names typically appear. Thus,
>
> ```
> int i, *pi, **ppi;
> ```
>
> declare an integer, a pointer to an
> integer, a pointer to a pointer to an
> integer. The syntax of these
> declarations reflects the observation
> that i, \*pi, and \*\*ppi all yield an
> int type when used in an expression.
> Similarly,
>
> ```
> int f(), *f(), (*f)();
> ```
>
> declare a function returning an
> integer, a function returning a
> pointer to an integer, a pointer to a
> function returning an integer;
>
> ```
> int *api[10], (*pai)[10];
> ```
>
> declare an array of pointers to
> integers, and a pointer to an array of
> integers. In all these cases the
> declaration of a variable resembles
> its usage in an expression whose type
> is the one named at the head of the
> declaration.
So we use `type * var` to declare a pointer because this allows the declaration to mirror the usage (dereferencing) of the pointer.
In this article, Ritchie also recounts that in "NB", an extended version of the "B" programming language, he used `int pointer[]` to declare a pointer to an `int`, as opposed to `int array[10]` to declare an array of `int`s. | Why do we use "type * var" instead of "type & var" when defining a pointer? | [
"",
"c++",
"syntax",
""
] |
The code below is what I am trying to use in order to get the count of one column and the averages of two other columns from multiple tables and then put the results into another table.
I thought this would work, but the count that is being put into the new table is incorrect as are the averages. A lot of times the averages are outside the range of the numbers that are being averaged. The numbers that are being averaged are all negative and most of them contain decimals. The data type for the columns is set to `Number` and the field size for the numbers being averaged (the source and the destination) is set to `Double`.
---
### Code:
```
For i = 1000 To 1783
strQuery1 = "Insert Into MIUsInGridAvgs (NumberofMIUs, ProjRSSI, RealRSSI) " & _
"Select Count(MIUID), Avg(ProjRSSI), Avg(RealRSSI) " & _
"From MIUsInGrid" & i & " "
DoCmd.SetWarnings False
DoCmd.RunSQL strQuery1
DoCmd.SetWarnings True
Next
```
The table names I am querying from all end with numbers between 1000 and 1783 inclusive.
---
### Example Data:
`MIUsInGrid1000`
```
MIUID Latitude Longitude ProjRSSI RealRSSI
110108098 32.593021 -85.367073 -97.4625 -108
```
`MIUsInGrid1001`
```
MIUID Latitude Longitude ProjRSSI RealRSSI
110112556 32.592461 -85.337067 -101 -95
110106208 32.592766 -85.337059 -101 -100
110115010 32.59288 -85.337189 -101 -98
```
`MIUsInGrid1002`
```
MIUID Latitude Longitude ProjRSSI RealRSSI
110172260 32.593349 -85.366318 -104.408333333333 -99
110106870 32.593464 -85.365822 -104.408333333333 -106
```
---
### Results:
```
NumberofMIUs ProjRSSI RealRSSI
1 -97.4625 -108 'MIUsInGrid1000
1 -100.883333333333 -109 'MIUsInGrid1001
1 -109.521428571429 -99 'MIUsInGrid1002
```
What am I doing wrong? | I found the answer but I don't really understand it. The column **NumberofMIUs** had the "`Indexed`" property set to "`Yes (Duplicates OK)`". When I changed the setting to "`No`" the query worked fine. | Don't you have to group by something in order to be able to use the `AVG()` group function?
What value does your `i` variable contain? | Why is my query not returning what I expect? | [
"",
"sql",
"ms-access",
"ms-access-2007",
""
] |
I am trying to compare the value of 2 instances of x inside an iterator.
x is a reference type containing its own data members. I am trying to compare one instance of x against another to determine if the values inside each are the same.
if (x.equals(x))
keeps evaluating to true when actually the value of each instance of x is different.
Cheers. | Assuming your code doesn't really look like this
```
X x = new X();
if(x.equals(x))
```
but more like
```
X x = new X();
X y = new X();
if(x.equals(y)) { }
```
And you are getting wrong values for `x.equals(y)` then your implementation of equals is broken.
Go to your `Class X` and check how equals is implemented. If it is not implemented in X check in the super class. | This is a hard question to answer with the details given. They have to be objects and not primitives to have a .equals method. So has the equals method been overridden in a way that is causing faulty comparisons to be done? That would be the place that I would be looking at. | Java: compare object values | [
"",
"java",
"iterator",
"compare",
""
] |
I often need to use a function which performs and action X is condition Y is set. What is the best way to name such a function?
I don't want to repeat *if* statements, since they could be complex.
For instance, if I want to trim a string if a property is set, function could be named:
* **void TrimIfOptionSet(string)** -- too unwieldy, especially if condition is complex
* **bool TryTrim(string)** -- does not mention an external condition, I'd expect it to only take the argument into account.
* **void ConditionalTrim(string)** -- bit verbose
Are there any conventions for this situation in C#/.Net, or any similar language? | Given the constraints, I'd pick `TrimIfOptionSet` or `TrimIfNeeded`.
* `TryTrim` feels like it'll *always* run a trim operation (in a `try` block), which isn't the same as running it only if needed
* `ConditionalTrim` is too long -- the reader's eyes stay on "conditional" and never get to "trim" | Try something like:
```
if(IsComplexCondition(complexData))
{
DoThing(otherData);
}
```
You generally don't want to couple the condition with the operation because you're making a single function capture too much semantic information at that point. It's "doing more than one thing." Instead, if you have a complex condition, capture that condition in a function to encapsulate it.
If you're referring to a much more common situation, such as parameter validation at the top of functions, consider something like [fluent parameter validation](http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/). If you're not doing something like parameter validation, then I might question why it's at the top of every function and not captured in a common location or performed once at a system boundary.
I don't think that there is a good answer for naming the general `ActionIfSomething()` case simply because it's not generally a good solution to a problem. I'd probably just say make the function call `Action()` and document it, perhaps in `<remarks>`, to only perform the action when `Something` is true. If the `Action` belongs with the condition in the function, then it only makes sense in the context of that condition, so re-specifying it in the function name is redundant. | Function naming: ActionIfCondition() | [
"",
"c#",
"naming-conventions",
"naming",
""
] |
I have a test file that contains tests taking quite a lot of time (they send calculations to a cluster and wait for the result). All of these are in specific TestCase class.
Since they take time and furthermore are not likely to break, I'd want to be able to choose whether this subset of tests does or doesn't run (the best way would be with a command-line argument, ie "`./tests.py --offline`" or something like that), so I could run most of the tests often and quickly and the whole set once in a while, when I have time.
For now, I just use `unittest.main()` to start the tests. | The default `unittest.main()` uses the default test loader to make a TestSuite out of the module in which main is running.
You don't have to use this default behavior.
You can, for example, make three [unittest.TestSuite](http://docs.python.org/library/unittest.html#unittest.TestSuite) instances.
1. The "fast" subset.
```
fast = TestSuite()
fast.addTests(TestFastThis)
fast.addTests(TestFastThat)
```
2. The "slow" subset.
```
slow = TestSuite()
slow.addTests(TestSlowAnother)
slow.addTests(TestSlowSomeMore)
```
3. The "whole" set.
```
alltests = unittest.TestSuite([fast, slow])
```
Note that I've adjusted the TestCase names to indicate Fast vs. Slow. You can subclass
unittest.TestLoader to parse the names of classes and create multiple loaders.
Then your main program can parse command-line arguments with [optparse](http://docs.python.org/library/optparse.html) or [argparse](https://docs.python.org/dev/library/argparse.html) (available since 2.7 or 3.2) to pick which suite you want to run, fast, slow or all.
Or, you can trust that `sys.argv[1]` is one of three values and use something as simple as this
```
if __name__ == "__main__":
suite = eval(sys.argv[1]) # Be careful with this line!
unittest.TextTestRunner().run(suite)
``` | To run only a single specific test, you can use:
```
python -m unittest test_module.TestClass.test_method
```
More information is [here](http://pythontesting.net/framework/specify-test-unittest-nosetests-pytest/). | Python unittest: how to run only part of a test file? | [
"",
"python",
"unit-testing",
"python-unittest",
""
] |
I am supporting a legacy C++ application which uses Xerces-C for XML parsing. I've been spoiled by .Net and am used to using XPath to select nodes from a DOM tree.
Is there any way to get access some limited XPath functionality in Xerces-C? I'm looking for something like selectNodes("/for/bar/baz"). I could do this manually, but XPath is so nice by comparison. | See the xerces faq.
<http://xerces.apache.org/xerces-c/faq-other-2.html#faq-9>
***Does Xerces-C++ support XPath?***
No.Xerces-C++ 2.8.0 and Xerces-C++ 3.0.1 only have partial XPath implementation for the purposes of handling Schema identity constraints. For full XPath support, you can refer Apache Xalan C++ or other Open Source Projects like Pathan.
It's fairly easy to do what you want using xalan however. | Here is a working example of XPath evaluation with **Xerces 3.1.2**.
**Sample XML**
```
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<root>
<ApplicationSettings>hello world</ApplicationSettings>
</root>
```
**C++**
```
#include <iostream>
#include <xercesc/dom/DOM.hpp>
#include <xercesc/dom/DOMDocument.hpp>
#include <xercesc/dom/DOMElement.hpp>
#include <xercesc/util/TransService.hpp>
#include <xercesc/parsers/XercesDOMParser.hpp>
using namespace xercesc;
using namespace std;
int main()
{
XMLPlatformUtils::Initialize();
// create the DOM parser
XercesDOMParser *parser = new XercesDOMParser;
parser->setValidationScheme(XercesDOMParser::Val_Never);
parser->parse("sample.xml");
// get the DOM representation
DOMDocument *doc = parser->getDocument();
// get the root element
DOMElement* root = doc->getDocumentElement();
// evaluate the xpath
DOMXPathResult* result=doc->evaluate(
XMLString::transcode("/root/ApplicationSettings"),
root,
NULL,
DOMXPathResult::ORDERED_NODE_SNAPSHOT_TYPE,
NULL);
if (result->getNodeValue() == NULL)
{
cout << "There is no result for the provided XPath " << endl;
}
else
{
cout<<TranscodeToStr(result->getNodeValue()->getFirstChild()->getNodeValue(),"ascii").str()<<endl;
}
XMLPlatformUtils::Terminate();
return 0;
}
```
**Compile and run** (assumes standard xerces library installation and C++ file named *xpath.cpp*)
```
g++ -g -Wall -pedantic -L/opt/lib -I/opt/include -DMAIN_TEST xpath.cpp -o xpath -lxerces-c
./xpath
```
**Result**
```
hello world
``` | XPath support in Xerces-C | [
"",
"xerces",
"xerces-c",
"xpath",
"c++",
""
] |
I'm trying to learn how to use oop in php. I'm also fairly new to jquery. Is it possible to make an Ajax request to a php class method? I've only ever sent Ajax requests to a file specifically for that purpose and that returns the data I need. | *Short answer*: No.
*Long answer*:
Ajax is just a term for making an HTTP request from the browser, using JavaScript, without leaving the page.
**The only thing you can "call" is a URL.**
You can write your PHP to do something based on what the URL is though.
```
<?php
if ($_POST['action'] == "delete") {
delete();
}
?>
``` | Basic answer no, but it can be done easily.
An ajax call itself cannot call class methods. It has not way of initiating the class and then calling the method. It can only cause the PHP file to run on the server via a POST/GET call on X url.
What you can do is use another file to act as a go-between from the ajax to the method. In other words, instead of calling the php file (update.php for example) directly as simple examples show, you can call a go-between file (call it whatever you like, ajax server, ajax router, etc) that uses GET/POST parameters you send to figuere out what method you want to use and what values to pass to it. You could then run the method from that file (initiating the class and calling the method with parameters), and return the results of that method from that file to the ajax calling script. | Jquery Ajax and php classes | [
"",
"php",
"jquery",
"ajax",
"oop",
""
] |
Basically, the question is:
Do the Exceptions in C# affect the performance a lot? Is it better to avoid Exceptions rethrow? If i generate an exception in my code, does it affect a performance?
Sorry for the sillines of the question itself | Microsoft's Design Guidelines for Developing Class Libraries is a very valuable resource. Here is a relevant article:
[Exceptions and Performance](http://msdn.microsoft.com/en-us/library/ms229009.aspx)
I would also recommend the [Framework Design Guidelines](https://rads.stackoverflow.com/amzn/click/com/0321246756) book from Microsoft Press. It has a lot of the information from the Design Guidelines link, but it is annotated by people with MS, and Anders Hejlsberg, himself. It gives a lot of insight into the "why" and "how" of the way things are. | If you're worried about exception performance, you're using them wrong.
But yes, exceptions do affect performance. | Using Exceptions throwing in C#. Does it affect a performance? | [
"",
"c#",
"exception",
""
] |
I want to add the oracle jdbc driver to my project as dependency (runtime scope) - ojdbc14.
In MVNrepository site the dependency to put in the POM is:
```
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.3.0</version>
</dependency>
```
of course this does't work as it is not in the central repository used by maven.
2 questions:
1. How do I find a repository (if any) that contains this artifact?
2. How do I add it so that Maven will use it? | *How do I find a repository (if any) that contains this artifact?*
Unfortunately due the binary license there is no public repository with the Oracle Driver JAR. This happens with many dependencies but is not Maven's fault. If you happen to find a public repository containing the JAR you can be sure that is illegal.
*How do I add it so that Maven will use it?*
Some JARs that can't be added due to license reasons have a *pom* entry in the [Maven Central repo](http://repo2.maven.org/maven2/com/oracle/ojdbc14/10.2.0.3.0/ojdbc14-10.2.0.3.0.pom). Just check it out, it contains the vendor's preferred Maven info:
```
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.3.0</version>
```
...and the URL to download the file which in this case is
<http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html>.
Once you've downloaded the JAR just add it to your computer repository with (note I pulled the groupId, artifactId and version from the POM):
```
mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc14 \
-Dversion=10.2.0.3.0 -Dpackaging=jar -Dfile=ojdbc.jar -DgeneratePom=true
```
*The last parameter for generating a POM will save you from pom.xml warnings*
If your team has a local Maven repository [this guide](http://maven.apache.org/guides/mini/guide-central-repository-upload.html) might be helpful to upload the JAR there. | The Oracle JDBC Driver is now available in the Oracle Maven Repository (not in Central).
```
<dependency>
<groupId>com.oracle.jdbc</groupId>
<artifactId>ojdbc7</artifactId>
<version>12.1.0.2</version>
</dependency>
```
The Oracle Maven Repository requires a user registration. Instructions can be found in:
<https://blogs.oracle.com/dev2dev/get-oracle-jdbc-drivers-and-ucp-from-oracle-maven-repository-without-ides>
**Update 2019-10-03**
I noticed Spring Boot is now using the Oracle JDBC Driver from **Maven Central**.
```
<dependency>
<groupId>com.oracle.ojdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
</dependency>
```
For Gradle users, use:
```
implementation 'com.oracle.ojdbc:ojdbc10:19.3.0.0'
```
There is no need for user registration.
**Update 2020-03-02**
Oracle is now publishing the drivers under the com.oracle.database group id. See Anthony Accioly answer for more information. Thanks Anthony.
Oracle JDBC Driver compatible with JDK6, JDK7, and JDK8
```
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.4</version>
</dependency>
```
Oracle JDBC Driver compatible with JDK8, JDK9, and JDK11
```
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<version>19.3.0.0</version>
</dependency>
```
Oracle JDBC Driver compatible with JDK10 and JDK11
```
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc10</artifactId>
<version>19.3.0.0</version>
</dependency>
``` | Find Oracle JDBC driver in Maven repository | [
"",
"java",
"maven",
"jdbc",
"maven-2",
"mvn-repo",
""
] |
I'm trying to port a Swing application to GWT.
However lots of this application classes use things that are not supported by GWT JRE emulation library such as java.util.Locale, java.text.SimpleDateFormat and much more.
Is there a tool that scans a project and spots such problems? | The Google Plugin for Eclipse shows errors for things that are unsupported by GWT's JRE emulation. <http://code.google.com/eclipse/> | The GWT compiler will complain if you try to access classes in the JRE that are not supported. | Is there a tool that checks GWT JRE emulation library violations? | [
"",
"java",
"gwt",
""
] |
This is related to my previous question [More than 1 Left joins in MSAccess](https://stackoverflow.com/questions/1057167/more-than-1-left-joins-in-msaccess)
The problem is that I have 3 left joins followed by an `AND` operator to check 1 condition.
If I run, then I am getting an error *"Join Expression not supported"*.
The query goes like this:
```
SELECT * FROM(( EMPLOYEE AS E LEFT JOIN DEPARTMENT AS D ON E.EID=D.EID)
LEFT JOIN MANAGERS M ON D.DID=M.DID)
LEFT JOIN MANAGERDETAILS MD ON M.MDID=MD.MDID
**AND E.ENO=MD.ENO**
```
If I take out `AND` part, it works fine.
Any idea? | The way I would write this would be:
```
SELECT EDM.*, MANAGERDETAILS.*
FROM (
SELECT ED.*, MANAGERS.*
FROM (
SELECT EMPLOYEE.*, DEPARTMENT.*
FROM EMPLOYEE
LEFT JOIN DEPARTMENT
ON EMPLOYEE.EID = DEPARTMENT.EID
) AS ED
LEFT JOIN MANAGERS
ON ED.DID = MANAGERS.DID
) AS EDM
LEFT JOIN MANAGERDETAILS
ON EDM.MDID = MANAGERDETAILS.MDID
AND EDM.ENO = MANAGERDETAILS.ENO
```
Basically, you join tables one at a time and alias the result that you can then use for the next join.
You can achieve arbitrarily complex Left joins in Access only by aliasing smaller subsets.
Your double join clause probably doesn't work because one of its members refers to a deeper resultset than the one that's visible at that level of the query. | You need a second reference to the Employee table since you are trying to pull the manager's employee record.
SELECT \*
FROM
(
(
(EMPLOYEE AS E LEFT JOIN DEPARTMENT AS D ON E.EID = D.EID)
LEFT JOIN MANAGERS AS M
ON D.DID = M.DID
)
LEFT JOIN MANAGERDETAILS AS MD
ON M.DID = MD.MDID
)
LEFT JOIN EMPLOYEE AS E2 ON MD.ENO = E2.ENO;
We don't have enough information on the data you expect, but this query will execute.
I know in Access you'll need to handle the parentheses, but you could do this with the graphic query builder. | Problems with More than 1 Left joins in MSAccess | [
"",
"sql",
"ms-access",
""
] |
What is the fastest way to loop thru a Query in T-SQL .
1) Cursors or
2) Temp tables with Key added or
any thing else. | I don't think you need a cursor for that (your comment about concat) if I understand what you're going for.
Here's one of mine that grabs all the phone numbers for a contact and plops them in a field and returns it.
```
DECLARE @numbers VARCHAR(255)
SELECT @numbers = COALESCE(@numbers + ' | ','') + PHONE_NUMB FROM my_table (NOLOCK)
WHERE CONTACT_ID=@contact_id RETURN @numbers
``` | The fastest way to "loop" thru a query is to just not do it. In SQL, you should be thinking set-based instead of loop-based. You should probably evaluate your query, ask why you need to loop, and look for ways to do it as a set.
With that said, using the FAST\_FORWARD option on your cursors will help speed things along. | Fastest way to loop thru a SQL Query | [
"",
"sql",
""
] |
I am a vc++ developer (but like Qt) interested in learning from open source projects by contributing and reading the code. I use Windows as a primary development platform.
Which project will be right for me to start? Is [chromium](http://code.google.com/chromium/) a good choice? | > Is chromium a good choice?
I believe so, yes!
The source code is IMO very well written, it's a really active project with a lot of work to do and is also interesting in many different ways. Obviously a browser is in itself just a combination of specific libraries, and thus Chromium gives you a nice entry to learn more about them and hopefully contribute evidently. But most importantly it has a big community, is sponsored by a big corporation and has many talented software engineers on its core team.
* Want to learn how to integrate the
[V8 javascript engine](http://code.google.com/p/v8/)?
* Want to learn about rendering/drawing on screen via [Skia](http://code.google.com/p/skia/)?
* Want to learn how to integrate [Webkit](http://webkit.org/)?
* Want to learn more about the [HTTP protocol / network stack](http://www.youtube.com/watch?v=ZhDb42M6ZLk)?
* Want to learn how to [sandbox](http://dev.chromium.org/developers/design-documents/sandbox) applications?
* Want to learn about [multi-process architecture](http://www.youtube.com/watch?v=A0Z0ybTCHKs) and IPC?
There are so many things to do, so you could even contribute things you know while learning stuff you don't.
---
I'd like to add; The choice of an open source project to join should be based on:
1. Your level of expertize
* What you'd like to learn
* Quality of the code
* Maturity of the project
* Code complexity (not to be confused with readability)
I only speak for myself here, but as much as I love learning more from too complex projects (file systems, RDBM etc) I find those projects to be less rewarding because of the overwhelming complexity. Try not to learn everything at once, take smaller steps and finish what you start rather than taking larger steps and give up.
Just my 2c - YMMV
---
In case you'd want to try Chromium out, here are links for the design documents:
* [Getting around the source code](http://dev.chromium.org/developers/how-tos/getting-around-the-chrome-source-code) explains in great detail how the projects tree structure is built.
* The [Engineering design docs](http://dev.chromium.org/developers/design-documents) explain the architecture, most under the hood and future work
* The [user experience design docs](http://dev.chromium.org/user-experience) provide insight to everything that touches the user, that is behavior and look.
* [Tech Talk Videos](http://dev.chromium.org/developers/tech-talk-videos) that are very helpful for understanding some key engineering issues and decisions, even if you don't intend to join the chromium project.
The links above are all taken from the [Chromium developer documentation](http://dev.chromium.org/developers), where even more details can be found.
Anyway, good luck finding a project that fits your needs! | Get involved in the [Qt Creator](http://www.qtsoftware.com/products/developer-tools) project. | Open source project for a C++ developer? | [
"",
"c++",
"qt",
"open-source",
""
] |
I have a rather memory hungry java application.
On my 32 bit systems with Windows XP Professional the application will just run fine if I give it `-Xmx1280m`. Everything below will end up in an `java.lang.OutOfMemoryError: Java heap space` exception.
If I run the same application on a 64 bit Windows XP Professional (everything else exactly the same) it requires `-Xms1400m` to prevent the OutOfMemory condition.
To my understanding, if I have a C program and I compile it for 32 bit and for 64 bit the
64 bit version will need more memory because pointers are wider and so on.
In my java example however the virtual machine (Sun) is the same and the bytecode is the same.
**Why does it need more memory on the 64 bit machine?** | Probably because the **virtual machine** implementation differs between 32/64 bit architecture in such a way that it consumes more memory (wider types, different GC).
The bytecode is irrelevant when it passes on the tasks to the underlying system. Im not sure that Java and memory-efficient are two terms I would put together anyway :P | Even though your bytecode is the same, the JVM converts that to machine code, so it has all the same reasons as C to require a larger memory footprint. | Does a 32bit process need more memory when it runs on a 64bit system? | [
"",
"java",
"windows-xp",
"64-bit",
"32-bit",
"out-of-memory",
""
] |
Say I have a class `Customer` which has a property `FirstName`. Then I have a `List<Customer>`.
Can LINQ be used to find if the list has a customer with `Firstname = 'John'` in a single statement.. how? | LINQ defines an extension method that is perfect for solving this exact problem:
```
using System.Linq;
...
bool has = list.Any(cus => cus.FirstName == "John");
```
make sure you reference System.Core.dll, that's where LINQ lives. | zvolkov's answer is the perfect one to find out *if* there is such a customer. If you need to *use* the customer afterwards, you can do:
```
Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
// Use customer
}
```
I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the *first* such customer... to find all of them, just use a normal `where` clause.) | Searching if value exists in a list of objects using Linq | [
"",
"c#",
"linq",
""
] |
Is there any library for distributed in-memory cache, distributed tasks, publish/subscribe messaging? I have used Hazelcast in Java, I would like something similar.
I know that Memcached is an in-memory cache and even distributed, but it is missing the messaging and remote task.
I just need something to coordinate a cluster of server without using traditional RPC and socket programming. | MPI might be what you want:
<http://en.wikipedia.org/wiki/Message_Passing_Interface>
There are C++ hooks available in boost:
<http://www.boost.org/doc/libs/1_39_0/doc/html/mpi.html>
Here is an informative podcast about Open-MPI, which is an implementation of MPI:
<http://twit.tv/floss50> | You might try [ACE](http://en.wikipedia.org/wiki/Adaptive_Communication_Environment). It is a rather high-level open-source library that introduces quite a lot of abstractions. | C++ distributed programming | [
"",
"c++",
"distributed",
"distributed-computing",
"in-memory",
""
] |
I want a python function that takes a pdf and returns a list of the text of the note annotations in the document. I have looked at python-poppler (<https://code.launchpad.net/~poppler-python/poppler-python/trunk>) but I can not figure out how to get it to give me anything useful.
I found the `get_annot_mapping` method and modified the demo program provided to call it via `self.current_page.get_annot_mapping()`, but I have no idea what to do with an AnnotMapping object. It seems to not be fully implemented, providing only the copy method.
If there are any other libraries that provide this function, that's fine as well. | Turns out the bindings were incomplete. It is now fixed. <https://bugs.launchpad.net/poppler-python/+bug/397850> | You should DEFINITELY have a look at `PyPDF2`. This amazing library has incredible potential, you can extract whatever from a PDF, including images or comments. Try to start by examining what Acrobat Reader DC (Reader) can give you on a PDF’s comments. Take a simple PDF, annotate it (add some comments) with Reader and in the comments tab in the upper right corner, click the horizontal three dots and click `Export All To Data File...` and select the format with the extension `xfdf`. This creates a wonderful xml file which you can parse. The format is very transparent and self-evident.
If, however, you cannot rely on a user clicking this and instead need to extract the same data from a PDF programmatically using python, do not despair, there is a solution. (Inspired by [Extract images from PDF without resampling, in python?](https://stackoverflow.com/questions/2693820/extract-images-from-pdf-without-resampling-in-python))
## Prerequisites
```
pip install PyPDF2
```
## xfdf XML
What Reader gives you in the above mentioned xfdf file, looks like this:
```
<?xml version="1.0" ?>
<xfdf xml:space="preserve" xmlns="http://ns.adobe.com/xfdf/">
<annots>
<caret IT="Replace" color="#0000FF" creationdate="D:20190221151519+01'00'" date="D:20190221151526+01'00'" flags="print" fringe="1.069520,1.069520,1.069520,1.069520" name="72f8d1b7-d878-4281-bd33-3a6fb4578673" page="0" rect="636.942000,476.891000,652.693000,489.725000" subject="Inserted Text" title="Admin">
<contents-richtext>
<body xfa:APIVersion="Acrobat:19.10.0" xfa:spec="2.0.2" xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<p dir="ltr">
<span dir="ltr" style="font-size:10.5pt;text-align:left;color:#000000;font-weight:normal;font-style:normal"> comment1</span>
</p>
</body>
</contents-richtext>
<popup flags="print,nozoom,norotate" open="no" page="0" rect="737.008000,374.656000,941.008000,488.656000"/>
</caret>
<highlight color="#FFD100" coords="183.867000,402.332000,220.968000,402.332000,183.867000,387.587000,220.968000,387.587000" creationdate="D:20190221151441+01'00'" date="D:20190221151448+01'00'" flags="print" name="a18c7fb0-0af3-435e-8c32-1af2af3c46ea" opacity="0.399994" page="0" rect="179.930000,387.126000,224.904000,402.793000" subject="Highlight" title="Admin">
<contents-richtext>
<body xfa:APIVersion="Acrobat:19.10.0" xfa:spec="2.0.2" xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/">
<p dir="ltr">
<span dir="ltr" style="font-size:10.5pt;text-align:left;color:#000000;font-weight:normal;font-style:normal">comment2</span>
</p>
</body>
</contents-richtext>
<popup flags="print,nozoom,norotate" open="no" page="0" rect="737.008000,288.332000,941.008000,402.332000"/>
</highlight>
<caret color="#0000FF" creationdate="D:20190221151452+01'00'" date="D:20190221151452+01'00'" flags="print" fringe="0.828156,0.828156,0.828156,0.828156" name="6bf0226e-a3fb-49bf-bc89-05bb671e1627" page="0" rect="285.877000,372.978000,298.073000,382.916000" subject="Inserted Text" title="Admin">
<popup flags="print,nozoom,norotate" open="no" page="0" rect="737.008000,268.088000,941.008000,382.088000"/>
</caret>
<strikeout IT="StrikeOutTextEdit" color="#0000FF" coords="588.088000,497.406000,644.818000,497.406000,588.088000,477.960000,644.818000,477.960000" creationdate="D:20190221151519+01'00'" date="D:20190221151519+01'00'" flags="print" inreplyto="72f8d1b7-d878-4281-bd33-3a6fb4578673" name="6686b852-3924-4252-af21-c1b10390841f" page="0" rect="582.290000,476.745000,650.616000,498.621000" replyType="group" subject="Cross-Out" title="Admin">
<popup flags="print,nozoom,norotate" open="no" page="0" rect="737.008000,383.406000,941.008000,497.406000"/>
</strikeout>
</annots>
<f href="p1.pdf"/>
<ids modified="ABB10FA107DAAA47822FB5D311112349" original="474F087D87E7E544F6DEB9E0A93ADFB2"/>
</xfdf>
```
Various types of comments are presented here as tags within an `<annots>` block.
## Using PyPDF2
Python can give you almost the same data. To obtain it, have a look at what the output of the following script gives:
```
from PyPDF2 import PdfFileReader
reader = PdfFileReader("/path/to/my/file.pdf")
for page in reader.pages:
try :
for annot in page["/Annots"] :
print (annot.getObject()) # (1)
print ("")
except :
# there are no annotations on this page
pass
```
The output for the same file as in the xfdf file above will look like this:
```
{'/Popup': IndirectObject(192, 0), '/M': u"D:20190221151448+01'00'", '/CreationDate': u"D:20190221151441+01'00'", '/NM': u'a18c7fb0-0af3-435e-8c32-1af2af3c46ea', '/F': 4, '/C': [1, 0.81961, 0], '/Rect': [179.93, 387.126, 224.904, 402.793], '/Type': '/Annot', '/T': u'Admin', '/RC': u'<?xml version="1.0"?><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" xfa:APIVersion="Acrobat:19.10.0" xfa:spec="2.0.2" ><p dir="ltr"><span dir="ltr" style="font-size:10.5pt;text-align:left;color:#000000;font-weight:normal;font-style:normal">comment2</span></p></body>', '/P': IndirectObject(5, 0), '/Contents': u'otrasneho', '/QuadPoints': [183.867, 402.332, 220.968, 402.332, 183.867, 387.587, 220.968, 387.587], '/Subj': u'Highlight', '/CA': 0.39999, '/AP': {'/N': IndirectObject(202, 0)}, '/Subtype': '/Highlight'}
{'/Parent': IndirectObject(191, 0), '/Rect': [737.008, 288.332, 941.008, 402.332], '/Type': '/Annot', '/F': 28, '/Open': <PyPDF2.generic.BooleanObject object at 0x02A425D0>, '/Subtype': '/Popup'}
{'/Popup': IndirectObject(194, 0), '/M': u"D:20190221151452+01'00'", '/CreationDate': u"D:20190221151452+01'00'", '/NM': u'6bf0226e-a3fb-49bf-bc89-05bb671e1627', '/F': 4, '/C': [0, 0, 1], '/Subj': u'Inserted Text', '/Rect': [285.877, 372.978, 298.073, 382.916], '/Type': '/Annot', '/P': IndirectObject(5, 0), '/AP': {'/N': IndirectObject(201, 0)}, '/RD': [0.82816, 0.82816, 0.82816, 0.82816], '/T': u'Admin', '/Subtype': '/Caret'}
{'/Parent': IndirectObject(193, 0), '/Rect': [737.008, 268.088, 941.008, 382.088], '/Type': '/Annot', '/F': 28, '/Open': <PyPDF2.generic.BooleanObject object at 0x02A42830>, '/Subtype': '/Popup'}
{'/Popup': IndirectObject(196, 0), '/M': u"D:20190221151519+01'00'", '/CreationDate': u"D:20190221151519+01'00'", '/NM': u'6686b852-3924-4252-af21-c1b10390841f', '/F': 4, '/IRT': IndirectObject(197, 0), '/C': [0, 0, 1], '/Rect': [582.29, 476.745, 650.616, 498.621], '/Type': '/Annot', '/T': u'Admin', '/P': IndirectObject(5, 0), '/QuadPoints': [588.088, 497.406, 644.818, 497.406, 588.088, 477.96, 644.818, 477.96], '/Subj': u'Cross-Out', '/IT': '/StrikeOutTextEdit', '/AP': {'/N': IndirectObject(200, 0)}, '/RT': '/Group', '/Subtype': '/StrikeOut'}
{'/Parent': IndirectObject(195, 0), '/Rect': [737.008, 383.406, 941.008, 497.406], '/Type': '/Annot', '/F': 28, '/Open': <PyPDF2.generic.BooleanObject object at 0x02A42AF0>, '/Subtype': '/Popup'}
{'/Popup': IndirectObject(198, 0), '/M': u"D:20190221151526+01'00'", '/CreationDate': u"D:20190221151519+01'00'", '/NM': u'72f8d1b7-d878-4281-bd33-3a6fb4578673', '/F': 4, '/C': [0, 0, 1], '/Rect': [636.942, 476.891, 652.693, 489.725], '/Type': '/Annot', '/RD': [1.06952, 1.06952, 1.06952, 1.06952], '/T': u'Admin', '/RC': u'<?xml version="1.0"?><body xmlns="http://www.w3.org/1999/xhtml" xmlns:xfa="http://www.xfa.org/schema/xfa-data/1.0/" xfa:APIVersion="Acrobat:19.10.0" xfa:spec="2.0.2" ><p dir="ltr"><span dir="ltr" style="font-size:10.5pt;text-align:left;color:#000000;font-weight:normal;font-style:normal">comment1</span></p></body>', '/P': IndirectObject(5, 0), '/Contents': u' pica', '/Subj': u'Inserted Text', '/IT': '/Replace', '/AP': {'/N': IndirectObject(212, 0)}, '/Subtype': '/Caret'}
{'/Parent': IndirectObject(197, 0), '/Rect': [737.008, 374.656, 941.008, 488.656], '/Type': '/Annot', '/F': 28, '/Open': <PyPDF2.generic.BooleanObject object at 0x02A42AB0>, '/Subtype': '/Popup'}
```
If you examine the output, you will realize that the outputs are all more or less the same. Every comment in the xfdf file has two counterparts in PyPDF2’s output in python. The `/C` attribute is the color of the highlight, in RGB, scaled to floats in the range <0, 1>. `/Rect` defines the bounding box of the comment on the page/spread, in points (1/72 of an inch) relative to the lower-left corner of the page, increasing values going right and up. `/M` and `/CreationDate` are modified and creation times, `/QuadPoints` is an array of `[x1, y1, x2, y2, ..., xn, yn]` coordinates of a line around the comment, `/Subject`, `/Type`, `/SubType`, `/IT` identify the type of the comment, `/T` is probably the creator, `/RC` is an xhtml representation of the comment’s text if there is one. If there is an ink-drawn comment, it will be presented here as having an attribute `/InkList` with data in the form `[[L1x1, L1y1, L1x2, L1y2, ..., L1xn, L1yn], [L2x1, L2y1, ..., L2xn, L2yn], ..., [Lmx1, Lmy1, ..., Lmxn, Lmyn]]` for line 1, line 2, ..., line m.
For a more thorough explanation of the various fields you get from `getObject()` in the given python code labeled as line (1), please consult <https://web.archive.org/web/20200617223756/https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf> and especially the section 12.5 Annotations starting at pages 381–413. | Parse annotations from a pdf | [
"",
"python",
"pdf",
""
] |
I'm currently implementing a very complex tree structure to allow for near-instant data access, instead of re-processing on each request.
I'm just wondering if there is a theoretical, or practical, limit at which the size of a tree becomes too big, or a point at which a dictionary becomes too collision-filled to function correctly/quickly?
A general answer would be appreciated but C#-specific information would be much better! | In .NET the maximum in either a Tree or Dictionary is 2^31 - 1 (and probably a few less with overhead).
In practical terms, you will probably have run out of memory long before then!
If the tree remains balanced then searches will remain approx. O(log N).
Dictionaries are more sensitive to the underlying algorithm used, for instance there are many hashing schemes with different characteristics. | Depends what you consider a large amount. Hundreds or Thousands should be OK, but millions may be worth looking for something specialised.
A tree will get slower as you grow, depending upon your storage technique and rebalancing.
A dictionary should be fairly consistent, but make sure you construct it with a size appropriate to the amount of data you're likely to store (maybe x2 to be safe). | Reasonable size of a Tree and Dictionary | [
"",
"c#",
"dictionary",
"tree",
"size",
""
] |
I understand that debug=true is a bad thing on any production server.
I am currently using some dll's that are from a third party and were compiled in debug mode and wanted to know - What happens to a DLL in debug mode inside a web application with debug=false? | The debug attribute of the system.web/compilation configuration element has no effect on the code of compiled DLLs.
It only affects code that's compiled dynamically, and has some other effects on the runtime (e.g. the executionTimeout element of the system.web/httpRuntime configuration element is ignored if debug=true). | In C# / .NET (unlike C++ DLLs) it is generally not an issue. Debug and Release are near identical and there are no memory-management issues (as there would be with C++ DLLs).
The following is from jaybaz's [blog](http://blogs.msdn.com/jaybaz_ms/archive/2004/06/28/168314.aspx):
> There are 3 things people typically identify as the difference between debug & release. You need to decide which one you’re interested in:
>
> “DEBUG” preprocessor flag. Can be set on the whole assembly/netmodule with ‘csc /define’, or on a whole file with #define.
>
> Debugging information (pdb). Set with ‘csc /debug[+|-]’. It doesn’t affect codegen, so it’s really not very interesting.
>
> Optimization. Set with ‘csc /optimize[+|-]’. In managed code, the JITter in the runtime does nearly all the optimization. The difference in generated IL from this flag is pretty small. The Whidbey C# compiler has more a difference on this flag than previous versions, but it’s still not much. | What happens to a DLL in debug mode inside a web application with debug=false? | [
"",
"c#",
".net",
"dll",
"debugging",
""
] |
> **Possible Duplicate:**
> [Difference between pointer variable and reference variable in C++](https://stackoverflow.com/questions/57483/difference-between-pointer-variable-and-reference-variable-in-c)
When should I declare my variables as pointers vs objects passed-by-reference? They compile to the same thing in assembly (at least run-time asymptotically) so when should I use which?
```
void foo(obj* param)
void foo(obj& param)
``` | My rule is simple: use \* when you want to show that value is optional and thus can be 0.
Excluding from the rule: all the \_obj\_s around are stored in containers and you don't want to make your code look ugly by using everywhere `foo(*value);` instead of `foo(value);`
So then to show that value can't be 0 put `assert(value);` at the function begin. | I follow the [Google style guide standard](http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml#Reference_Arguments) as it makes the most sense to me. It states:
> Within function parameter lists all
> references must be const:
>
> ```
> void Foo(const string &in, string *out);
> ```
>
> In fact it is a very strong convention
> in Google code that input arguments
> are values or const references while
> output arguments are pointers. Input
> parameters may be const pointers, but
> we never allow non-const reference
> parameters.
>
> One case when you might want an input
> parameter to be a const pointer is if
> you want to emphasize that the
> argument is not copied, so it must
> exist for the lifetime of the object;
> it is usually best to document this in
> comments as well. STL adapters such as
> bind2nd and mem\_fun do not permit
> reference parameters, so you must
> declare functions with pointer
> parameters in these cases, too. | c++ * vs & in function declaration | [
"",
"c++",
"pointers",
"reference",
"pass-by-reference",
""
] |
I am getting this error [alt text http://img239.imageshack.us/img239/6936/jserror.png](http://img239.imageshack.us/img239/6936/jserror.png) when the map loads.
The error is in the original, unmodified OpenLayers.js file on this line:
`return!!(document.namespaces);`
I have tried rewriting it to:
`return (typeof(document.namespaces) != 'undefined');`
and it worked but then I get same "unspecified" errors on further referrals to document.namespaces:
`if(!document.namespaces.olv){document.namespaces.add("olv",this.xmlns); ...`
I tried rewriting this to:
`if(typeof(document.namespaces.olv) == 'undefined') { ...`
but I get the same "unspecified error".
I only get this error on Internet Explorer (I tested on 7) and not in Firefox.
Any clues?
Thanks. | I have found the solution.
The problem was that I was creating the map when the DOM was ready with Jquery:
```
$(document).ready(function(){ ... //create map here [WRONG]
```
All you have to do is to create the map after the onload event:
```
window.onload = function() { ... // create map here [CORRECT]
``` | The real problem is that document.namespaces is not ready in IE8 sometimes when triggering $(document).ready (because of VML)
You can use instead :
```
jQuery(window).load(function() {} ...);
``` | Javascript "unspecified error" in Open Layers | [
"",
"javascript",
"dictionary",
"openlayers",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.