Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
While searching for how to do this, I found some vague discussion about different options, like JNI vs JNA, but not much in the way of concrete examples.
Context: if Java's `File.renameTo()` cannot do it's job (for whatever reason; [it is a little problematic](https://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows)), I'd like to fall back to directly using this native Windows function, which is defined in kernel32.dll ([from this answer](https://stackoverflow.com/questions/1000183/reliable-file-renameto-alternative-on-windows/1000308#1000308)):
```
BOOL WINAPI MoveFile(
__in LPCTSTR lpExistingFileName,
__in LPCTSTR lpNewFileName
);
```
So, using whatever approach, how exactly would you call that function from within Java code? I'm looking for the simplest way, with the minimum amount of non-Java code or extra steps (e.g. in compilation or deployment). | If you go with JNA, consider invoking [MoveFileW](http://msdn.microsoft.com/en-us/library/aa365239(VS.85).aspx) directly - it saves having to provide configuration info to choose between Unicode and ANSI calls.
```
import java.io.*;
import com.sun.jna.*;
public class Ren {
static interface Kernel32 extends Library {
public static Kernel32 INSTANCE = (Kernel32) Native
.loadLibrary("Kernel32", Kernel32.class);
public static int FORMAT_MESSAGE_FROM_SYSTEM = 4096;
public static int FORMAT_MESSAGE_IGNORE_INSERTS = 512;
public boolean MoveFileW(WString lpExistingFileName,
WString lpNewFileName);
public int GetLastError();
public int FormatMessageW(int dwFlags,
Pointer lpSource, int dwMessageId,
int dwLanguageId, char[] lpBuffer, int nSize,
Pointer Arguments);
}
public static String getLastError() {
int dwMessageId = Kernel32.INSTANCE.GetLastError();
char[] lpBuffer = new char[1024];
int lenW = Kernel32.INSTANCE.FormatMessageW(
Kernel32.FORMAT_MESSAGE_FROM_SYSTEM
| Kernel32.FORMAT_MESSAGE_IGNORE_INSERTS, null,
dwMessageId, 0, lpBuffer, lpBuffer.length, null);
return new String(lpBuffer, 0, lenW);
}
public static void main(String[] args) throws IOException {
String from = ".\\from.txt";
String to = ".\\to.txt";
new FileOutputStream(from).close();
if (!Kernel32.INSTANCE.MoveFileW(new WString(from),
new WString(to))) {
throw new IOException(getLastError());
}
}
}
```
---
EDIT: I've edited my answer after checking the code - I was mistaken about using char[] in the signature - it is better to use [WString](https://jna.dev.java.net/javadoc/com/sun/jna/WString.html). | If this is really necessary (renameTo doesn't work and you're sure MoveFile will), I would use [JNA](https://github.com/twall/jna/). It looks like most of the work is already done in com.mucommander.file.util.[Kernel32.java](http://trac.mucommander.com/browser/trunk/source/com/mucommander/file/util/Kernel32.java)/[Kernel32API.java](http://trac.mucommander.com/browser/trunk/source/com/mucommander/file/util/Kernel32API.java). | What is the easiest way to call a Windows kernel function from Java? | [
"",
"java",
"windows",
"winapi",
"java-native-interface",
"jna",
""
] |
I am trying to send an email using c# using the following code.
```
MailMessage mail = new MailMessage();
mail.From = new MailAddress(fromAddress, friendlyName);
mail.To.Add(toAddress);
mail.CC.Add(ccAddress);
//set the content
mail.Subject = emailSubject;
mail.Body = emailHeader + "\n" + emailBody;
//send the message
SmtpClient smtp = new SmtpClient(ServerAddress);
smtp.Credentials = CredentialCache.DefaultNetworkCredentials;
mail.IsBodyHtml = true;
smtp.Send(mail);
```
Now the "toAddress" string that my function recieves might contain a single address, or it might have many, comma delimited addresses.
Now the problem is that, in case of multiple comma delimited addresses, one or two of them might be of the wrong email address format.
So when I try to send an email using this code, I get the exception:
"The specified string is not in the form required for an e-mail address."
Is there any way to validate the comma delimited email addresses?
I had read somewhere that the only way to validate an email address is to send an email to it, because the regular expressions to validate an email addreess can be surprisingly huge.
Also, I have no control over the design, or on how that address string comes to my function,I can't add the email validation in the UI, so I am helpless there...
My problem is that the email will not be delivered to **ALL** the addresses in the comma delimited string, even though only **SOME** of the addresses are of the wrong format.
Is there any way to properly validate email addresses in .NET? Is there a way to weed out the bad email addresses and send the mail to only the good ones? | You could just split the email string on the comma and validate each email address using a simple (or huge) email regex. Or, try creating a `MailAddress` object; it supports some basic validation of the address too. | This is code we have on production (even added a comma for you). Normally you shouldn't use try/catch for validation, but it works well here. I believe it's better than trying to recode the validator.
```
string[] allToAddresses = to.Split(";,".ToCharArray(),
StringSplitOptions.RemoveEmptyEntries)
foreach (string toAddress in allToAddresses)
{
try
{
message.To.Add(toAddress);
}
catch (FormatException)
{
//do nothing, ill-formed address.
}
}
``` | Validating an email address | [
"",
"c#",
".net",
"email",
""
] |
I'm trying to setup a widget framework using jQuery, so I need to import java script by parsing the widget's xhtml and including in the framework page. The problem is that this may lead to pollution of the namespace. Is it possible to load java script into a namespace at runtime?
Perhaps there is some better method that I'm overlooking?
Thanks,
Pete | AS Josh Stodola mentioned creating the variable at runtime isn't the problem
```
var holdsWidgetUUID = "widgetUUIDValue";
eval(holdsWidgetUUID + "= (" + data + ")");
alert(eval(holdsWidgetUUID));
```
Or if you prefer
```
var UUID = "widgetUUID";
var holdsWidgetUUID = "widgetUUIDValue";
window["widgets"] = new Array();
window["widgets"][holdsWidgetUUID] = data;
alert(window["widgets"][holdsWidgetUUID]);
```
The problem is getting the loaded javascript to work an be callable like dynamicvariablename.methodname()
I have a working solution if you force a certain coding practice upon the included javascript. Maybe this gets you in the right direction.
This is a widgets javascript (works.js). Notive that it's a javascript "class" with internally defined fields and methods. Which by itself keeps namespace pollution low and allows us the achieve the desired calling form x.getInfo()
```
function () {
this.type = 1;
this.color = "red";
this.getInfo = function() {
return this.color + ' ' + this.type + ' widget';
};
}
```
And this is the file which includes it at runtime in a namespace
```
<html>
<head>
<title>Widget Magic?</title>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var UUID = "widgetUUID";
var holdsWidgetUUID = "widgetUUIDValue";
window["widgets"] = new Array();
$.get("works.js", function(data) {
window["widgets"][holdsWidgetUUID] = eval("(" + data + ")");
$(document).ready(function() {
window["widgets"][holdsWidgetUUID] = new (window["widgets"][holdsWidgetUUID])();
alert(window["widgets"][holdsWidgetUUID].color);
alert(window["widgets"][holdsWidgetUUID].getInfo());
});
});
</script>
</head>
<body>
<p>Just some stuff</p>
</body>
</html>
``` | You can do something like this...
```
var myOtherFramework = null;
$.get("myScript.js", function(data) {
myOtherFramework = eval("(" + data + ")");
});
```
And then reference it like...
```
myOtherFramework.funcName();
``` | Import javascript dynamically with jQuery? | [
"",
"javascript",
"jquery",
"dynamic",
""
] |
I have a bunch of HTML that is generated by a daemon using C, XML and XSL. Then I have a PHP script which picks up the HTML markup and displays it on the screen
I have a huge swathe of XHTML 1 compliant markup. I need to modify all of the links in the markup to remove `&utm_source=report&utm_medium=email&utm_campaign=report`.
So far I've considered two options.
1. Do a regex search in the PHP backend which trims out the Analytics code
2. Write some Jquery to loop through the links and then trim out the Analytics code from the href.
Hurdles:
1. The HTML can be HUGE. I.E. more than 4MB (ran some tests, they average at about 100Kb)
2. It has to be fast.We get approximately 3K
Thoughts?
Right now I'm trying to use `str_replace('&utm_source=report&utm_medium=email&utm_campaign=report','',$html);` but it's not working. | I eventually deferred to using str\_replace and replacing the string through the entire contents of the document :(. | You could use `sed` or some other low level tool to remove that parts:
```
find /path/to/dir -type f -name '*.html' -exec sed -i 's/&utm_source=report&utm_medium=email&utm_campaign=report//g' {} \;
```
But that would remove this string anywhere and not just in URLs. So be careful. | Is there a regular expression to strip specific query variables from a URI? | [
"",
"php",
"regex",
"xhtml",
"uri",
""
] |
I have a bunch of pages inheriting from a master view. One one of these pages I want to use a popular [jQuery](http://jquery.com/) plugin called "[Uploadify](http://www.uploadify.com/)".
Where should I place the reference for the Uploadify javascript file? I only need it on one small page so it didn't seem right to place it in Master view. Is it 'Ok' to place it in the content tag of my inherited view that will use this plugin? | The best way I know to do this is to add a `ContentPlaceHolder` in the `<head>` section of the `MasterPage`, and add the `<script>` tags to a `Content` referencing that section in all pages that need extra javascripts (or stylehseets, or whatever... It certainly adds an extra degree of freedom).
In you master:
```
<head>
<!-- Sitewide script references, title tags etc goes here -->
<asp:ContentPlaceHolder ID="HeadContent" runat="server" />
</head>
```
As it is empty by default, you don't have to change anything in any other pages to make this change to your master.
In your page that needs the extra js script:
```
<asp:Content ID="HeadContentFromPage" ContentPlaceHolderId="HeadContent">
<script type="text/javascript" src="myPageSpecificScript.js"></script>
</asp:Content>
``` | Put a [ScriptManager](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanager.aspx) control on your master page and include the commonly used JS files there:
```
<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Scripts>
<asp:ScriptReference Path="Common.js" />
</Scripts>
</asp:ScriptManager>
```
Put a [ScriptManagerProxy](http://msdn.microsoft.com/en-us/library/system.web.ui.scriptmanagerproxy%28loband%29.aspx) control on your content pages (or on any user controls) and include the specific JS files there:
```
<asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server" >
<Scripts>
<asp:ScriptReference Path="Specific.js" />
</Scripts>
</asp:ScriptManagerProxy>
```
**EDIT**: I'm not sure if this also works with ASP.NET **MVC**. | Where should I include a javascript reference for a view that inerhits from a Master view in ASP.NET MVC? | [
"",
"javascript",
"asp.net-mvc",
"view",
"master-pages",
""
] |
I've figured out how to get a `JTable` to be sorted properly, but I can't figure out how to get it to automatically update the sort order when a table cell is changed. Right now, I have this (admittedly long) code, mostly based on that in the Java Tutorial's [How to Use Tables](http://java.sun.com/docs/books/tutorial/uiswing/components/table.html). I've highlighted the changes I've made with `// ADDED`. In this case, newly-added values sort properly, but when I go in to edit a value, it doesn't seem to resort, even though I call `fireTableCellUpdated`?
In short, how can I get a table to re-sort when a data value changes in the model?
```
/*
* Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved.
* See the standard BSD license.
*/
package components;
/*
* TableSortDemo.java requires no other files.
*/
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
public class TableSortDemo extends JPanel {
private boolean DEBUG = false;
public TableSortDemo() {
super();
setLayout(new BoxLayout(TableSortDemo.this, BoxLayout.PAGE_AXIS));
final MyTableModel m = new MyTableModel();
JTable table = new JTable(m);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
table.setAutoCreateRowSorter(true);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Add the scroll pane to this panel.
add(scrollPane);
// ADDED: button to add a value
JButton addButton = new JButton("Add a new value");
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
m.addValue(
JOptionPane.showInputDialog(
TableSortDemo.this, "Value?"));
}
});
// ADDED button to change a value
JButton setButton = new JButton("Change a value");
setButton.addActionListener(new ActionListener() {
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent e) {
m.setValueAt(
JOptionPane.showInputDialog(
TableSortDemo.this, "Value?"),
Integer.parseInt(
JOptionPane.showInputDialog(
TableSortDemo.this, "Which?")), 0);
}
});
add(addButton);
add(setButton);
}
class MyTableModel extends AbstractTableModel {
private static final long serialVersionUID = -7053335255134714625L;
private String[] columnNames = {"Column"};
// ADDED data as mutable ArrayList
private ArrayList<String> data = new ArrayList<String>();
public MyTableModel() {
data.add("Anders");
data.add("Lars");
data.add("Betty");
data.add("Anna");
data.add("Jon");
data.add("Zach");
}
// ADDED
public void addValue(Object v) {
data.add(v.toString());
int row = data.size() - 1;
fireTableRowsInserted(row, row);
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data.get(row) + " " + row;
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class<String> getColumnClass(int c) {
return String.class;
}
/*
* Don't need to implement this method unless your table's
* editable.
*/
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
/*
* Don't need to implement this method unless your table's
* data can change.
*/
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data.set(row, value.toString());
// ADDED: uncommented this line, despite warnings to the contrary
fireTableCellUpdated(row, col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data.get(i));
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableSortDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableSortDemo newContentPane = new TableSortDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
``` | This took a two-step solution:
First I had the TableSorter sort on data change, by using this rather than `autoCreateRowSorter`:
```
sorter = new TableRowSorter<MyTableModel>(m);
table.setRowSorter(sorter);
sorter.setSortsOnUpdates(true);
```
Then, I had to change the update method to update the entire table. The `fireTableCellUpdated` and the `fireTableRowsUpdated` would only redraw the specific rows that were updated, not the entire table (meaning you'd get a duplicate-appearing entry that changed as soon as it was redrawn later. So, I changed
```
fireTableCellUpdated(row, col);
```
to
```
fireTableRowsUpdated(0, data.size() - 1);
```
and now it sorts properly, even upon data changes, and selection is preserved. | Its a [long-standing bug on JTable](https://bugs.java.com/bugdatabase/view_bug?bug_id=6539455), reported in 2007 (astonished that it isn't fixed, not even in jdk7)
Firing a update on all rows is a reasonable quick fix if it doesn't degrade performance too much (due to triggering frequent complete resorts). For the fearless, here's a partial fix on JTable - partial, because not yet all possible scenarios are captured. Which is the reason it never made it into JXTable (or maybe I had other priorities then :-)
```
public static class JTableRepaintOnUpdate extends JTable {
private UpdateHandler beforeSort;
@Override
public void sorterChanged(RowSorterEvent e) {
super.sorterChanged(e);
maybeRepaintOnSorterChanged(e);
}
private void beforeUpdate(TableModelEvent e) {
if (!isSorted()) return;
beforeSort = new UpdateHandler(e);
}
private void afterUpdate() {
beforeSort = null;
}
private void maybeRepaintOnSorterChanged(RowSorterEvent e) {
if (beforeSort == null) return;
if ((e == null) || (e.getType() != RowSorterEvent.Type.SORTED)) return;
UpdateHandler afterSort = new UpdateHandler(beforeSort);
if (afterSort.allHidden(beforeSort)) {
return;
} else if (afterSort.complex(beforeSort)) {
repaint();
return;
}
int firstRow = afterSort.getFirstCombined(beforeSort);
int lastRow = afterSort.getLastCombined(beforeSort);
Rectangle first = getCellRect(firstRow, 0, false);
first.width = getWidth();
Rectangle last = getCellRect(lastRow, 0, false);
repaint(first.union(last));
}
private class UpdateHandler {
private int firstModelRow;
private int lastModelRow;
private int viewRow;
private boolean allHidden;
public UpdateHandler(TableModelEvent e) {
firstModelRow = e.getFirstRow();
lastModelRow = e.getLastRow();
convert();
}
public UpdateHandler(UpdateHandler e) {
firstModelRow = e.firstModelRow;
lastModelRow = e.lastModelRow;
convert();
}
public boolean allHidden(UpdateHandler e) {
return this.allHidden && e.allHidden;
}
public boolean complex(UpdateHandler e) {
return (firstModelRow != lastModelRow);
}
public int getFirstCombined(UpdateHandler e) {
if (allHidden) return e.viewRow;
if (e.allHidden) return viewRow;
return Math.min(viewRow, e.viewRow);
}
public int getLastCombined(UpdateHandler e) {
if (allHidden || e.allHidden) return getRowCount() - 1;
return Math.max(viewRow, e.viewRow);
}
private void convert() {
// multiple updates
if (firstModelRow != lastModelRow) {
// don't bother too much - calculation not guaranteed to do anything good
// just check if the all changed indices are hidden
allHidden = true;
for (int i = firstModelRow; i <= lastModelRow; i++) {
if (convertRowIndexToView(i) >= 0) {
allHidden = false;
break;
}
}
viewRow = -1;
return;
}
// single update
viewRow = convertRowIndexToView(firstModelRow);
allHidden = viewRow < 0;
}
}
private boolean isSorted() {
// JW: not good enough - need a way to decide if there are any sortkeys which
// constitute a sort or any effective filters
return getRowSorter() != null;
}
@Override
public void tableChanged(TableModelEvent e) {
if (isUpdate(e)) {
beforeUpdate(e);
}
try {
super.tableChanged(e);
} finally {
afterUpdate();
}
}
/**
* Convenience method to detect dataChanged table event type.
*
* @param e the event to examine.
* @return true if the event is of type dataChanged, false else.
*/
protected boolean isDataChanged(TableModelEvent e) {
if (e == null) return false;
return e.getType() == TableModelEvent.UPDATE &&
e.getFirstRow() == 0 &&
e.getLastRow() == Integer.MAX_VALUE;
}
/**
* Convenience method to detect update table event type.
*
* @param e the event to examine.
* @return true if the event is of type update and not dataChanged, false else.
*/
protected boolean isUpdate(TableModelEvent e) {
if (isStructureChanged(e)) return false;
return e.getType() == TableModelEvent.UPDATE &&
e.getLastRow() < Integer.MAX_VALUE;
}
/**
* Convenience method to detect a structureChanged table event type.
* @param e the event to examine.
* @return true if the event is of type structureChanged or null, false else.
*/
protected boolean isStructureChanged(TableModelEvent e) {
return e == null || e.getFirstRow() == TableModelEvent.HEADER_ROW;
}
}
``` | Live sorting of JTable | [
"",
"java",
"model-view-controller",
"swing",
"sorting",
"jtable",
""
] |
I am designing a website using PHP 5.2.9 and MS Sql Server 2005. I have an SSRS report and I want to set it up so that people over the internet can access it (after they put in a username and password, but i can figure that part out).
Our website is hosted locally on a web server and the database is on a seperate server. I haven't set up the SSRS instance yet.
So any help on figuring out how to do this would be awesome (it's a bit too late in the game to change over to asp.net( | Well I found some documentation from microsoft on the whole matter [here](http://technet.microsoft.com/en-us/library/ms159272(SQL.90).aspx). I've got it up and running now so I am happy. although in order for it to be perfect i still need another firewall between the web server and the rest of the network. | Simplest way to tackle this is to look into what MS calls "URL Access" which allows you to link to a report hosted on an SSRS installation. Lots of ways to customize through all of the URL Access parameters.
Take a look here: [URL Access](http://msdn.microsoft.com/en-us/library/ms153586.aspx)
Simple Example:
`http://<Server Name>/reportserver?/Sales/YearlySalesByCategory&rs:Command=Render`
The link above would cause the report to be rendered in the web browser just like a normal page. You can also specify other render modes such as PDF. What I normally do in my applications is for the user to click on a link referencing the report, with the render mode set to PDF. You can then wrap all your security and authentication code around it so it is kept away from those you don't want to use it. | Internet Facing SSRS Report | [
"",
"php",
"reporting-services",
""
] |
I'm developing a site for a client who already have the photos of his products on Facebook, and he wants the same albums to be replicated over his site. I was already using Facebook Connect, so I dropped a combination of `photos.getAlbums` and `photos.get` to dynamically make the galleries.
So far so good, but then I realized that if there's no user logged trough FBC, no session is created and the API becomes unusable, even for content that is publicly available. I obviously want to show the albums to everyone and not just the people who connect their accounts.
Is this how all functions in the Facebook API work? What's the best (easier to implement) workaround for this situation? | As of September 2010, you can now authenticate just as an application, with no associated user. See <http://developers.facebook.com/docs/authentication/> for details. Or you can run this example code to get an access token:
```
curl -F grant_type=client_credentials \
-F client_id=your_app_id \
-F client_secret=your_app_secret \
https://graph.facebook.com/oauth/access_token
``` | For the record, I managed to solve this situation by developing a small backend that requires the client to login to Facebook once and give `offline_access` [extended permission](http://wiki.developers.facebook.com/index.php/Extended_permissions) to the FB app, so I can save his session key and use it to authenticate the Facebook API client every time I need to use FQL to get non-public content.
One could obviously add some caching in the middle to avoid unnecessary requests to Facebook, but it's been working fine for months now without hitting any limits that I know of. | Facebook API without client authentication for public content | [
"",
"php",
"api",
"authentication",
"facebook",
""
] |
I'm writing an iPhone web app, and I want to automatically focus a text field when the page is loaded, bringing up the keyboard. The usual Javascript:
```
input.focus();
```
doesn't seem to be working. Any ideas? | **Note**: this answer is old and may not be relevant to newer versions out there...
---
It comes as no help to you but the last poster in [this](http://discussion.forum.nokia.com/forum/showthread.php?t=127724) thread wrote that its a bug of the webkit engine.
I can't tell if its a verified bug or not...
Last post from [way back machine](http://web.archive.org/web/20090831121948/http://discussion.forum.nokia.com/forum/showthread.php?t=127724) (as original seems to not work):
> I am developing my app in pure XHTML MP / Ecmascript MP / WCSS. So
> using native platform browser control api is really not an option for
> me. Yes the behaviour u mention is the same as mine. I searched his
> topic in the bugzilla at webkit.org and found that this indeed is a
> reported bug. focus() to a text box does highlight the element but
> does not provide a carat in it for the user to start entering text.
> Using a timer as mentioned by "peppe@peppe.net" does not help either.
>
> This behaviour is common across platforms (s60,iphone,android) which
> use the webkit engine.
>
> So as of now i dont see a solution to this problem.
>
> Hope this helps | It will only show the keyboard if you fire focus from a click event, so put a button on the page with a onclick that does the focus and it will show the keyboard. Completely useless except for validation (on click of submit validation code focuses on invalid element) | How do I focus an HTML text field on an iPhone (causing the keyboard to come up)? | [
"",
"javascript",
"iphone",
"html",
""
] |
Does anyone know of source code, ideally in C# or similar, for reading .DXF files (as used by AutoCAD etc)? If not code, then tables showing the various codes (elements / blocks / etc) and their meanings?
I am writing a reader myself, and have dead tree documentation detailing the format, but am trying to avoid writing e.g. a converter from each of the 255 ACI colours to RGB... Thanks! | [Cadlib](http://www.woutware.com/cadlib.html) from WoutWare have I been using for a couple of projects with good results. | I have work a couple of years at developing my own [DXf-Viewer in java](http://www.hauk-sasko.de/fileadmin/dxf_viewer/dxf_viewer_applet.html) (you could drop your own DXF file or an URL on the viewer) for 2D drawings.
The published information from AutoCAD is a good base but doesn't explain how it works.
Becoming member of the Open Design Alliance, will give you the possibility to convert several CAD formats to DXF. It may be a good idea if you are developing a commercial product.
There is a german book (<http://www.crlf.de/Verlag/DXF-intern/DXF-intern.html>) about DXF which really explain this format. It's expensive, but could save days of search.
The colors in the DXF Format are indexed, you must have a converter from ACI to RGB. Be careful with values 0 and 1 which having a special meaning.
Regards. | Reading .DXF files | [
"",
"c#",
"autocad",
"dxf",
""
] |
How do you create a hidden field in JavaScript into a particular form ?
```
<html>
<head>
<script type="text/javascript">
var a =10;
function test() {
if (a ==10) {
// ... Here i need to create some hidden field for form named = chells
}
}
</script>
</head>
<body >
<form id="chells" name="formsdsd">
<INPUT TYPE=BUTTON OnClick="test();">
</form>
</body>
</html>
``` | ```
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
``` | You can use jquery for create element on the fly
```
$('#form').append('<input type="hidden" name="fieldname" value="fieldvalue" />');
```
or other way
```
$('<input>').attr({
type: 'hidden',
id: 'fieldId',
name: 'fieldname'
}).appendTo('form')
``` | Create a hidden field in JavaScript | [
"",
"javascript",
""
] |
I was wondering if there is a Java library that acts as a wrapper for the Google Maps API. What I am interested in is displaying a satellite map of a specific region (lon, lat) on my desktop application. It doesn't have to be Google Maps specifically, any map service would do the trick.
What I need though is a library to work with a desktop client, no javascript, GWT etc.
Any ideas? | If you are just looking to display a satellite map image for a specific latitude longitude (without the google maps panning/zooming etc), then you should check out [Google Static Maps](http://code.google.com/apis/maps/documentation/staticmaps/).
You just need to build a URL string, then make an HTTP request (from your java implementation) for the image (in whatever format you like). You can specify a whole bunch of [parameters](http://code.google.com/apis/maps/documentation/staticmaps/#URL_Parameters) in the URL to get the satellite image you are after:

From the URL:
```
http://maps.google.com/staticmap?center=40,26&zoom=1&size=150x112&maptype=satellite&key=ABQIAAAAgb5KEVTm54vkPcAkU9xOvBR30EG5jFWfUzfYJTWEkWk2p04CHxTGDNV791-cU95kOnweeZ0SsURYSA&format=jpg
```
EDIT: Ok, I actually deleted this answer because I discovered [section 10.8 in the TOS](http://code.google.com/apis/maps/terms.html#section_10_8) explicitly forbids accessing static maps from outside a browser. But then I discovered this [FAQ update](http://code.google.com/apis/maps/faq.html#tos_nonweb) which seems to allow it. I might ask a Google person and get the final word.
EDIT: Thanks [Paracycle](https://stackoverflow.com/users/98634/paracycle), not sure if that is a new addition to the FAQ, but in any case it is pretty explicit, [you are **not** allowed to do this](http://code.google.com/apis/maps/faq.html#mapsformobile). | Google maps does not allow for using it's images in desktop applications. Microsoft has a collaboration with USGS at <http://terraserver-usa.com/>. There is a [freely available web service](http://terraserver-usa.com/webservices.aspx) with a [WSDL](http://terraserver-usa.com/TerraService2.asmx). You can use common Java WSDL binding libraries like [Axis](http://ws.apache.org/axis2/) or [CXF](http://cxf.apache.org/) to create java object to access the service.
Also, NASA has the [World Wind](http://worldwind.arc.nasa.gov/java/index.html) project which has a Java API. The images are not the Google images but much of the Google images are based off of these images. | Java API for Google Maps (or similar) | [
"",
"java",
"google-maps",
""
] |
I found a simple pure python blowfish implementation that meets my needs for a particular project.
There's just one part of it that bothers me:
```
def initialize(key):
"""
Use key to setup subkeys -- requires 521 encryptions
to set p and s boxes. key is a hex number corresponding
to a string of 32 up to 448 1s and 0s -- keylen says
how long
"""
# Note that parray and sboxes are globals that have been pre-initialized.
hexkey = hex(key)[2:]
if hexkey[-1]=='L':
hexkey = hexkey[:-1]
if len(hexkey)%2==1:
hexkey = '0'+hexkey
lenkey = len(hexkey)/8
if lenkey==0:
pos=0
# XOR key segments with P-boxes
for i in range(18):
if lenkey>0:
pos = (i%lenkey)*8 # offset into key gives subkey
subkey = eval('0x'+hexkey[pos:pos+8]+'L')
parray[i] ^= subkey # immediate XOR -- Python 2.0+ syntax
# encrypt 0-data, then keep re-encrypting and reassigning P-boxes
output = 0L
for i in range(0,17,2):
output = bfencrypt(output)
parray[i], parray[i+1] = output>>32, output & 0xFFFFFFFFL
# re-encrypt and reassign through all the S-boxes
for i in range(4):
for j in range(0,255,2):
output = bfencrypt(output)
sbox[i][j],sbox[i][j+1] = output>>32, output & 0xFFFFFFFFL
# print "Initialization complete"
```
**`subkey = eval('0x'+hexkey[pos:pos+8]+'L')`**? Please tell me there's a better way to do this.
Isn't there a way to refactor this to use an actual integer type rather than hex values in a string? | Yes. Use int() with a base of 16.
```
>>> int('ffffffff',16)
4294967295L
```
so:
```
subkey = int(hexkey[pos:pos+8], 16)
```
should do the same thing without needing eval.
**[Edit]** In fact, there's generally no reason why you'd need to convert to a string representation at all, given an integer - you can simply extract out each 32 bit value by ANDing with `0xffffffff` and shifting the key right by 32 bits in a loop. eg:
```
subkeys = []
while key:
subkeys.append(key & 0xffffffff)
key >>= 32
if not subkeys: subkeys = [0] # Handle 0 case
subkeys.reverse() # Use same order as before (BUT SEE BELOW)
```
However, this initialization process seems a bit odd - it's using the hex digits starting from the left, with no zero padding to round to a multiple of 8 hex digits (so the number `0x123456789` would be split into `0x12345678` and `0x9`, rather than the more customary `0x00000001` and `0x23456789`. It also repeats these numbers, rather than treating it as a single large number. You should check that this code is actually performing the correct algorithm. | **Don't use this code, much less try to improve it.**
Using crypto code found on the internet is likely to cause serious security failures in your software. See [Jeff Atwood's little series](http://www.codinghorror.com/blog/archives/001275.html) on the topic.
It is much better to use a proven crypto library at the highest possible level of abstraction. Ideally one that implements all the key handling in C and takes care of destroying key material after use.
One problem of doing crypto in Python is that you have no control over proliferation of key material in memory due to the nature of Python strings and the garbage collection process. | Refactor this block cipher keying function | [
"",
"python",
"encryption",
""
] |
When I tried to get the content of a tag using "unicode(head.contents[3])" i get the output similar to this: "Christensen Sk\xf6ld". I want the escape sequence to be returned as string. How to do it in python? | Assuming Python sees the name as a normal string, you'll first have to decode it to unicode:
```
>>> name
'Christensen Sk\xf6ld'
>>> unicode(name, 'latin-1')
u'Christensen Sk\xf6ld'
```
Another way of achieving this:
```
>>> name.decode('latin-1')
u'Christensen Sk\xf6ld'
```
Note the "u" in front of the string, signalling it is uncode. If you print this, the accented letter is shown properly:
```
>>> print name.decode('latin-1')
Christensen Sköld
```
BTW: when necessary, you can use de "encode" method to turn the unicode into e.g. a UTF-8 string:
```
>>> name.decode('latin-1').encode('utf-8')
'Christensen Sk\xc3\xb6ld'
``` | I suspect that it's acutally working correctly. By default, Python displays strings in ASCII encoding, since not all terminals support unicode. If you actually print the string, though, it should work. See the following example:
```
>>> u'\xcfa'
u'\xcfa'
>>> print u'\xcfa'
Ïa
``` | How do convert unicode escape sequences to unicode characters in a python string | [
"",
"python",
"unicode",
"python-2.x",
""
] |
What is the difference between $str[n] and $str{n}, given that $str is a string.
I noticed that both seem to work the same, except that {} does not occur in any documentation I found. | They are the same. However, they are getting rid of the `{}` syntax, so you should go with `[]`.
[According to the manual](http://www.php.net/language.types.string):
> Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in `$str[42]`. Think of a string as an array of characters for this purpose. The functions `substr()` and `substr_replace()` can be used when you want to extract or replace more than 1 character.
>
> Note: As of PHP 7.1.0, negative string offsets are also supported. These specify the offset from the end of the string. Formerly, negative offsets emitted `E_NOTICE` for reading (yielding an empty string) and `E_WARNING` for writing (leaving the string untouched).
>
> **Note**: Prior to PHP 8.0.0, strings could also be accessed using braces, as in $str{42}, for the same purpose. This curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0. | Be careful, `$str[n]` and `$str{n}` give n-th Byte of `String`, not n-th character of `String`. For multibyte encoding (UTF-8, etc.) one character doesn't need to be one Byte.
`$str[0]` – first Byte of string
`mb_substr($str, 0, 1)` – first character of string (including multibyte charsets)
<http://php.net/mb_substr> | PHP: string indexing | [
"",
"php",
"string",
""
] |
I was trying to use the Apache Ant [`Get` task](http://ant.apache.org/manual/Tasks/get.html) to get a list of WSDLs generated by another team in our company. They have them hosted on a weblogic 9.x server on <http://....com:7925/services/>. I am able to get to the page through a browser, but the get task gives me a FileNotFoundException when trying to copy the page to a local file to parse. I was still able to get (using the ant task) a URL without the non-standard port 80 for HTTP.
I looked through the Ant source code, and narrowed the error down to the URLConnection. It seems as though the URLConnection doesn't recognize the data is HTTP traffic, since it isn't on the standard port, even though the protocol is specified as HTTP. I sniffed the traffic using WireShark and the page loads correctly across the wire, but still gets the FileNotFoundException.
Here's an example where you will see the error (with the URL changed to protect the innocent). The error is thrown on **connection.getInputStream();**
```
import java.io.File;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class TestGet {
private static URL source;
public static void main(String[] args) {
doGet();
}
public static void doGet() {
try {
source = new URL("http", "test.com", 7925,
"/services/index.html");
URLConnection connection = source.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
} catch (Exception e) {
System.err.println(e.toString());
}
}
}
``` | check the response code being returned by the server | The response to my HTTP request returned with a status code 404, which resulted in a FileNotFoundException when I called getInputStream(). I still wanted to read the response body, so I had to use a different method: **HttpURLConnection#getErrorStream()**.
Here's a JavaDoc snippet of getErrorStream():
> Returns the error stream if the
> connection failed but the server sent
> useful data nonetheless. The typical
> example is when an HTTP server
> responds with a 404, which will cause
> a FileNotFoundException to be thrown
> in connect, but the server sent an
> HTML help page with suggestions as to
> what to do.
Usage example:
```
public static String httpGet(String url) {
HttpURLConnection con = null;
InputStream is = null;
try {
con = (HttpURLConnection) new URL(url).openConnection();
con.connect();
//4xx: client error, 5xx: server error. See: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html.
boolean isError = con.getResponseCode() >= 400;
//In HTTP error cases, HttpURLConnection only gives you the input stream via #getErrorStream().
is = isError ? con.getErrorStream() : con.getInputStream();
String contentEncoding = con.getContentEncoding() != null ? con.getContentEncoding() : "UTF-8";
return IOUtils.toString(is, contentEncoding); //Apache Commons IO
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
//Note: Closing the InputStream manually may be unnecessary, depending on the implementation of HttpURLConnection#disconnect(). Sun/Oracle's implementation does close it for you in said method.
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
if (con != null) {
con.disconnect();
}
}
}
``` | URLConnection FileNotFoundException for non-standard HTTP port sources | [
"",
"java",
"ant",
"urlconnection",
""
] |
Is declaring/assigning a variable in a high level language such as c++, an explicit instruction?
e.g. x = 5;
It would be handled by the loader, and treated as state information, correct?
It is not an instruction, but a state object, as opposed to something like a for loop, which is an instruction, which makes it's way to the cpu ?
edit: OK, to clarify a bit more. I am not talking about optimisations. Assume none. I am talking about the end result of a compiled program, in an executable file format. Under the circumstances where the compiler decides not to use the MOV instruction, will the data 5 exist within the executables files data segment, or somewhere else?
Is it possible for the 5 to exist as data without being an instruction, with that data later on being loaded into memory? Or, in general, will x = 5 result in a mov instruction when the program is executed. | If your variable is a primitive type (int, char, etc.):
For a global or static variable, no. This is just an entry in the BSS or DATA segment (depending on if it is initialized or not), no executable code required. Except, of course, if the initializer has to be evaluated at runtime.
For a local variable, if it's not initialized, usually the first one implies an assembly instruction, the others not. That's because the space allocation for them is usually made adding an offset to the stack pointer (in fact, subtracting - the stack grows backwards). When you declare your first int variable, an "ADD SP, 4" is generated; for the second, it's just changed to "ADD SP, 8". This instruction will not be at the place where you declare your variable, but instead at the function begin, because all the stack space for local variables must be allocated there.
If you initialize a local variable at creation, then you will have a MOV instruction to load the value to its location in the stack. This instruction will be at the same place as the declaration, in relation to the rest of the code.
These rules for local variables assume no optimization. One common form of optimization is to use CPU registers as variables, in this case no allocation is needed, but initialization will generate an instruction. Also, sometimes these registers must have their values preserved, so you'll see a PUSH instruction at the begin and a POP at the end of the function.
The rules for objects when no constructor are involved (or the constructor is inlined) are a lot more complicated, but a similar logic applies. When you have a non-inlined constructor, of course you need at least an instruction for its call. | Are you asking if a variable declaration will translate into an assembly instruction in the same way an add or delete would? If so, then the general answer is there is no **direct** translation into assembly.
There may be instructions which facilitate the declaration of a variable such as updating the stack pointer to make space for a variable. But there is no x86 assembly instruction which says declare variable of this type on the stack.
Most of my experience is with x86 and amd64 chips so there could be instructions on other processors but I am not aware of them (but would be curious to read about them if they did exist).
Variable assignment is a bit different. The **general** case of x=5 will translate to some type of assembly instruction (writing the value to a register for instance). However with C++ it's really hard to be specific because there are many optimizations and chip specific settings that could cause a particular line to have no translation in machine code. | is declaring a variable an instruction | [
"",
"c++",
""
] |
I have a WinForm app that has other child forms (not mdi). If the user presses "Esc" the topmost form should be closed even if it doesn't have the focus.
I can use a keyboard hook to globally catch the Escape but I also need the handle of the form to be closed.
I guess there is a way to do that using Win32 API, but is there a solution using managed code? | Here is one way to get the topmost form that uses Win32 (not very elegant, but it works):
```
public const int GW_HWNDNEXT = 2; // The next window is below the specified window
public const int GW_HWNDPREV = 3; // The previous window is above
[DllImport("user32.dll")]
static extern IntPtr GetTopWindow(IntPtr hWnd);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool IsWindowVisible(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto, EntryPoint = "GetWindow", SetLastError = true)]
public static extern IntPtr GetNextWindow(IntPtr hwnd, [MarshalAs(UnmanagedType.U4)] int wFlag);
/// <summary>
/// Searches for the topmost visible form of your app in all the forms opened in the current Windows session.
/// </summary>
/// <param name="hWnd_mainFrm">Handle of the main form</param>
/// <returns>The Form that is currently TopMost, or null</returns>
public static Form GetTopMostWindow(IntPtr hWnd_mainFrm)
{
Form frm = null;
IntPtr hwnd = GetTopWindow((IntPtr)null);
if (hwnd != IntPtr.Zero)
{
while ((!IsWindowVisible(hwnd) || frm == null) && hwnd != hWnd_mainFrm)
{
// Get next window under the current handler
hwnd = GetNextWindow(hwnd, GW_HWNDNEXT);
try
{
frm = (Form)Form.FromHandle(hwnd);
}
catch
{
// Weird behaviour: In some cases, trying to cast to a Form a handle of an object
// that isn't a form will just return null. In other cases, will throw an exception.
}
}
}
return frm;
}
``` | How about this using [Application.Openforms](http://msdn.microsoft.com/en-us/library/system.windows.forms.application.openforms.aspx)
```
Form GetTopMostForm()
{
return Application.OpenForms
.Cast<Form>()
.First(x => x.Focused);
}
``` | How to get the handle of the topmost form in a WinForm app? | [
"",
"c#",
"winforms",
"winapi",
"topmost",
""
] |
How do I convert a `java.io.File` to a `byte[]`? | It depends on what best means for you. Productivity wise, don't reinvent the wheel and use Apache Commons. Which is here [`FileUtils.readFileToByteArray(File input)`](https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)). | From **JDK 7** you can use [`Files.readAllBytes(Path)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllBytes(java.nio.file.Path)).
Example:
```
import java.io.File;
import java.nio.file.Files;
File file;
// ...(file is initialised)...
byte[] fileContent = Files.readAllBytes(file.toPath());
``` | File to byte[] in Java | [
"",
"java",
"file-io",
""
] |
I'm using SQL Server 2005. With the query below (simplified from my real query):
```
select a,count(distinct b),sum(a) from
(select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null) a
group by a
```
Is there any way to do a count distinct without getting
"Warning: Null value is eliminated by an aggregate or other SET operation."
Here are the alternatives I can think of:
1. Turning ANSI\_WARNINGS off
2. Separating into two queries, one with count distinct and a where clause to eliminate nulls, one with the sum:
```
select t1.a, t1.countdistinctb, t2.suma from
(
select a,count(distinct b) countdistinctb from
(
select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null
) a
where a.b is not null
group by a
) t1
left join
(
select a,sum(a) suma from
(
select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null
) a
group by a
) t2 on t1.a=t2.a
```
3. Ignore the warning in the client
Is there a better way to do this? I'll probably go down route 2, but don't like the code duplication. | ```
select a,count(distinct isnull(b,-1))-sum(distinct case when b is null then 1 else 0 end),sum(a) from
(select 1 a,1 b union all
select 2,2 union all
select 2,null union all
select 3,3 union all
select 3,null union all
select 3,null) a
group by a
```
Thanks to Eoin I worked out a way to do this. You can count distinct the values including the nulls and then remove the count due to nulls if there were any using a sum distinct. | Anywhere you have a null possibly returned, use
```
CASE WHEN Column IS NULL THEN -1 ELSE Column END AS Column
```
That will sub out all your Null Values for -1 for the duration of the query and they'll be counted/aggregated as such, then you can just do the reverse in your fine wrapping query...
```
SELECT
CASE WHEN t1.a = -1 THEN NULL ELSE t1.a END as a
, t1.countdistinctb
, t2.suma
``` | Count distinct and Null value is eliminated by an aggregate | [
"",
"sql",
"sql-server",
"sql-server-2005",
"null",
"aggregate",
""
] |
I'm trying to write a regular expression in PHP. From this code I want to match 'bar'.
```
<data info="foo">
"bar"|tr
</data>
```
I tried this two regex, without success. It matches 'foo"> "bar'.
```
$regex = '/"(.*?)"\|tr/s';
$regex = '/"[^"]+(.*?)"\|tr/s';
```
Anyone can help me? | You need to escape the backslash in PHP strings:
```
$regex = '/"([^"]*)"\\|tr/s';
```
I added a capturing group to get the contents of the quotes, which you seem to be interested in.
Since you seem to apply the regex to XML, I just want to warn you that XML and regular expressions don't play well together. Regex is only recommendable in conjunction with a DOM. | ```
\"\w+\"
```
should match any word char in parenthesis | PHP regular expression to extract quoted text in tag body | [
"",
"php",
"regex",
""
] |
.Net's odd locking semantics are bugging me again.
I'm launching a thread, the child thread in turns starts a form. The parent thread should wait until the form is created.
My first attempt was to use a Monitor to watch the Form variable:
```
private void OpenForm()
{
if (FormThread == null)
{
Monitor.Enter(Form);
FormThread = new Thread(FormStub);
FormThread.SetApartmentState(ApartmentState.STA);
FormThread.Start();
Monitor.Wait(Form);
Monitor.Exit(Form);
}
}
private void FormStub()
{
Form = new ConnectorForm();
Monitor.Enter(Form);
Monitor.PulseAll(Form);
Monitor.Exit(Form);
Application.Run(Form);
}
```
... This throws an exception. Monitor.Enter() fails, since Form == null.
I could very easily create a dummy integer or something (I actually think I'll canabalize the FormThread variable), but I was wondering if there was a more elegant solution. | Better synchronisation primitive for this case:
```
private ManualResetEvent mre = new ManualResetEvent(false);
private void OpenForm()
{
if (FormThread == null)
{
FormThread = new Thread(FormStub);
FormThread.SetApartmentState(ApartmentState.STA);
FormThread.Start();
mre.WaitOne();
}
}
private void FormStub()
{
Form = new ConnectorForm();
mre.Set();
Application.Run(Form);
}
``` | Doesn't performing a spin-wait on the current thread delete the whole point of using a separate thread to lanch the new form? Unless I'm misunderstanding something, you just want to create the new form synchronously. (Is there any reason it needs to reside in a different STA?) | C#: Wait for variable to become non-null | [
"",
"c#",
"multithreading",
"monitor",
""
] |
I'm trying to generate php files that 'include' a template html file, as so:
```
$page = htmlspecialchars("Hello! <?php include("template.html"); ?>");
```
But, when I run it, I get:
Parse error: syntax error, unexpected T\_STRING in /home/oliver/web/postmanapp.com/public/core.php on line 15
I'm pretty sure I need to escape the PHP code, just not sure how. | You have to escape any double quotes inside strings that are declared in double quotes. So this should work:
```
$code = "Hello! <?php include(\"template.html\"); ?>";
```
See [PHP manual about strings](http://docs.php.net/manual/en/language.types.string.php).
And if you want to put that code into a file, you could use the [`file_put_contents` function](http://docs.php.net/file_put_contents):
```
file_put_contents('myscript.php', $code);
``` | The answer is a combination of some of the other suggestions, but neither of them would solve the problem, even combined!
**Problem 1. Unescaped Double Quotes**
```
"Hello! <?php include("template.html"); ?>"
```
Here you have what looks like a single string. PHP sees the opening quote, and then it gets to the quote right before the word template and it says: oh, the string is done now. Then it sees template, which it thinks is a variable. Then it sees a dot and thinks it's a new concatenation operator. Then it sees the quote mark after `html` and it thinks it's a new string, which isn't allowed right after a variable like that.
So, you need either:
```
'Hello! <?php include("template.html"); ?>'
```
(Which is what I would recommend. Single quoted strings in PHP run slightly faster because it doesn't have to look inside the string for variables.)
or, as the other person suggested, using the escape character for the double quotes:
```
"Hello! <?php include(\"template.html\"); ?>"
```
**Problem 2. Wrong place for htmlspecialchars()**
But, you have another, worse problem. htmlspecialchars basically turns all HTML characters into their HTML character entities.
In other words, **`<`** becomes **`<`**.
So, what you're outputting into your PHP file will be this:
```
Hello! <?php include("template.html"); ?>
```
When you run that file, the PHP won't execute, because there isn't a valid open tag.
**Problem 3. This is not a good use of include**
I'm betting there's a WAY better way to solve your problem than to use PHP to write a PHP include tag that includes ANOTHER file.
An earlier user is right... file\_put\_contents() or file\_get\_contents() is probably something closer to what you want. But really, any time you're using PHP to write to PHP another file, there's probably a better way. I almost guarantee it. | Include dynamic PHP in generated php file | [
"",
"php",
""
] |
There are a number of ways to compare strings. Are there performance gains by doing one way over another?
I've always opted to compare strings like so:
```
string name = "Bob Wazowski";
if (name.CompareTo("Jill Yearsley") == 0) {
// whatever...
}
```
But I find few people doing this, and if anything, I see more people just doing a straight == comparison, which to my knowledge is the worst way to compare strings. Am I wrong?
Also, does it make a difference in how one compares strings within LINQ queries? For example, I like to do the following:
```
var results = from names in ctx.Names
where names.FirstName.CompareTo("Bob Wazowski") == 0
select names;
```
But again, I see few people doing string comparisons like so in their LINQ queries. | According to Reflector
```
"Hello" == "World"
```
is the same as
```
String.Equals("Hello", "World");
```
which basically determines if they are the same reference object, if either of them is null, which would be an automatic false if one was null and the other was not, and then compares each character in an unsafe loop. So it doesn't care about cultural rules at all, which usually isn't a big deal.
and
```
"Hello".CompareTo("World") == 0
```
is the same as
```
CultureInfo.CurrentCulture.CompareInfo.Compare("Hello", "World", CompareOptions.None);
```
This is basically the opposite as far as functionality. It takes into consideration culture, encoding, and everything else with the string in to context.
So I would imagine that **String.CompareTo is a couple of orders of magnitude slower than the equality operator**.
as for your LINQ it doesn't matter if you are using LINQ-to-SQL because both will generate the same SQL
```
var results = from names in ctx.Names
where names.FirstName.CompareTo("Bob Wazowski") == 0
select names;
```
of
```
SELECT [name fields]
FROM [Names] AS [t0]
WHERE [t0].FirstName = @p0
```
so you really aren't gaining anything for LINQ-to-SQL except harder to read code and probably more parsing of the expressions. If you are just using LINQ for standard array stuff then the rules I laid out above apply. | In my opinion, you should always use the clearest way, which is using `==`!
This can be understood directly: When "Hello" equals "World" then do something.
```
if ("Hello" == "World")
// ...
```
Internally, `String::Equals` is invoked which exists explicitly for this purpose - Comparing two strings for equality. (This has nothing to do with pointers and references etc.)
This here isn't immediately clear - Why compare to zero?
```
if ("Hello".CompareTo("World") == 0)
```
.CompareTo isn't designed just for checking equality (you have == for this) - It compares two strings. You use .CompareTo in sorts to determine wheter one string is "greater" than another. You **can** check for equality because it yield zero for equal strings, but that's not what it's concepted for.
Hence there are different methods and interfaces for checking equality (IEquatable, operator ==) and comparing (IComparable)
Linq doesn't behave different than regular C# here. | String comparison performance in C# | [
"",
"c#",
".net",
"linq",
"performance",
"string-comparison",
""
] |
I have a method that returns void in a class that is a dependency of the class I want to test.
This class is huge and I'm only using this single method from it.
I need to replace the implementation of this method for the test as I want it to do something different and I need to be able to access the parameters this method receives.
I cannot find a way of doing this in [EasyMock](http://easymock.org/). I think I know how to do it with [Mockito](http://site.mockito.org/) by using [`doAnswer`](https://static.javadoc.io/org.mockito/mockito-core/2.7.5/org/mockito/Mockito.html#doAnswer(org.mockito.stubbing.Answer)) but I don't want to add another library unless absolutely necessary. | If I understand what you want to do correctly, you should be able to use `andAnswer()`:
```
mockObject.someMethod(eq(param1), eq(param2));
expectLastCall().andAnswer(new IAnswer() {
public Object answer() {
//supply your mock implementation here...
SomeClass arg1 = (SomeClass) getCurrentArguments()[0];
AnotherClass arg2 = (AnotherClass) getCurrentArguments()[1];
arg1.doSomething(blah);
//return the value to be returned by the method (null for void)
return null;
}
});
```
The [EasyMock User Guide](http://easymock.org/user-guide.html) explains:
> ### Creating Return Values or Exceptions
>
> Sometimes we would like our mock object to return a value or throw an exception that is created at the time of the actual call. Since EasyMock 2.2, the object returned by [`expectLastCall()`](http://easymock.org/api/org/easymock/EasyMock.html#expectLastCall--) and [`expect(T value)`](http://easymock.org/api/org/easymock/EasyMock.html#expect-T-) provides the method [`andAnswer(IAnswer answer)`](http://easymock.org/api/org/easymock/IExpectationSetters.html#andAnswer-org.easymock.IAnswer-) which allows [you] to specify an implementation of the interface [`IAnswer`](http://easymock.org/api/org/easymock/IAnswer.html) that is used to create the return value or exception.
>
> Inside an [`IAnswer`](http://easymock.org/api/org/easymock/IAnswer.html) callback, the arguments passed to the mock call are available via [`EasyMock.getCurrentArguments()`](http://easymock.org/api/org/easymock/EasyMock.html#getCurrentArguments--). If you use these, refactorings like reordering parameters may break your tests. You have been warned. | If you just call the void method for each time you're expecting it to be invoked and then invoke `EasyMock.expectLastCall()` prior to calling `replay()`, Easymock will “remember” each invocation.
So I don’t think you need to explicitly call `expect()` (other than `lastCall`) since you’re not expecting anything from a void method, except its invocation.
Thanks Chris!
[“Fun With EasyMock”](http://burtbeckwith.com/blog/?p=43) by fellow StackOverflow user [Burt Beckwith](https://stackoverflow.com/users/160313/burt-beckwith) is a good blog post that provides more detail. Notable excerpt:
> Basically the flow that I tend to use is:
>
> 1. Create a mock
> 2. call `expect(mock.[method call]).andReturn([result])` for each expected call
> 3. call `mock.[method call]`, then `EasyMock.expectLastCall()` for each expected void call
> 4. call `replay(mock)` to switch from “record” mode to “playback” mode
> 5. inject the mock as needed
> 6. call the test method
> 7. call `verify(mock)` to assure that all expected calls happened | EasyMock: Void Methods | [
"",
"java",
"unit-testing",
"mocking",
"void",
"easymock",
""
] |
I have just started with Python. When I execute a python script file on Windows, the output window appears but instantaneously goes away. I need it to stay there so I can analyze my output. How can I keep it open? | You have a few options:
1. Run the program from an already-open terminal. Open a command prompt and type:
```
python myscript.py
```
For that to work you need the python executable in your path. Just check on [how to edit environment variables](https://superuser.com/questions/284342/what-are-path-and-other-environment-variables-and-how-can-i-set-or-use-them) on Windows, and add `C:\PYTHON26` (or whatever directory you installed python to).
When the program ends, it'll drop you back to the **cmd** prompt instead of closing the window.
2. Add code to wait at the end of your script. For Python2, adding ...
```
raw_input()
```
... at the end of the script makes it wait for the `Enter` key. That method is annoying because you have to modify the script, and have to remember removing it when you're done. Specially annoying when testing other people's scripts. For Python3, use `input()`.
3. Use an editor that pauses for you. Some editors prepared for python will automatically pause for you after execution. Other editors allow you to configure the command line it uses to run your program. I find it particularly useful to configure it as "`python -i myscript.py`" when running. That drops you to a python shell after the end of the program, with the program environment loaded, so you may further play with the variables and call functions and methods. | `cmd /k` is the typical way to open any console application (not only Python) with a console window that will remain after the application closes. The easiest way I can think to do that, is to press Win+R, type `cmd /k` and then drag&drop the script you want to the Run dialog. | How to keep a Python script output window open? | [
"",
"python",
"windows",
""
] |
I have the following query in ASP.NET/C# code which is failing to return any values using a parameter...
```
select * from MyTable where MyTable.name LIKE @search
```
I have tried the following query alternatives to set this parameter in SQL commands...
```
select * from MyTable where MyTable.name LIKE %@search%
select * from MyTable where MyTable.name LIKE '%' + @search + '%'
select * from MyTable where MyTable.name LIKE '%@search%'
```
And through the api...
```
myCmd.Parameters.AddWithValue("@search", search);
myCmd.Parameters.AddWithValue("@search", "%" + search + "%");
myCmd.Parameters.AddWithValue("@search", "%'" + search + "'%");
```
None of those work.
The search parameter I am using has single quotes in its text which I think is making things even more awkward. I believe I am escaping the parameter correctly because if I construct a query which uses the value directly as opposed to through parameters like so...
```
select * from MyTable where MyTable.name LIKE '%MyValue''ToSearchForWith''Quotes%'
```
That works. From what I have seen all you need to do to have single quotes in your query is to double them up. I have not seen any errors so I am assuming I've got this correct. So worst case I have a solution but I would like to be setting the search value through the api as I believe this is better practice. | I think the issue is that you're escaping the quotes in your `search` parameter, when the SQL parameter does that for you.
The percent signs should be *inside* the SQL Parameter value; your query just references the parameter plainly. The SQL should look like this:
```
select * from MyTable where MyTable.name LIKE @search
```
And the code should look like this:
```
string search = "MyValue'ToSearchForWith'Quotes";
myCmd.Parameters.AddWithValue("@search", "%" + search + "%");
```
Note that `search` is the *original* value, not escaped. | On the SQL side, this is correct:
```
select * from MyTable where MyTable.name LIKE '%' + @search + '%'
```
If the parameter was passed in from outside, it would not matter if it contained single quotes.
On the API side, this should be correct:
```
myCmd.Parameters.AddWithValue("@search", "%" + search + "%");
```
The AddWithValue() method does all the necessary escaping for you, no need to interfere. | Setting value of parameter containing " ' " (apostrophe) used in LIKE query | [
"",
"c#",
"asp.net",
"sql-server",
""
] |
The follwoing code loops over a json object to place marker on a google map. Which works fine.
```
function displayMarkers(data){
for(var i = 0; i < data.Lat.length; i++){
var point = new GLatLng(data.Lat[i],data.Lng[i]);
marker = new GMarker(point);
map.addOverlay(marker);
// here's the problem
GEvent.addListener(marker, "click", function(){
alert(data.Name[i]);
});
}
}
```
The problem is, every marker always responds with the last value of "i". I'm stuck trying to figure out a way to identify the marker that has been clicked to somehow get the right information from the data object.
I'm thinking about creating an array of markers at creation to loop through based on the markers location, but that feels really inefficient to me.
Any help, as always, greatly appreciated. | The [click event for the map](http://code.google.com/apis/maps/documentation/reference.html#GMap2.click) passes three different elements.
```
GEvent.addListener(map, "click", function(overlay, latlng, overlaylatlng) {
// overlay = GOverlay or null
// latlng = GLatLng
// overlaylatlng = GLatLng or null
});
```
If the user did not click on an overlay, 'overlay' and 'overlaylatlng' will be null.
**Update:** You have to add the listener to the map (not the marker) if you want to get a GOverlay out of it. The [click event for a GMarker](http://code.google.com/apis/maps/documentation/reference.html#GMarker.click) only returns the GLatLng. | The Map supports an onTap event, which passes the index of the marker which was selected, please refer to [this](http://www.androidguys.com/2008/09/09/maps-itemizedoverlay-and-you/) example: | Is there a way to identify which Google Map Marker has been clicked? | [
"",
"javascript",
"google-maps",
"google-maps-markers",
""
] |
I have a value class according to the description in "C++ Coding Standards", Item 32. In short, that means it provides value semantics and does not have any virtual methods.
I don't want a class to derive from this class. Beside others, one reason is that it has a public nonvirtual destructor. But a base class should have a destructor that is public and virtual or protected and nonvirtual.
I don't know a possibility to write the value class, such that it is not possible to derive from it. I want to forbid it at compile time. Is there perhaps any known idiom to do that? If not, perhaps there are some new possibilities in the upcoming C++0x? Or are there good reasons that there is no such possibility? | Even if the question is not marked for C++11, for people who get here it should be mentioned that C++11 supports new contextual identifier `final`. See [wiki page](http://en.wikipedia.org/wiki/C++11#Explicit_overrides_and_final) | Bjarne Stroustrup has written about this [here](http://www.research.att.com/~bs/bs_faq2.html#no-derivation).
---
The relevant bit from the link:
**Can I stop people deriving from my class?**
Yes, but why do you want to? There are two common answers:
* for efficiency: to avoid my function
calls being virtual.
* for safety: to ensure that my class is not used as a
base class (for example, to be sure
that I can copy objects without fear
of slicing)
In my experience, the efficiency reason is usually misplaced fear. In C++, virtual function calls are so fast that their real-world use for a class designed with virtual functions does not to produce measurable run-time overheads compared to alternative solutions using ordinary function calls. Note that the virtual function call mechanism is typically used only when calling through a pointer or a reference. When calling a function directly for a named object, the virtual function class overhead is easily optimized away.
If there is a genuine need for "capping" a class hierarchy to avoid virtual function calls, one might ask why those functions are virtual in the first place. I have seen examples where performance-critical functions had been made virtual for no good reason, just because "that's the way we usually do it".
The other variant of this problem, how to prevent derivation for logical reasons, has a solution. Unfortunately, that solution is not pretty. It relies on the fact that the most derived class in a hierarchy must construct a virtual base. For example:
```
class Usable;
class Usable_lock {
friend class Usable;
private:
Usable_lock() {}
Usable_lock(const Usable_lock&) {}
};
class Usable : public virtual Usable_lock {
// ...
public:
Usable();
Usable(char*);
// ...
};
Usable a;
class DD : public Usable { };
DD dd; // error: DD::DD() cannot access
// Usable_lock::Usable_lock(): private member
```
(from [D&E](http://www.research.att.com/~bs/dne.html) sec 11.4.3). | Is it possible to forbid deriving from a class at compile time? | [
"",
"c++",
""
] |
Good people of stackoverflow,
As always, I am writing a factory in order to dynamically instantiate objects.
To schematize, I have four types:
```
class CatDescriptor : PetDescriptor
class DogDescriptor : PetDescriptor
class Cat : Pet
class Dog : Pet
```
I instanciate the two last types from the factory. And here comes the dilemma:
Should I just test the descriptor types with the "is" operator which hides reflection and then cost something.
```
static Pet.Factory(PetDescriptor descriptor)
{
if (descriptor is CatDescriptor)
{
return new Cat();
}
else if (...)
{
...
}
}
```
Should I use an Enum "Type" as an attribute embedded in the PetDescriptor.
```
class PetDescriptor
{
public Type PetType;
public enum Type
{
Cat,
Dog
}
}
static Pet.Factory(PetDescriptor descriptor)
{
switch (descriptor.PetType)
{
case PetDescriptor.Type.Cat:
return new Cat();
....
}
}
```
Or use virtual methods:
```
class PetDescriptor
{
public virtual bool IsCat()
{
return false;
}
...
}
class CatDescriptor : PetDescriptor
{
public override bool IsCat()
{
return true;
}
}
static Pet.Factory(PetDescriptor descriptor)
{
if (descriptor.IsCat())
{
return new Cat();
}
else if (...)
{
...
}
}
```
Votes are opened !
edit: question is about reflection performance, and not factory design. | Since your `PetDescriptor` identifies the `Pet` I would use **overload**:
```
static class PetFactory
{
public static Dog CreatePet(DogDescriptor descriptor)
{
return new Dog(descriptor);
}
public static Cat CreatePet(CatDescriptor descriptor)
{
return new Cat(descriptor);
}
}
```
**(edit)**
Of course, this only works if you have a concrete `PetDescritor` : `CatDescriptor` or `DogDescriptor`.
If you don't have the *abstract* `PetDescriptor` upon creation I would go with the first solution.
Alternately, you could declare an `Enum` in the **Factory class** that would specify with concrete `Pet` you like to create. The [Wikipedia](http://en.wikipedia.org/wiki/Factory_method_pattern) has a simple example with [Pizza](http://en.wikipedia.org/wiki/Factory_method_pattern). | Having tests in your factory defeat the purpose (you'll have to update your class for every new concrete instance you want to create).
You can either :
* Use the [abstract factory pattern](http://en.wikipedia.org/wiki/Abstract_factory_pattern)
* (much better) use a IoC framework to instanciate your objects for you (I'd suggest [Castle Windsor](http://www.castleproject.org/container/index.html), [NInject](http://ninject.org/) or if you're in a MS shop only, [Unity](http://www.codeplex.com/unity)). | Cost of Reflection while using factory | [
"",
"c#",
"performance",
"reflection",
"factory",
""
] |
I'm getting very confused with memory management in relation to vectors and could do with some basic concepts explaining.
I have a program that uses big vectors.
I created the vectors with the ***new*** operator and release them at the end of the program with ***delete*** to get the memory back.
My question is, if the program crashes or gets aborted for what ever reason, the ***delete*** lines will be missed, is there a way to recover the memory even in this scenario.
I also have some other large vectors that I assign without the ***new*** keyword.
I have read that these will be created on the heap but do not need to be deallocated in anyway as the memory management is dealt with 'under the hood'.
However I am not sure this is the case as every time I run my program I lose RAM.
So my second question is, can vectors created without the ***new*** keyword really be left to their own devices and trusted to clear up after themselves even if code is aborted mid flow.
And I suppose a third question that has just sprung to mind is, if Vectors are automatically created on the heap why would you ever use the ***new*** keyword with them?
Thanks for reading,
ben | I suspect your questions are about std::vector< T > (as opposed to an array T[]).
1. When your application crashes or gets aborted for whatever reason, the OS reclaims the memory. If not you are using a truly rare OS and have discovered a bug.
2. You need to distinguish between the memory used by the vector itself and the memory of its contained objects. The vector can be created on the heap or on the stack as you noted, the memory it allocates for its contained elements is always on the heap (unless you provide your own allocator which does something else). The memory allocated by the vector is managed by the implementation of vector, and if the vector is destructed (either because it goes out of scope for a vector on the stack or because you delete a vector on the heap) its destructor makes sure that all memory is freed. | Don't use `new` to create vectors. Just put them on the stack.
The vector's destructor automatically invokes the destructor of each element in the vector. So you don't have to worry about deleting the objects yourself. However, if you have a vector of pointers, the objects that the pointers refer to will *not* be cleaned up. Here's some example code. For clarity I am leaving out most details:
```
class HeapInt
{
public:
HeapInt(int i) {ptr = new int(i);}
~HeapInt() {delete ptr;}
int& get() {return *ptr;}
private:
int* ptr;
};
int main()
{
// this code DOES NOT leak memory
std::vector<HeapInt> vec;
for (int i = 0; i < 10; ++i)
{
HeapInt h(i);
vec.push_back(h);
}
return 0;
}
```
Even if main() throws an exception, no memory is lost. However, this code *does* leak memory:
```
int main()
{
// this code though, DOES leak memory
std::vector<int*> vec;
for (int i = 0; i < 10; ++i)
{
int* ptr = new int(i);
vec.push_back(ptr);
}
// memory leak: we manually invoked new but did not manually invoke delete
return 0;
}
``` | C++ memory management and vectors | [
"",
"c++",
"memory",
"vector",
""
] |
I'm trying to figure out how I could detect whether people logging into my site are behind a proxy or not. I've read that you can detect a person's real IP address through embeddable objects (Flash and Java). However, I haven't been able to actually find any examples or source for this.
I'm using PHP and I've read that looking for `$_SERVER['HTTP_X_FORWARDED_FOR'], $_SERVER['HTTP_CLIENT_IP']`, etc. would detect most proxies but so far I haven't been able to by testing with TOR (maybe TOR doesn't flag those, but I've read that anonymous proxies still show `HTTP_X_FORWARDED`). I'd like to try doing it with a java servlet, if possible. Could anyone point me in the right direction (preferably with examples?) I saw some code on ha.ckers.org but they only showed the client side and not the server side. | TOR does not supply any server headers such as X\_FORWARDED\_FOR, so your best bet is to use a list of all known exit nodes. A list can be found at <https://torstat.xenobite.eu/>.
For other proxies, you can look at server headers. Possible server headers of interest include:
```
HTTP_VIA
HTTP_X_FORWARDED_FOR
HTTP_FORWARDED_FOR
HTTP_X_FORWARDED
HTTP_FORWARDED
HTTP_CLIENT_IP
HTTP_FORWARDED_FOR_IP
VIA
X_FORWARDED_FOR
FORWARDED_FOR
X_FORWARDED FORWARDED
CLIENT_IP
FORWARDED_FOR_IP
HTTP_PROXY_CONNECTION
```
In PHP, you can get the value of these fields in the `$_SERVER[] superglobal`. | If your want to check weather the user is using proxy or not you can go with the port scan and checking the headers when request is made. These method will reveal public IP if the proxy is non-transparent (By the way there are two types of IP address public and private IP address). But this will not work if it is transparent proxy.
```
function detectProxy() {
$sockport = false;
$proxyports=array(80,8080,6588,8000,3128,3127,3124,1080,553,554);
for ($i = 0; $i <= count($proxyports); $i++) {
if(@fsockopen($ipaddress,$proxyports[$i],$errstr,$errno,0.5)){
$sockport=true;
}
}
if(
isset($_SERVER['HTTP_VIA'])
|| isset($_SERVER['HTTP_X_FORWARDED_FOR'])
|| isset($_SERVER['HTTP_FORWARDED_FOR'])
|| isset($_SERVER['HTTP_X_FORWARDED'])
|| isset($_SERVER['HTTP_FORWARDED'])
|| isset($_SERVER['HTTP_CLIENT_IP'])
|| isset($_SERVER['HTTP_FORWARDED_FOR_IP'])
|| isset($_SERVER['VIA'])
|| isset($_SERVER['X_FORWARDED_FOR'])
|| isset($_SERVER['FORWARDED_FOR'])
|| isset($_SERVER['X_FORWARDED'])
|| isset($_SERVER['FORWARDED'])
|| isset($_SERVER['CLIENT_IP'])
|| isset($_SERVER['FORWARDED_FOR_IP'])
|| isset($_SERVER['HTTP_PROXY_CONNECTION'])
|| $sockport === true
) {
echo 'User is using proxy';
}
else{
echo ''user is not using proxy';
}
}
```
Second method is by using DNS server by allocating sub domain to each user.
You can also check this site [proxy checker](https://www.sabiduria.in/tracker/Do-you-think-you-know-more-about-your-device-than-we-know/) which will show public and private IP address even when you are using proxy. | Detecting whether a user is behind a proxy | [
"",
"php",
"http",
"proxy",
""
] |
I'm facing a problem while working with iFrames. What I need to do is, get the contents of a division 'contents' , display it in an iframe, and then remove all forms/form elements ONLY in that iframe. When i use $("#form").remove(), it removes the form both in iframe and in the window. Can someone help?
Thank You. | You can wrap the iframe in a DIV with an ID and remove forms only inside of that. Can you post some code? Would be easier to work off that. Or just grab the iframe (although I'm not sure it will work, haven't tested it).
```
$("iframe").find("#form").remove();
``` | Do both the forms have the same id (#form)?
Give them separate ids (eg: `<form id="inner">` and `<form id="outer">`) and you should be able to target them individually: `$(#inner).remove()` | jQuery iFrame manipulation | [
"",
"javascript",
"jquery",
"html",
""
] |
I'm updating some code and while I was working in a header, I came across the following line.
```
.
.
.
class HereIsMyClass;
.
.
.
```
That's it. It's just one line that precedes another, longer class definition. HereIsMyClass is in fact another class somewhere else, but I don't understand why this line is written here. What does it do? | This line in C++ is a forward declaration. It's stating that at some point in the future a class named HereIsMyClass will likely exist. It allows for you to use a class in a declaration before it's completely defined.
It's helpful for both breaking up circularly dependent classes and header file management.
For example
```
class HereIsMyClass;
class Foo {
void Bar(HereIsMyClass* p1) ...
};
class HereIsMyClass {
void Function(Foo f1);
}
``` | It's called a "forward declaration". This tells the compiler that 'HereIsMyClass' is the name of a class (versus the name of a variable, a function, or something else). The class will have to be defined later for it to be used.
This is useful when you have classes that need to refer to each other.
[Here's](http://www.eventhelix.com/RealtimeMantra/HeaderFileIncludePatterns.htm) one description. | One line class definition? | [
"",
"c++",
"class",
"definition",
""
] |
Are there any specific advantages or disadvantages to either `print` or `stderr`? | They're just two different things. `print` generally goes to `sys.stdout`. It's worth knowing the difference between [`stdin`, `stdout`, and `stderr`](http://en.wikipedia.org/wiki/Standard_streams) - they all have their uses.
In particular, `stdout` should be used for normal program output, whereas `stderr` should be reserved only for error messages (abnormal program execution). There are utilities for splitting these streams, which allows users of your code to differentiate between normal output and errors. | `print` can print on any file-like object, including `sys.stderr`.
```
print >> sys.stderr, 'Text'
```
The advantages of using `sys.stderr` for errors instead of `sys.stdout` are:
* If the user redirected stdout to a file, she still sees errors on the screen.
* It's not buffered, so if `sys.stderr` is redirected to a log file there are less chance that the program may crash before the error was logged.
---
This answer written with Python 2 in mind.
For Python 3, use `print('Text', file=sys.stderr)` instead. | print vs stderr | [
"",
"python",
"printing",
"stderr",
""
] |
I have a Hindi magazine website hosted on Joomla. Though helpful from publishing point of view the site was a maintenance nightmare. Joomla is so much susceptible to hacker attacks. My host will often shut down my site due to bots attacking my website. Recently I relaunched the site as a new Wordpress based site on a different name. The Joomla based website would therefore never be updated anymore. However, I do want to maintain the old content. I have used PHP but hardly am a power user.
I want to convert the files as plain HTML. I created a mirror of the website using HTTrack. But thanks to the fact that Joomla had variety of URLs for the same page (if you used a SEF URL plugin you would understand) the mirror is full of redundant content. Moreover I have repetitive HTML content (for header,footer,menu etc) in each page.
My questions are:
1. Which is a better option, create a static HTML site or PHP4.x pages (with Unicode content and having include PHP fragments for repetitive content)?
2. If latter is better should I use template system like Smarty? I am worried about caching since the content will hardly be updated I want caches to last forever.
Thanks for the help. | If I were you I'd move everything over to WordPress since you have started using this. This way you will be maintaining a single website application keeping things better manageable in the long run.
You can copy the data out of Joomla using the Joomla administration interface. Or maybe even quicker using a database tool like MySQL Tools or Navicat which has a lot of export options.
Copying the HTML from Joomla using tools like HTTrack or TelePort Pro will result in lots of duplicate code and pages like you state.
Maintaining an extra PHP site just for the old content will be as much effort as getting everything into WordPress. | If the content is not going to change frequently I recommend using HTML files. They are static and hence faster.
However, if you are going to be updating content frequently, then you can either upgrade to the latest version of any popular CMS preferably joomla or drupal. I cite these two because they are actively developed and you can get a lot of support for them on the internet. Be sure to follow their security guide for hardening your installation. | Joomla to Static HTML website | [
"",
"php",
"html",
"unicode",
"joomla",
"smarty",
""
] |
Can you see anything wrong with this code, or can it be optimised?
**Code from index.php, to include the file**
```
if(empty($_GET['t'])) {
$folder = "apps/";
}else {
$folder = str_replace("/", "", $_GET['t']) . "/";
}
if(empty($_GET['app'])) {
include('apps/home.php');
} else {
if(file_exists($folder.$app.".php")) {
include($folder.$app.".php");
} else {
include("/home/radonsys/public_html/global/error/404.php");
}
}
```
My problem? one page, which posts to itself doesnt find it's page and returns to that 404 page.
If you want, I can include the form code for that page?
**Code from bugs.php**
```
<form method="post" action="">
<div>Title</div>
<div><input name="title" type="text" class="bginput" value="" size="59" tabindex="1" /></div>
<br />
<div>
<label class="smallfont">
Application
<select name="app" style="display:block; width:200px" tabindex="2">
<option value="Admin CP">AdminCP</option>
<option value="Add User">Add User</option>
<option value="Bugzilla">Bugzilla</option>
<option value="Portal">Portal</option>
<option value="To Do">To Do</option>
<option value="Internal Messages">Internal Messages</option>
<option value="User CP">UserCP</option>
<option value="Change Password">Change Password</option>
<option value="Change Email">Change Email</option>
<option value="General">General</option>
</select>
</label>
</div>
<br />
<div>Bug Description</div>
<textarea name="content" style="width:7%"></textarea>
<br />
<div>
<label class="smallfont">
Priority
<select name="priority" style="display:block; width:200px" tabindex="2">
<option value="0" selected="selected">Unknown</option>
<option value="1">1 - Highest</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5 - Medium</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10 - Lowest</option>
</select>
</label>
</div>
<br />
<input type="submit" value="Save" />
</form>
```
**Clarification**
The above script is in index.php, which calls on a page, e.g, ?app=bugs includes bugs.php in the apps folder.
Stuff on the bugs.php script uses POST to itself to send the data, however, post data never reaches the page itself since we're stuck with the error page, 404.php | Well, the answer to why that certain application/page was having the problem was becuase the select id was app, which incidentally, was the app variable for the page, so it wasn't fetching the correct pages.
*Tip* **Remember to name your properties carefully!** | you are saying the form posts to itself, does that mean you are using POST?
if so, you need to change $\_GET[] to $\_POST[]
The more code you post, the better. | Anything wrong with this PHP | [
"",
"php",
"html",
"forms",
"include",
"directory",
""
] |
I have an ASP.NET/C# application, part of which converts WWW links to mailto links in an HTML email.
For example, if I have a link such as:
> www.site.com
It gets rewritten as:
> mailto:my@address.com?Subject=www.site.com
This works extremely well, until I run into URLs with ampersands, which then causes the subject to be truncated.
For example the link:
> www.site.com?val1=a&val2=b
Shows up as:
> mailto:my@address.com?Subject=www.site.com?val1=a&val2=b
Which is exactly what I want, but then when clicked, it creates a message with:
> subject=www.site.com?val1=a
Which has dropped the `&val2`, which makes sense as & is the delimiter in a mailto command.
So, I have tried various other was to work around this with no success.
I have tried implicitly quoting the `subject=''` part and that did nothing.
I (in C#) replace '&' with `&` which Live Mail and Thunderbird just turn back into:
> www.site.com?val1=a&val2=b
I replaced '&' with '%26' which resulted in:
> mailto:my@address.com?Subject=www.site.com?val1=a%26amp;val2=b
In the mail with the subject:
> `www.site.com?val1=a&val2=b`
---
### EDIT:
In response to how URL is being built, this is much trimmed down but is the gist of it. In place of the att.Value.Replace I have tried System.Web.HtmlUtility.URLEncode calls which also results in a failure
```
HtmlAgilityPack.HtmlNodeCollection nodes =doc.DocumentNode.SelectNodes("//a[@href]");
foreach (HtmlAgilityPack.HtmlNode link in nodes)
{
HtmlAgilityPack.HtmlAttribute att = link.Attributes["href"];
att.Value = att.Value.Replace("&", "%26");
}
``` | Try **mailto:my@address.com?Subject=www.site.com?val1=a%26val2=b**
`&` is an HTML escape code, whereas `%26` is a URL escape code. Since it's a URL, that's all you need.
EDIT: I figured that's how you were building your URL. **Don't build URLs that way!** You need to get the `%26` in there before you let anything else parse or escape it. If you really must do it this way (which you really should try to avoid), then you should search for `"&"` instead of just `"&"` because the string has already been HTML escaped at this point.
So, ideally, you build your URL properly before it's HTML escaped. If you can't do it properly, at least search for the right string instead of the wrong one. `"&"` is the wrong one. | You cant put any character as subject. You could try using System.Web.HttpUtility.URLEncode function on the subject´s value... | How can I deal with ampersands in a mail client's mailto links? | [
"",
"c#",
"email",
""
] |
A module I'm adding to our large Java application has to converse with another company's SSL-secured website. The problem is that the site uses a self-signed certificate. I have a copy of the certificate to verify that I'm not encountering a man-in-the-middle attack, and I need to incorporate this certificate into our code in such a way that the connection to the server will be successful.
Here's the basic code:
```
void sendRequest(String dataPacket) {
String urlStr = "https://host.example.com/";
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setMethod("POST");
conn.setRequestProperty("Content-Length", data.length());
conn.setDoOutput(true);
OutputStreamWriter o = new OutputStreamWriter(conn.getOutputStream());
o.write(data);
o.flush();
}
```
Without any additional handling in place for the self-signed certificate, this dies at conn.getOutputStream() with the following exception:
```
Exception in thread "main" javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
....
Caused by: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
....
Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
```
Ideally, my code needs to teach Java to accept this one self-signed certificate, for this one spot in the application, and nowhere else.
I know that I can import the certificate into the JRE's certificate authority store, and that will allow Java to accept it. That's not an approach I want to take if I can help; it seems very invasive to do on all of our customer's machines for one module they may not use; it would affect all other Java applications using the same JRE, and I don't like that even though the odds of any other Java application ever accessing this site are nil. It's also not a trivial operation: on UNIX I have to obtain access rights to modify the JRE in this way.
I've also seen that I can create a TrustManager instance that does some custom checking. It looks like I might even be able to create a TrustManager that delegates to the real TrustManager in all instances except this one certificate. But it looks like that TrustManager gets installed globally, and I presume would affect all other connections from our application, and that doesn't smell quite right to me, either.
What is the preferred, standard, or best way to set up a Java application to accept a self-signed certificate? Can I accomplish all of the goals I have in mind above, or am I going to have to compromise? Is there an option involving files and directories and configuration settings, and little-to-no code? | Create an `SSLSocket` factory yourself, and set it on the `HttpsURLConnection` before connecting.
```
...
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslFactory);
conn.setMethod("POST");
...
```
You'll want to create one `SSLSocketFactory` and keep it around. Here's a sketch of how to initialize it:
```
/* Load the keyStore that includes self-signed cert as a "trusted" entry. */
KeyStore keyStore = ...
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
sslFactory = ctx.getSocketFactory();
```
If you need help creating the key store, please comment.
---
Here's an example of loading the key store:
```
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(trustStore, trustStorePassword);
trustStore.close();
```
To create the key store with a PEM format certificate, you can write your own code using `CertificateFactory`, or just import it with `keytool` from the JDK (keytool *won't* work for a "key entry", but is just fine for a "trusted entry").
```
keytool -import -file selfsigned.pem -alias server -keystore server.jks
``` | I read through LOTS of places online to solve this thing.
This is the code I wrote to make it work:
```
ByteArrayInputStream derInputStream = new ByteArrayInputStream(app.certificateString.getBytes());
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(derInputStream);
String alias = "alias";//cert.getSubjectX500Principal().getName();
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null);
trustStore.setCertificateEntry(alias, cert);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(trustStore, null);
KeyManager[] keyManagers = kmf.getKeyManagers();
TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509");
tmf.init(trustStore);
TrustManager[] trustManagers = tmf.getTrustManagers();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
URL url = new URL(someURL);
conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
```
app.certificateString is a String that contains the Certificate, for example:
```
static public String certificateString=
"-----BEGIN CERTIFICATE-----\n" +
"MIIGQTCCBSmgAwIBAgIHBcg1dAivUzANBgkqhkiG9w0BAQsFADCBjDELMAkGA1UE" +
"BhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsTIlNlY3VyZSBE" +
... a bunch of characters...
"5126sfeEJMRV4Fl2E5W1gDHoOd6V==\n" +
"-----END CERTIFICATE-----";
```
I have tested that you can put any characters in the certificate string, if it is self signed, as long as you keep the exact structure above. I obtained the certificate string with my laptop's Terminal command line. | How can I use different certificates on specific connections? | [
"",
"java",
"ssl",
"keystore",
"truststore",
"jsse",
""
] |
I have two columns in my Items table 'Category', 'Category2', the two columns contain, essentially the same information. If I had designed the database I would have created a separate table for categories and added items to categories based based off of that table, unfortunately I didn't create the database and I can't change it now but I think there is still a way to do what I want to do.
An example of the table is shown below
```
Category Category2
------------------ -----------------
truck full size - pickup
full size - pickup truck
Sedan Import - Sedan
Convertible Domestic - Coupe
```
I want to run a query to count the total number of trucks, sedans, full size - pickup, etc. I tried the below query but it grouped the two columns separately
```
SELECT Category, Count(*) as Count
FROM Items
GROUP BY Category, Category2
``` | Just dump both categories into a single column before grouping.
```
SELECT Category, Count(*) as TheCount
FROM
(
SELECT Category1 as Category
FROM Items
UNION ALL
SELECT Category2
FROM Items
) sub
GROUP BY Category
``` | Imagine that a row with "category, category2" can be transformed to two rows (one with "category", one with "category2") to get what you want. You'd do that like this:
```
SELECT items.category /* , other columns... */
FROM items
UNION ALL
SELECT items.category2 /* , other columns... */
FROM items
```
So all you then need to do is aggregate across these:
```
SELECT category, count(*) FROM (
SELECT items.category FROM items
UNION ALL
SELECT items.category2 FROM items
) expanded
GROUP BY category
```
You can also do the aggregate by stages like this if your database supports it:
```
with subcounts as (
select items.category, items.category2, count(*) as subcount
from items
group by category, category2)
select category, sum(subagg) as finalcount from (
select subcounts.category, sum(subcount) as subagg from subcounts group by category
union all
select subcounts.category2, sum(subcount) as subagg from subcounts group by category2
) combination
group by category
```
This will limit to just one scan of the main items table, good if you only have a small number of categories. You can emulate the same thing with temp tables in databases that don't support "WITH..."
EDIT:
I was sure there had to be another way to do it without scanning Items twice, and there is. Well, this is the PostgreSQL version:
```
SELECT category, count(*) FROM (
SELECT CASE selector WHEN 1 THEN category WHEN 2 THEN category2 END AS category
FROM Items, generate_series(1,2) selector
) items_fixed GROUP BY category
```
The only postgresql-specific bit here is "generate\_series(1,2)" which produces a "table" containing two rows-- one with "1" and one with "2". Which is IMHO one of the handiest features in postgresql. You can implement similar things in the like of SQL Server as well, of course. Or you could say "(select 1 as selector union all select 2)". Another alternative is "(values(1),(2)) series(selector)" although how much of that syntax is standard and how much is postgres-specific, I'm not sure. Both these approaches have an advantage of giving the planner an idea that there will only be two rows.
Cross-joining this series table items allows us generate two output rows for each row of item. You can even take that "items\_fixed" subquery and make it a view -- which btw is the reverse of the process I tend to use to try and solve these kind of problems. | Advanced SQL GROUP BY query | [
"",
"sql",
"sql-server",
""
] |
I am a PHP web programmer who is trying to learn C#.
I would like to know why C# requires me to specify the data type when creating a variable.
```
Class classInstance = new Class();
```
Why do we need to know the data type before a class instance? | As others have said, C# is static/strongly-typed. But I take your question more to be "Why would you *want* C# to be static/strongly-typed like this? What advantages does this have over dynamic languages?"
With that in mind, there are lots of good reasons:
* **Stability** Certain kinds of errors are now caught automatically by the compiler, before the code ever makes it anywhere close to production.
* **Readability/Maintainability** You are now providing more information about how the code is supposed to work to future developers who read it. You add information that a specific variable is intended to hold a certain kind of value, and that helps programmers reason about what the purpose of that variable is.
This is probably why, for example, Microsoft's style guidelines recommended that VB6 programmers put a type prefix with variable names, but that VB.Net programmers do not.
* **Performance** This is the weakest reason, but late-binding/duck typing can be slower. In the end, a variable refers to memory that is structured in some specific way. Without strong types, the program will have to do extra type verification or conversion behind the scenes at runtime as you use memory that is structured one way physically as if it were structured in another way logically.
I hesitate to include this point, because ultimately you often have to do those conversions in a strongly typed language as well. It's just that the strongly typed language leaves the exact timing and extent of the conversion to the programmer, and does no extra work unless it needs to be done. It also allows the programmer to force a more advantageous data type. But these really are attributes of the *programmer*, rather than the platform.
That would itself be a weak reason to omit the point, except that a good dynamic language will often make better choices than the programmer. This means a dynamic language can help many programmers write faster programs. Still, for *good* programmers, strongly-typed languages have the *potential* to be faster.
* **Better Dev Tools** If your IDE knows what type a variable is expected to be, it can give you additional help about what kinds of things that variable can do. This is much harder for the IDE to do if it has to infer the type for you. And if you get more help with the minutia of an API from the IDE, then you as a developer will be able to get your head around a larger, richer API, and get there faster.
Or perhaps you were just wondering why you have to specify the class name twice for the same variable on the same line? The answer is two-fold:
1. Often you don't. In C# 3.0 and later you can use the `var` keyword instead of the type name in many cases. Variables created this way are still statically typed, but the type is now *inferred* for you by the compiler.
2. Thanks to inheritance and interfaces sometimes the type on the left-hand side doesn't match the type on the right hand side. | It's simply how the language was designed. C# is a C-style language and follows in the pattern of having types on the left.
In C# 3.0 and up you can kind of get around this in many cases with local type inference.
```
var variable = new SomeClass();
```
But at the same time you could also argue that you are still declaring a type on the LHS. Just that you want the compiler to pick it for you.
**EDIT**
Please read this in the context of the users original question
> why do we need [class name] before a variable name?
I wanted to comment on several other answers in this thread. A lot of people are giving "C# is statically type" as an answer. While the statement is true (C# is statically typed), it is almost completely unrelated to the question. Static typing does not necessitate a type name being to the left of the variable name. Sure it can help but that is a language designer choice not a necessary feature of static typed languages.
These is easily provable by considering other statically typed languages such as F#. Types in F# appear on the right of a variable name and very often can be altogether ommitted. There are also several counter examples. PowerShell for instance is extremely dynamic and puts all of its type, if included, on the left. | Why is C# statically typed? | [
"",
"c#",
"static-typing",
""
] |
I have started work on a local app for myself that runs through the browser. Having recently gone through the django tutorial I'm thinking that it might be better to use django rather than just plain python.
There's one problem: I have at least 20 models and each will have many functions. Quite simply it's going to create one huge models file and probably huge views too. How do I split them up?
The [models are all related](http://woarl.com/images/entity%20chart.png) so I can't simply make them into separate apps can I? | "I have at least 20 models" -- this is probably more than one Django "app" and is more like a Django "project" with several small "apps"
I like to partition things around topics or subject areas that have a few (1 to 5) models. This becomes a Django "app" -- and is the useful unit of reusability.
The overall "project" is a collection of apps that presents the integrated thing built up of separate pieces.
This also helps for project management since each "app" can become a sprint with a release at th end. | This is a pretty common need... I can't imagine wading through a models.py file that's 10,000 lines long :-)
You can split up the `models.py` file (and views.py too) into a pacakge. In this case, your project tree will look like:
```
/my_proj
/myapp
/models
__init__.py
person.py
```
The `__init__.py` file makes the folder into a package. The only gotcha is to be sure to define an inner `Meta` class for your models that indicate the app\_label for the model, otherwise Django will have trouble building your schema:
```
class Person(models.Model):
name = models.CharField(max_length=128)
class Meta:
app_label = 'myapp'
```
Once that's done, import the model in your `__init__.py` file so that Django and sync db will find it:
```
from person import Person
```
This way you can still do `from myapp.models import Person` | About 20 models in 1 django app | [
"",
"python",
"django",
"django-models",
""
] |
I need to add a functionality in an application (C#) which will use a web service (XML SOAP service).
Now this application can (and mostly) be used in an corporate environment which has a proxy server in place.
I understand the SOAP services use HTTP protocol and hence should use port 80, which is normally kept opened. Is it right that application can use web service without any special coding or I will need to write special code to detect proxy settings or some other issues you see?
EDIT: Webservice is a publicly available service on internet. Its not on same network. | OK. So I did some experiments and it turns out that we do need to write some code to make it work from behind the proxy server. (Though I would have prefered a better solution)
So it actually drills down to asking proxy server details from user and then configure the service proxy class for proxy server as below:
```
var networkCredentials = new NetworkCredential ("username", "password", "domain");
WebProxy myProxy = new WebProxy ("W.X.Y.Z:NN", true) {Credentials = networkCredentials};
var service = new iptocountry { Proxy = myProxy };
string result = service.FindCountryAsString ("A.B.C.D");
```
I wrote a test class and it uses [IP To Country](http://www.xmethods.net/ve2/index.po) free web service.
Using above code, I could consume the web service successfully. | It will use port 80 by default, and you shouldn't have to do any further coding.
If you do need to go through a proxy of some sort, all you need to do is add the following to your web.config:
```
<system.net>
<defaultProxy>
<proxy proxyaddress="http://yourproxyserver:80" />
</defaultProxy>
</system.net>
```
You could also do it through code using this:
```
WebRequest.DefaultWebProxy = new WebProxy("http://yourproxyserver:80/",true);
``` | Calling a webservice from behind a proxy server | [
"",
"c#",
".net",
"web-services",
"soap",
""
] |
I recently got stuck in a situation like this:
```
class A
{
public:
typedef struct/class {…} B;
…
C::D *someField;
}
class C
{
public:
typedef struct/class {…} D;
…
A::B *someField;
}
```
Usually you can declare a class name:
```
class A;
```
But you can't forward declare a nested type, the following causes compilation error.
```
class C::D;
```
Any ideas? | You can't do it, it's a hole in the C++ language. You'll have to un-nest at least one of the nested classes. | ```
class IDontControl
{
class Nested
{
Nested(int i);
};
};
```
I needed a forward reference like:
```
class IDontControl::Nested; // But this doesn't work.
```
My workaround was:
```
class IDontControl_Nested; // Forward reference to distinct name.
```
Later when I could use the full definition:
```
#include <idontcontrol.h>
// I defined the forward ref like this:
class IDontControl_Nested : public IDontControl::Nested
{
// Needed to make a forwarding constructor here
IDontControl_Nested(int i) : Nested(i) { }
};
```
This technique would probably be more trouble than it's worth if there were complicated constructors or other special member functions that weren't inherited smoothly. I could imagine certain template magic reacting badly.
But in my very simple case, it seems to work. | Forward declaration of nested types/classes in C++ | [
"",
"c++",
"class",
"nested",
"forward-declaration",
""
] |
Given these two tables:
```
CREATE TABLE TEST1 (TEST VARCHAR2(1 BYTE))
CREATE TABLE TEST2 (TEST VARCHAR2(1 BYTE))
```
Where TEST1 has two rows both with the value 'A' and TEST2 has one row with the value 'B'.
When I run this command:
```
SELECT TEST FROM TEST1
MINUS
SELECT TEST FROM TEST2
```
I get the output:
```
Test
-----
A
```
It appears that MINUS removes the duplicates (as there are two 'A' rows in TEST1).
How can you get MINUS query to include duplicate values (return two 'A' rows)? | Oracle supports multiple columns in the IN statement, so you can write:
```
SELECT a, b, c
FROM table1
WHERE (a,b,c) not in (
select a,b,c from table2
)
``` | Another option:
```
SELECT TEST, row_number() OVER (PARTITION BY TEST ORDER BY TEST) FROM TEST1
MINUS
SELECT TEST, row_number() OVER (PARTITION BY TEST ORDER BY TEST) FROM TEST2
```
This would be MINUS with each duplicate treated as a distinct entry. Note in the example below, if TEST1 has two 'C' values and TEST2 has only one, you get one in the output.
```
dev> select * from test1;
T
-
A
A
B
C
C
dev> select * from test2;
T
-
B
C
dev> SELECT TEST, row_number() OVER (PARTITION BY TEST ORDER BY TEST) FROM TEST1
2 MINUS
3 SELECT TEST, row_number() OVER (PARTITION BY TEST ORDER BY TEST) FROM TEST2
4 /
T ROW_NUMBER()OVER(PARTITIONBYTESTORDERBYTEST)
- --------------------------------------------
A 1
A 2
C 2
``` | Prevent Oracle minus statement from removing duplicates | [
"",
"sql",
"oracle",
""
] |
I am trying to start unit testing. I am looking at a few C++ frameworks and want to try Boost.Test. The documentation seems very thorough, and it's a bit overwhelming, especially someone new to unit testing. So here's a situation that I want:
Let's say I have 2 classes, `Foo` and `Bar`. I want to write a suite of tests for `Foo` and a suite of tests for `Bar`, preferably in different files. I want to run the tests only if I run the program with a command line parameter. So my `main()` should look something like:
```
int main(int argc, const char* argv[])
{
if (argc == 1 && strcmp(argv[0], "-test") == 0)
run_all_tests();
else
return program_main(argc, argv);
}
```
I think `test_foo.cpp` should be something like:
```
#include "foo.hpp"
#define BOOST_TEST_MODULE Foo test
#include <boost/test/unit_test.hpp>
BOOST_AUTO_TEST_SUITE( Foo_Test )
BOOST_AUTO_TEST_CASE( Foo1 )
{
Foo f;
BOOST_CHECK( f.isValid() );
}
BOOST_AUTO_TEST_CASE( Foo2 )
{
Foo f;
BOOST_CHECK( f.baz() == 5 );
}
BOOST_AUTO_TEST_SUITE_END()
```
However, I don't know (1) what the actual command to run the tests is, and (2) how to actually tell the library that I want to run EVERY test.
So, who has experience with Boost.Test? Can someone help in a detailed way? Thank you so much. | BOOST.Test is very flexible and you can probably do what you want. However since you say you are new to unit testing, you should probably follow the standard unit testing structure.
This is to have a separate test project for each project you are unit testing. Then include the sources and libraries you need to build the test project.
This is cleaner as there are no test logic in your main project that might get run accidentally and it is easy to run the tests as they have their own executable. This approach also works for testing libraries. If you follow this structure you will find that most of the BOOST.Test defaults work out of the box and you can just worry about writing you tests and code. | In your `test_foo.cpp`, the macros add test suites and test cases in
to a global list: `master_testsuite`, which is the root of all test
nodes. You just need to compile all the test files like
`test_foo.cpp`, `test_boo.cpp` and a runner, then link them all into on
executable.
The function `unit_test_main` is used to run the tests in `master_testsuite`.
```
boost::unit_test::unit_test_main(
&init_unit_test,
argc,
argv
)
```
Based on the macro you defined before including
`<boost/test/unit_test.h>`, *Boost.Test* may already generate the `main`
function for you.[1] The generated `main` simply invoked
`unit_test_main` with `argc` and `argv` in `main`. It's recommended to
use `unit_test_main` because it can process some console arguments,
like [run test by name](http://www.boost.org/doc/libs/1_39_0/libs/test/doc/html/utf/user-guide/runtime-config/run-by-name.html "Running Boost Test By Name").
The first argument of `unit_test_main` is a hook. Depending on
`BOOST_TEST_ALTERNATIVE_INIT_API`, it has different definition.
```
#ifdef BOOST_TEST_ALTERNATIVE_INIT_API
typedef bool (*init_unit_test_func)();
#else
typedef test_suite* (*init_unit_test_func)( int, char* [] );
#endif
```
You can customize the `master_testsuite` in the hook. In the second
form, the returned value is the new master testsuite.
[1] if `BOOST_TEST_MAIN` and `BOOST_TEST_MAIN` are defined, but
`BOOST_TEST_NO_MAIN` is not. | Helping getting started using Boost.Test | [
"",
"c++",
"unit-testing",
"boost",
""
] |
I would like to create a new event-dispatch thread in Swing, and I'm having trouble finding any references online for how to do this. I have done this in .NET by creating a new thread and calling Application.run(...). Has anyone done this? Is it possible in Swing?
FYI the reason I am trying to do this is because I am writing an Eclipse plug-in, and I would like to pop up dialogs that are not modal to the IDE but that are modal (blocking) to my UI logic. I could accomplish this using non-modal dialogs and callbacks, but that requires the overhead of making my code multi-threaded. I'll revert to that if the former is not possible. | Yes, it's possible. I've have done such multiple EDT dispatch threads logic in Swing. However, net result was that it didn't work reliably.
(a) All JVMs don't work nicely with multiple EDT threads (synchronization problems in graphics rendering logic in native code and such, IBM JVM failed with multiple EDT threads, Sun JVM & Apple JVM did work)
(b) Swing rendering logic has few bugs causing that random rendering errors will occur (for example, <https://bugs.java.com/bugdatabase/view_bug?bug_id=6727829>).
Anyway, doing this requires basically establishing two AppContexts, which each have their own EDT thread. | I'm a little confused by your question, because you mention Swing but then say you are writing an Eclipse plugin. Since the question is tagged Swing, I'll give a Swing answer (but posted as CW).
There is one event dispatch thread. There is always one event dispatch thread, unless there is none at all. You cannot create another one.
You can, however, change the [`ModalityType`](http://java.sun.com/javase/6/docs/api/java/awt/Dialog.ModalityType.html) of your dialogs, or change the [`ModalExclusionType`](http://java.sun.com/javase/6/docs/api/java/awt/Dialog.ModalExclusionType.html) of a window. In this case, if you were writing this all yourself, you would set your top-level window's `ModalExclusionType` to [`APPLICATION_EXCLUDE`](http://java.sun.com/javase/6/docs/api/java/awt/Dialog.ModalExclusionType.html#APPLICATION_EXCLUDE).
But again, I don't see how this could help you, since Eclipse uses SWT instead of Swing. | Multiple Swing event-dispatch threads | [
"",
"java",
"multithreading",
"swing",
"modal-dialog",
"ui-thread",
""
] |
In MySQL, you can use the keyword USING in a join when you join on columns from different tables with the same name. For example, these queries yield the same result:
```
SELECT * FROM user INNER JOIN perm USING (uid)
SELECT * FROM user INNER JOIN perm ON user.uid = perm.uid
```
Is there an equivalent shortcut in SQL Server? | nope, have to use:
```
SELECT * FROM user INNER JOIN perm ON user.uid = perm.uid
``` | No, SQL Server does not support this kind of shortcut.
I would like to point out that even if it did, shortcuts like these are NOT A GOOD IDEA. I recently worked on a database where the developers thought it would be a good idea to use the `*= and =*` shortcuts for RIGHT JOIN and LEFT JOIN. Good idea until someone upgraded the SQL Compatibility level to 90. Then it became an extremely Bad Idea.
So, learn from us. Shortcuts are bad. A little extra typing never killed anyone. | SQL Server equivalent of MySQL's USING | [
"",
"sql",
"mysql",
"sql-server",
"join",
"using",
""
] |
How do I convert from `CString` to `const char*` in my Unicode MFC application? | To convert a `TCHAR` CString to ASCII, use the `CT2A` macro - this will also allow you to convert the string to UTF8 (or any other Windows code page):
```
// Convert using the local code page
CString str(_T("Hello, world!"));
CT2A ascii(str);
TRACE(_T("ASCII: %S\n"), ascii.m_psz);
// Convert to UTF8
CString str(_T("Some Unicode goodness"));
CT2A ascii(str, CP_UTF8);
TRACE(_T("UTF8: %S\n"), ascii.m_psz);
// Convert to Thai code page
CString str(_T("Some Thai text"));
CT2A ascii(str, 874);
TRACE(_T("Thai: %S\n"), ascii.m_psz);
```
There is also a macro to convert from ASCII -> Unicode (`CA2T`) and you can use these in ATL/WTL apps as long as you have VS2003 or greater.
See the [MSDN](http://msdn.microsoft.com/en-us/library/87zae4a3(VS.80).aspx) for more info. | If your CString is Unicode, you'll need to do a conversion to multi-byte characters. Fortunately there is a version of CString which will do this automatically.
```
CString unicodestr = _T("Testing");
CStringA charstr(unicodestr);
DoMyStuff((const char *) charstr);
``` | Convert CString to const char* | [
"",
"c++",
"visual-studio",
"visual-c++",
"unicode",
"mfc",
""
] |
I'm confused how to import a SQL dump file. I can't seem to import the database without creating the database first in MySQL.
This is the error displayed when `database_name` has not yet been created:
`username` = username of someone with access to the database on the original server.
`database_name` = name of database from the original server
```
$ mysql -u username -p -h localhost database_name < dumpfile.sql
Enter password:
ERROR 1049 (42000): Unknown database 'database_name'
```
If I log into MySQL as root and create the database, `database_name`
```
mysql -u root
create database database_name;
create user username;# same username as the user from the database I got the dump from.
grant all privileges on database_name.* to username@"localhost" identified by 'password';
exit mysql
```
then attempt to import the sql dump again:
```
$ mysql -u username -p database_name < dumpfile.sql
Enter password:
ERROR 1007 (HY000) at line 21: Can't create database 'database_name'; database exists
```
How am I supposed to import the SQL dumpfile? | Open the sql file and comment out the line that tries to create the existing database. | This is a **known bug** at MySQL.
[bug 42996](http://bugs.mysql.com/bug.php?id=42996)
[bug 40477](http://bugs.mysql.com/bug.php?id=40477)
As you can see this has been a known issue since 2008 and they have not fixed it yet!!!
**WORK AROUND**
You first need to create the database to import. It doesn't need any tables. Then you can import your database.
1. first start your MySQL command line (apply username and password if you need to)
`C:\>mysql -u user -p`
2. Create your database and exit
```
mysql> DROP DATABASE database;
mysql> CREATE DATABASE database;
mysql> Exit
```
3. Import your selected database from the dump file
`C:\>mysql -u user -p -h localhost -D database -o < dumpfile.sql`
You can replace localhost with an IP or domain for any MySQL server you want to import to.
The reason for the DROP command in the mysql prompt is to be sure we start with an empty and clean database. | Error importing SQL dump into MySQL: Unknown database / Can't create database | [
"",
"sql",
"mysql",
"mysql-error-1049",
"mysql-error-1007",
""
] |
For debugging purposes, I would like to have a variable in all my templates holding the path of the template being rendered. For example, if a view renders templates/account/logout.html I would like {{ template\_name }} to contain the string templates/account/logout.html.
I don't want to go and change any views (specially because I'm reusing a lot of apps), so the way to go seems to be a context processor that introspects something. The question is what to introspect.
Or maybe this is built in and I don't know about it? | **The easy way:**
Download and use the [django debug toolbar](http://github.com/robhudson/django-debug-toolbar/tree/master). You'll get an approximation of what you're after and a bunch more.
**The less easy way:**
Replace `Template.render` with `django.test.utils.instrumented_test_render`, listen for the `django.test.signals.template_rendered` signal, and add the name of the template to the context. Note that `TEMPLATE_DEBUG` must be true in your settings file or there will be no origin from which to get the name.
```
if settings.DEBUG and settings.TEMPLATE_DEBUG
from django.test.utils import instrumented_test_render
from django.test.signals import template_rendered
def add_template_name_to_context(self, sender, **kwargs)
template = kwargs['template']
if template.origin and template.origin.name
kwargs['context']['template_name'] = template.origin.name
Template.render = instrumented_test_render
template_rendered.connect(add_template_name_to_context)
``` | From [Django 1.5 release notes](https://django-doc-test1.readthedocs.io/en/stable-1.5.x/releases/1.5.html#new-view-variable-in-class-based-views-context):
> **New view variable in class-based views context**
>
> In all generic class-based views (or any class-based view inheriting from `ContextMixin`), the context dictionary contains a `view` variable that points to the `View` instance.
Therefore, if you're using class-based views, you can use
```
{{ view.template_name }}
```
This works if `template_name` is explicitly set as an attribute on the view.
Otherwise, you can use
```
{{ view.get_template_names }}
```
to get a list of templates, e.g. `['catalog/book_detail.html']`. | Getting the template name in django template | [
"",
"python",
"django",
""
] |
Which javascript major modes exist in Emacs, and what are their key-features ? | I think what you want is this:
<http://www.corybennett.org/download/javascript-mode.el>
[Then again, maybe this what you are looking for?](http://www.emacswiki.org/emacs/JavaScriptMode)
or [this?](http://code.google.com/p/js2-mode/)
People seem to prefer (at least given the highest rated answer):
**Updated:** <http://steve-yegge.blogspot.com/2008/03/js2-mode-new-javascript-mode-for-emacs.html> | > js2-mode: a new JavaScript mode for Emacs
>
> ---
>
> This is part of a larger
> project, in progress, to permit writing Emacs extensions in JavaScript
> instead of Emacs-Lisp.
>
> **Features:**
>
> * M-x customize
> * Accurate syntax
> highlighting
> * Indentation
> * Code folding
> * Comment and string filling
> * Syntax errors
> * Strict
> warnings
> * jsdoc highlighting
<http://steve-yegge.blogspot.com/2008/03/js2-mode-new-javascript-mode-for-emacs.html>
With some documentation. | Javascript major mode in Emacs | [
"",
"javascript",
"emacs",
""
] |
In a TextBox, I could use `textBox1.SelectionStart = 4`. How can I do this in a DataGridView?
edit for clarification: suppose a specific cell is already selected and in editing mode. If I push the right arrow key, the caret moves to the right one position over whatever text is in that cell. I wish to create a button that does the same thing. | You should probably clarify a bit. Do you mean to change the selected row in a DataGridView or is there a textbox in your DataGridView that you want to move the caret for?
If you're looking to modify the selected row, try the SelectedIndex property. | ```
private void RadGridView1_SelectionChanged(object sender, Telerik.Windows.Controls.SelectionChangeEventArgs e)
{
RadGridView1.CurrentItem = RadGridView1.SelectedItem;
}
``` | C#: Changing caret position in a DataGridView | [
"",
"c#",
"datagridview",
"caret",
""
] |
I Have a cursor in stored procedure under SQL Server 2000 (not possible to update right now) that updates all of table but it usually takes few minutes to complete. I need to make it faster.
Whereas GDEPO:Entry depot, CDEPO:Exit depot,Adet: quantity,E\_CIKAN quantity that's used.
Record explanations:
1. 20 unit enters depot 01,
2. 10 unit leaves 01.
3. 5 Unit leaves 01 (E\_CIKAN for 1st record will be 15 now)
4. 10 more unit enters depot 01.
5. 3 unit leaves 01 from 1st record. Notice now 1st record has E\_CIKAN set to 18.
6. This is where the problem comes in: 3 unit needs to leave depot 01. It takes 2 unit from 1st record and 1 unit from 5th record. My SP can handle this fine as seen in picture, except it's REALLY slow.
Here's the stored procedure translated into English;
```
CREATE PROC [dbo].[UpdateProductDetails]
as
UPDATE PRODUCTDETAILS SET E_CIKAN=0;
DECLARE @ID int
DECLARE @SK varchar(50),@DP varchar(50) --SK = STOKKODU = PRODUCTID, DP = DEPOT
DECLARE @DEMAND float --Demand=Quantity, We'll decrease it record by record
DECLARE @SUBID int
DECLARE @SUBQTY float,@SUBCK float,@REMAINS float
DECLARE SH CURSOR FAST_FORWARD FOR
SELECT [ID],PRODUCTID,QTY,EXITDEPOT FROM PRODUCTDETAILS WHERE (EXITDEPOT IS NOT NULL) ORDER BY [DATE] ASC
OPEN SH
FETCH NEXT FROM SH INTO @ID, @SK,@DEMAND,@DP
WHILE (@@FETCH_STATUS = 0)
BEGIN
DECLARE SA CURSOR FAST_FORWARD FOR
SELECT [ID],QTY,E_CIKAN FROM PRODUCTDETAILS WHERE (QTY>E_CIKAN) AND (PRODUCTID=@SK) AND (ENTRYDEPOT=@DP) ORDER BY [DATE] ASC
OPEN SA
FETCH NEXT FROM SA INTO @SUBID, @SUBQTY,@SUBCK
WHILE (@@FETCH_STATUS = 0) AND (@DEMAND>0)
BEGIN
SET @REMAINS=@SUBQTY-@SUBCK
IF @DEMAND>@REMAINS --current record isnt sufficient, use it and move on
BEGIN
UPDATE PRODUCTDETAILS SET E_CIKAN=QTY WHERE ID=@SUBID;
SET @DEMAND=@DEMAND-@REMAINS
END
ELSE
BEGIN
UPDATE PRODUCTDETAILS SET E_CIKAN=E_CIKAN+@DEMAND WHERE ID=@SUBID;
SET @DEMAND=0
END
FETCH NEXT FROM SA INTO @SUBID, @SUBAD,@SUBCK
END
CLOSE SA
DEALLOCATE SA
FETCH NEXT FROM SH INTO @ID, @SK,@DEMAND,@DP
END
CLOSE SH
DEALLOCATE SH
``` | Based on our conversation in my other answer to this question, I think I have found a way to speed up your routine.
You have two nested cursors:
* The first one is selecting each row that has an exitdepot specified. It takes the product, depo and amount, and then:
* The inner cursor loop runs through the rows for that product/depot that have entrydepot specified. It adds onto the E\_CIKAN for each one, until it has allocated all the product.
So the inner cursor loop runs at least once for every exitdepot row you have. However, your system doesn't really care which items went out with which transaction - you are only trying to calculate the final E\_CIKAN values.
So ...
Your outer loop only needs to get the **total** amount of items shipped out for each product/depot combo. Hence you could change the outer cursor definition to:
```
DECLARE SH CURSOR FAST_FORWARD FOR
SELECT PRODUCTID,EXITDEPOT, Sum(Qty) as TOTALQTY
FROM PRODUCTDETAILS
WHERE (EXITDEPOT IS NOT NULL)
GROUP BY PRODUCTID, EXITDEPOT
OPEN SH
FETCH NEXT FROM SH INTO @SK,@DP,@DEMAND
```
(and then also change the matching FETCH from SH at the end of the code to match, obviously)
This means your outer cursor will have many fewer rows to loop through, and your inner cursor will have roughtly the same amount of rows to loop through.
So this should be faster. | Cursors have to be the worst performing solution to any problem when using T-SQL.
You have two options depending on the complexity of what you're really trying to accomplish:
1. Attempt to rewrite the entire set of code to use set operations. This would be the fastest performing method...but sometimes you just can't do it using set operations.
2. Replace the cursor with a combination of a table variable (with identity column), counter, and while loop. You can then loop through each row of the table variable. Performs better than a cursor...even though it may not seem like it would. | How to make a T-SQL Cursor faster? | [
"",
"sql",
"sql-server",
"database-cursor",
""
] |
I am looking for:
* What JMX is.
* Where I can find some good JMX
Tutorials.
* What JMX can provide to me as a
Java EE programmer.
* Anything else I should be aware
of. | JMX is a way to view and manipulate the runtime state of your application. It's somewhat similar in concept to SNMP, if that helps. IMO, it's indispensable for monitoring and understanding server-type applications that might not have any other user interface besides writing to a log file.
The basic approach is to create an interface for the things you want to monitor, then have a class implement the interface, then register an instance of that class with the "MBeanServer" (which actually makes the stuff defined in the interface available to JMX monitoring apps like jconsole).
Here's a trivial -- but working -- example:
(I'm assuming Java 5 or better)
## TestServerMBean.java
```
public interface TestServerMBean
{
public long getUptimeMillis();
public long getFooCount();
public void setFooCount(long val);
public void printStuff(String stuff);
}
```
## TestServer.java:
```
import java.lang.management.ManagementFactory;
import java.util.concurrent.atomic.AtomicLong;
import javax.management.ObjectName;
// If jconsole doesn't see this app automatically, invoke the application with the following java flags, and connect
// 'remotely' via jconsole.
//
// -Dcom.sun.management.jmxremote
// -Dcom.sun.management.jmxremote.port=2222 (or whatever)
// -Dcom.sun.management.jmxremote.authenticate=false
// -Dcom.sun.management.jmxremote.ssl=false
public class TestServer implements TestServerMBean
{
private final AtomicLong m_counter = new AtomicLong(0L);
private final long m_startTimeMillis = System.currentTimeMillis();
public void run() throws InterruptedException {
while (true) {
m_counter.incrementAndGet();
Thread.sleep(5000);
}
}
public long getFooCount() {
return m_counter.get();
}
public void setFooCount(long val) {
m_counter.set(val);
}
public long getUptimeMillis() {
return System.currentTimeMillis() - m_startTimeMillis;
}
public void printStuff(String stuff) {
System.out.println(stuff);
}
public static void main(String[] args) throws Exception {
TestServer ts = new TestServer();
ManagementFactory.getPlatformMBeanServer().registerMBean(ts, new ObjectName("myapp:service=MyServer"));
ts.run();
}
}
```
Compile and run TestServer.class as usual, fire up `jconsole`, connect to TestServer (it'll show up automatically, else see comments in code above), then look at the 'MBeans' tab, and you'll see our instance named `myapp:service=MyServer`. You can view the current "uptime", and watch `FooCounter` increment every 5 seconds. You can also set FooCounter to whatever (long) value you want, and invoke the `printStuff` method with any String argument.
Obviously this is a ridiculous "server", but hopefully having a simple working example will help illustrate the overall concept: being able to peek into and manipulate a running app.
There are a lot of additional features and different types of MBeans, but just the vanilla JMX shown above goes a long way, IMO. | In a nutshell JMX allows you to remotely invoke methods or view exposed data from the inside of a running JVM. A lot of applications use JMX to sort of attach a remote dashboard to their running JVMs in order to provide remote management.
For example, if you had an app server running on a machine, with JMX it would be possible to remotely view the exposed information about that server. It is also possible to code your own JMX MBeans which can expose any variables or methods inside your application. The exposed variables can then be "polled" remotely to test for certain conditions you would like to know about.
Another useful thing about JMX is that you can remotely change variables on the fly. For instance, if you have some sort of pool set up that has a maximum total amount, this maximum amount can be changed remotely without having to restart or change any configuration files on your application server.
`jconsole` is provided by Sun with Java to be able to easily view your MBeans remotely without having to code your own client solution. You could also consume the MBeans with a custom solution which can give you excellent flexibility.
Also, there are already some monitoring software that come with JMX MBean monitoring built in. Zenoss and Applications Manager 8 do this, to name a couple.
**Addition:**
There is already a lot of software that takes advantage of JMX. Tomcat exposes information that is accessible via jconsole and so does JBoss Application Server. | JMX Defined | [
"",
"java",
"jakarta-ee",
"jmx",
""
] |
I have a hashtable with n number of records. I need to copy out the records between x and y and iterate through them.
How would I do this?
Example:
HT1.Count = 500;
HT2 = HT1[0] - HT1[100];
--edit--
Just so you are aware, the reasoning for this is I am generating PDF's from .MSG files. The problem arises for the end user that when they get a 12GB PDF it causes issues :P
I need to break the PDF's into messages of 250, and then start a new PDF. So order does not really matter, neither does returning the same records each time, as it will only be done once. | My bet would be doing a custom function like this:
```
public IEnumerable<object> GetRange(Hashtable ht, int min, int max) {
int i = 0;
foreach (var key in ht.Keys) {
i++;
if (i > max) {
yield break;
}
if (i >= min) {
yield return ht[key];
} else continue;
}
}
```
However, take into account that the order of the keys is not guaranteed, so this can have an unordered sequence of objects | As others have stated, you cannot iterate over a hashtable in the way you seem to want. If, on the other hand, what you want is the result where the keys are in that range, you can do something like this:
```
public IDictionary<int, T> GetRange<T>(
IDictionary<int, T> source, int min, int max)
{
// add error checking for min,max, null, etc...
int capacity = Math.Max(0, max - min);
Dictionary<int, T> target = new Dictionary<int, T>(capacity);
for (int key = min; key < max; key++)
{
if (source.ContainsKey(key))
{
target.Add(key, source[key]);
}
}
return target;
}
```
Note that I am using the generic version (`Dictionary`) instead of the old `Hashtable`, but the idea would be the same. | copy n k/v pairs from Hashtable | [
"",
"c#",
"hashtable",
"enumerator",
""
] |
I have a MEF (Microsoft Extension Framework) application which loads some assemblies from a folder. I need to enumerate the assemblies that produced any exports for my application.
One way to do it is to enumerate imports calling `GetExportedObject().GetType().Assembly`. But it would be cleaner to do this without instantiation of imports. Is there a way to get loaded assemblies from a catalog or anything else?
I need assemblies to get their attributes like copyright, version, name and such. My folder can contain both assemblies with exports and without ones, but I need only assemblies that satisfied any imports in the app. | The AssemblyCatalog has an Assembly property. The AggregateCatalog does not have a way to get this information directly- there's no guarantee that the inner catalogs even load their parts from an assembly. The DirectoryCatalog doesn't have this capability although it might be possible to add it if there was a good reason.
Why do you want to get the list of assemblies? You may be better off not using a directory catalag, instead just scan and load the assemblies in a directory yourself, and create an AssemblyCatalog for each one and add it to an AggregateCatalog.
EDIT: MEF doesn't have a way of getting a list of all the exports that were "used" in composition. You could probably write your own catalog which would return part definitions that were shells around the default part definitions and kept track of which parts had GetExportedObject called on them. You can use the APIs in ReflectionModelServices to figure out which type corresponds to a given part definition from the default catalogs. Note that writing such a catalog would probably not be a simple undertaking. | This is one way of doing it, and is used in Caliburn.Micro:
```
var aggregateCatalog = new AggregateCatalog(...);
var assemblies = aggregateCatalog.Parts
.Select(part => ReflectionModelServices.GetPartType(part).Value.Assembly)
.Distinct()
.ToList();
``` | How to enumerate assemblies within AggregateCatalog or DirectoryCatalog in MEF? | [
"",
"c#",
"mef",
""
] |
Below are two common issues resulting in undefined behavior due to the sequence point rules:
```
a[i] = i++; //has a read and write between sequence points
i = i++; //2 writes between sequence points
```
What are other things you have encountered with respect to sequence points?
It is really difficult to find out these issues when the compiler is not able to warn us. | Here is a simple rule from Programming principles and practices using c++ by Bjarne Stroustup
> "if you change the value of a variable in an expression.Don't read or
> write twice in the same expression"
```
a[i] = i++; //i's value is changed once but read twice
i = i++; //i's value is changed once but written twice
``` | A variation of Dario's example is this:
```
void Foo(shared_ptr<Bar> a, shared_ptr<Bar> b){ ... }
int main() {
Foo(shared_ptr<Bar>(new Bar), shared_ptr<Bar>(new Bar));
}
```
which might leak memory. There is no sequence point between the evaluation of the two parameters, so not only may the second argument be evaluated before the first, but both Bar objects may also be created before any of the `shared_ptr`'s
That is, instead of being evaluated as
```
Bar* b0 = new Bar();
arg0 = shared_ptr<Bar>(b0);
Bar* b1 = new Bar();
arg1 = shared_ptr<Bar>(b1);
Foo(arg0, arg1);
```
(which would be safe, because if `b0` gets successfully allocated, it gets immediately wrapped in a `shared_ptr`), it may be evaluated as:
```
Bar* b0 = new Bar();
Bar* b1 = new Bar();
arg0 = shared_ptr<Bar>(b0);
arg1 = shared_ptr<Bar>(b1);
Foo(arg0, arg1);
```
which means that if `b0` gets allocated successfully, and `b1` throws an exception, then `b0` will never be deleted. | Which issues have you encountered due to sequence points in C and C++? | [
"",
"c++",
"c",
"sequence-points",
""
] |
I'm trying to code an application which runs un different java platforms like J2SE, J2ME, Android, etc. I already know that I'll have to rewrite most of the UI for each platform, but want to reuse the core logic.
Keeping this core portable involves three drawbacks that I know of:
1. Keeping to the old **Java 1.4 syntax**, not using any of the nice language features of Java 5.0
2. only using **external libraries** that are known to work on those platforms (that is: don't use JNI and don't have dependencies to other libs which violate this rules)
3. only using the **classes which are present** on all those platforms
I know of ways to overcome **(1)**: code in 5.0 style and automatically convert it to 1.4 (*retroweaver* - haven't tried it yet, but seems ok).
I think **(2)** is a problem that I just have to accept.
Now I'd like to know what's the best workarround for **(3)**, especially collection classes, which I miss the most. I can think of those:
* Most programmers I know just don't use `Set`, `Map`, `List`, etc. and fallback to `Vector` and plain Arrays. I think this makes code ugly in the first place. But I also know that the right choice between `TreeSet/Hashset` or `LinkedList/ArrayList` is crucial for performance, and always using `Vector` and Arrays can't be right.
* I could code my own implementations of that classes. This seems to be reinventing the wheel, and I think I could not do it as good as others have done.
* Since Java is open source, I could grab the sourcecode of the J2SE Collections framework and include into my application when building for J2ME. I don't know if this is a good idea, though. Pherhaps there are good reasons not to do this.
* Maybe there already are libraries out there, which rebuild the most important features of the collections framework, but are optimized for low end systems, pherhaps by not implementing functionality that is used infrequently. Do you know any?
Thanks for your answers and opinions!
**Edit:** I finally found a (complex, but nice) solution, and I thought by providing my own answer and accepting it, the solution would become visible at the top. But to the contrary, my answer is still at the very bottom. | It's been a while since I asked this question, and I while since I found a nice, working solution for the problem, but I had since forgotton to tell you.
My main focus was the Java Collections Framework, which is part of the `java.util` package.
I've finally taken the source code of Suns Java 6.0 and copied all the classes that belong to the Collections framework into a project of my own. This was a Java 6.0 project, but I used the jars from J2ME as classpath. Most of those classes that I copied depend on other J2SE classes, so there are broken dependencies. Anyway, it was quite easy to cut those depensencies by leaving out everything that deals with serialization (which is not a priority for me) and some minor adjustments.
I compiled the whole thing with a Java 6 compiler, and retrotranslator was used to port the resulting bytecode back to Java 1.2.
Next problem is the package name, because you can't deliver classes from `java.util` with a J2ME application and load them - the bootstrap class loader won't look into the applications jar file, the other bootloaders aren't allowed to load something with that package name, and on J2ME you can't define custom classloaders. Retrotranslator not only converts bytecode, it also helps to change name references in existing bytecode. I had to move and rename all classes in my project, e.g. `java.util.TreeMap` became `my.company.backport.java.util.TreeMap_`.
I was than able to write actual J2ME application in a second Java 6.0 project which referenced the usual `java.util.TreeMap`, using the generic syntax to create type-safe collections, compile that app to Java 6.0 byte code, and run it through retrotranslator to create Java 1.2 code that now references `my.company.backport.java.util.TreeMap_`. Note that `TreeMap` is just an example, it actually works for the whole collections framework and even for 3rd party J2SE Jars that reference that framework.
The resulting app can be packaged as a jar and jad file, and runs fine on both J2ME emulators and actual devices (tested on a Sony Ericsson W880i).
The whole process seems rather complex, but since I used Ant for build automation, and I needed retranslator anyway, there only was a one-time overhead to setup the collection framework backport.
As stated above, I've done this nearly a year ago, and writing this mostly from the top of my head, so I hope there are no errors in it. If you are interested in more details, leave me a comment. I've got a few pages of German documentation about that process, which I could provide if there is any demand. | J2ME is brutal, and you're just going to have to resign yourself to doing without some of the niceties of other platforms. Get used to Hashtable and Vector, and writing your own wrappers on top of those. Also, don't make the mistake of assuming that J2ME is standard either, as each manufacturer's JVM can do things in profoundly different ways. I wouldn't worry much about performance initially, as just getting correctness on J2ME is enough of a challenge. It is possible to write an app that runs across J2ME, J2SE and Android, as I've done it, but it takes a lot of work. One suggestion that I'd have is that you write the core of your application logic and keep it strictly to java.lang, java.util and java.io. Anywhere where you're going to be doing something that might interact with the platform, such as the file system or network, you can create an interface that your core application code interacts with, that you have different implementations for the different environments. For example, you can have an interface that wraps up HTTP stuff, and uses javax.microedition.io.HttpConnection with J2ME and java.net.HttpURLConnection on Android. It's a pain, but if you want to maintain an app running on all three of those environments, it can get you there. Good luck. | How to deal with the most common classes missing on J2ME | [
"",
"java",
"java-me",
"cross-platform",
"portability",
"midp",
""
] |
I can call a function directly (I'll use `alert` as an example) like so
```
alert("Hello World!"); // pops up an alert window
```
However, when I put a function in an object, calling it no longer works:
```
d = {func: alert};
d.func("Hello World!"); // doesn't do anything
d["func"]("Hello World!"); // also doesn't do anything
```
I figured maybe I needed to explicitly pass in a blank `this` argument, so I tried
```
d.func(null, "Hello World!") // still nothing
```
but to no avail. Interestingly, this does work
```
d.func.apply(null, ["Hello World!"]); // success!
```
but that's so gratuitously verbose it makes my teeth hurt (to quote JWZ). Is there a more concise, less ugly way? | Functions in JavaScript are passed by value. The `alert()` function is natively implemented, meaning it has no JavaScript value. Depending on your browser, the meaninfulness (forgive me for that) of that native wrapper varies. Your code actually works in Google Chrome, but won't work in Firefox, and off the top of my head I'm going to say it won't work in Internet Explorer, either, which is generally not friendly about modifying native objects and functions. You could use the following instead:
```
d = {
func: function (message) {
alert(message);
}
};
``` | If you try this:
```
function test(x) {
alert(x);
}
var x = {func: test}
x.func('Hi!');
```
It works as you expect. When I try doing this to `alert` directly Firebug gives me the following error message:
```
[Exception... "Cannot modify properties of a WrappedNative"
nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)"
location: "JS frame :: http://stackoverflow.com/questions/859466/javascript-function-in-an-object-hash :: anonymous :: line 72" data: no]
```
So I am guessing it's a security thing or something to do with it being a native function. | Javascript function in an object/hash | [
"",
"javascript",
"function",
""
] |
I used list to place cities into a trip. Then I iterate over
the list to display the trip itinerary. I would like to access
the cities by the name rather than by the trip order. So, I
thought I could use a map rather than a list but the key determines
the order. I would still like to control the order of the sequence
but be able to access the entries by a key.
Can these features be combined? Is there some standard way to address
this?
```
#include <list>
#include <iostream>
struct City{
City(std::string a_n, int a_d):name(a_n), duration(a_d){}
std::string name;
int duration;
};
int main(){
std::list<City*> trip;
trip.push_back(new City("NY", 5));
trip.push_back(new City("LA", 2));
for (std::list<City*>::iterator ii=trip.begin(); ii!=trip.end(); ++ii)
std::cout << (*ii)->name << " for " << (*ii)->duration << " days." <<std::endl;
}
``` | Often times you will need to compose multiple lists and maps. The common way is to store a pointer to the Cities in your by city lookup map from the pointers in your list. Or you can use a class like [Boost.MultiIndex](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/index.html) to do what you want in what I would say is much cleaner. It also scales much better and there is a lot less boiler plate code if you want to add new indexes. It is also usually [more space and time efficient](http://www.boost.org/doc/libs/1_39_0/libs/multi_index/doc/performance.html)
```
typedef multi_index_container<
City,
indexed_by<
sequenced<>, //gives you a list like interface
ordered_unique<City, std::string, &City::name> //gives you a lookup by name like map
>
> city_set;
``` | Create a `map<string,int> m;`, where the values are indexes to a `vector<City>`, for example `m["NY"] == 0` and `m["LA"] == 1`. | Order like a list but access by a key? | [
"",
"c++",
"stl",
"containers",
""
] |
I have a project that is currently all over the place and i'm thinking of making it MVC.
The problem is that the system is currently being used and I can not change the interface (It's in frames :s) Also there are certain things that I will need to handle myself such as password generation, login and user levels.
I already have the model side down of the MVC so I am wondering is it worth using a framework like Zend Framework or CakePHP or just to code my own View and Controllers to work around this problem?
I am going to have to work this in slowly and I'm not sure if i will be able to do that if I use one of the ready made frameworks. | Normally I would recoil in horror and advise against bringing yet another web MVC framework into the world, but it's fair to note that our hosts Joel and Jeff have another opinion on the matter:
From Joel: [In Defense of Reinventing the Wheel](http://www.joelonsoftware.com/articles/fog0000000007.html)
From Jeff: [Don't Reinvent the Wheel](http://www.codinghorror.com/blog/archives/001145.html)
One last thought: If it's a one-person project, then you only affect yourself with this choice. My resistance would spike up if a team developing a long-lived product was involved. You may do a disservice to the team and the customer if you roll your own. | I wrote my own MVC framework for Coldfusion because the current "flavour of the month" Mach-II was horrendously slow. After switching my page generation time dropped from 2-5 seconds down to 9 milliseconds.
Over the last 3 years I've developed this framework into a rival for any commercial or open-source framework I've used (and I've used quite a few) by building in function libraries and components for a range of common tasks (CMS, CC processing, Image manipulation, etc..)
Although there was no doubt some "re-inventing the wheel" the wheel I ended up with was exactly what I need to do my job. I understand how it works with an intimacy that no documentation could ever provide.
Of course, one day some future programmer may be cursing over my code wishing a pox on me for not using their favorite library - but frankly - I just couldn't care less. I wrote it for ME, it does what I need and it does it well. I also learned a lot in the process.
Having said that you are NOT automatically doing your customers/co-workers a disservice by writing your own framework. Public frameworks tend to have no real direction so they tend to bloat massively trying to keep everyone happy. This bloat means more to learn, more that can go wrong. Your framework will be meeting a much smaller set of requirements and with good documentation could be a lot easier to understand and setup than a more established public one.
I say go for it, live on the edge a little. Maybe in 5 years you'll release the next "Mach-II" or whatever and we can all bitch about it. | Should I use a framework or write my own MVC? | [
"",
"php",
"model-view-controller",
"zend-framework",
"cakephp",
"refactoring",
""
] |
First off, I'm a PM and the dev team is already mad at me. So I'd like to take a shot creating the solution to the question below.
We have a static maintenance mode html page that displays "Please check back soon" in 24 languages. Right now we are displaying all 24 translations at once and the page is pretty ugly.
I've wrapped each translation into it's own div tag like this:
```
<div id="en">
<p>Please check back soon</p>
</div>
<div id="es">
<p>Compruebe por favor más adelante</p>
</div>
...
```
I'm looking to use javascript to detect the browser language and set visibility:visible; for the div that corresponds to the browser language. And set all the other div tags to visibility:hidden;
Looking for help with detecting browser language and stripping out locale (if provided) so I have a 2 character value to use in a complex switch. | My solution would be to use the Accept-Language header in the HTTP request to find the user's preferred language and then just return one div in the correct language. This way you don't have to worry about hiding divs. Also, if you hide divs they will all be displayed initially and then only set to hidden after the Javascript executes so it won't be as good of a user experience.
Please see: <http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html> | First, this seems to be a server side solution rather than a client side solution. However, a quick search did turn up this snippet:
```
var userLang = (navigator.language) ? navigator.language : navigator.userLanguage;
alert ("The language is: " + userLang);
```
on [this page](http://answers.yahoo.com/question/index?qid=20080418104516AAssAjm).
So if you really must do it on the client then this might help. | Toggle visibility of div tags based on Browser Language | [
"",
"javascript",
"html",
"localization",
""
] |
Whenever I remove and add swing components from say JPanel, shall I perform call on validate or revalidate? | `revalidate()` is basically a `invalidate()` followed by a `validate()`.
Look at Sun's Java source code.
You want to call `revalidate()`. | **revalidate()** would be better. revalidate() marks all the container upto the top level as not proper or not valid. Then it calls validate() on the top level. The validate() method of the parent checks if at least one of its immediate children is signaled invalid or improper. it calls validate of the parent.
so calling revalidate() **automatically means** calling validate(). | Remove Swing Component Using Validate or Revalidate | [
"",
"java",
"swing",
""
] |
Why String.indexOf do not use exception but return -1 when substring not found?
The purpose of this question is: when we start custom exception.
I believe avoid the need to return special error code is right design path.
What's your opinion? | As a rule of thumb, if the purpose of a method is to check for something, then the lack of that something shouldn't be an exception. If the method is assuming that something is true, then the absence of that something would be an exception. Thus "File.exists()" doesn't throw a FileNotFoundException, but "File.open()" does. | exceptions are for exceptional cases, when a string does not contain a letter, that's hardly exceptional, unless you are using it for some extreme case. If that's what you are doing, you can always choose to throw your own exception. | Why String.indexOf do not use exception but return -1 when substring not found? | [
"",
"java",
"exception",
""
] |
I'm trying to learn [OpenGL](http://en.wikipedia.org/wiki/OpenGL) and improve my C++ skills by going through the [Nehe guides](http://nehe.gamedev.net/), but all of the examples are for Windows and I'm currently on Linux. I don't really have any idea how to get things to work under Linux, and the code on the site that has been ported for Linux has way more code in it that's not explained (so far, the only one I've gotten to work is the [SDL](http://en.wikipedia.org/wiki/Simple_DirectMedia_Layer) example: <http://nehe.gamedev.net/data/lessons/linuxsdl/lesson01.tar.gz>). Is there any other resource out there that's a bit more specific towards OpenGL under Linux? | The first thing to do is install the OpenGL libraries. I recommend:
```
freeglut3
freeglut3-dev
libglew1.5
libglew1.5-dev
libglu1-mesa
libglu1-mesa-dev
libgl1-mesa-glx
libgl1-mesa-dev
```
Once you have them installed, link to them when you compile:
```
g++ -lglut -lGL -lGLU -lGLEW example.cpp -o example
```
In example.cpp, include the OpenGL libraries like so:
```
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>
```
Then, to enable the more advanced opengl options like shaders, place this after your glutCreateWindow Call:
```
GLenum err = glewInit();
if (GLEW_OK != err)
{
fprintf(stderr, "Error %s\n", glewGetErrorString(err));
exit(1);
}
fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));
if (GLEW_ARB_vertex_program)
fprintf(stdout, "Status: ARB vertex programs available.\n");
if (glewGetExtension("GL_ARB_fragment_program"))
fprintf(stdout, "Status: ARB fragment programs available.\n");
if (glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite"))
fprintf(stdout, "Status: ARB point sprites available.\n");
```
That should enable all OpenGL functionality, and if it doesn't, then it should tell you the problems. | I'll guess that it is the compilation process that is the biggest difference initially. Here is a useful **Makefile** for compiling simple OpenGL apps on Ubuntu.
```
INCLUDE = -I/usr/X11R6/include/
LIBDIR = -L/usr/X11R6/lib
FLAGS = -Wall
CC = g++ # change to gcc if using C
CFLAGS = $(FLAGS) $(INCLUDE)
LIBS = -lglut -lGL -lGLU -lGLEW -lm
All: your_app # change your_app.
your_app: your_app.o
$(CC) $(CFLAGS) -o $@ $(LIBDIR) $< $(LIBS) # The initial white space is a tab
```
Save this to a file called *Makefile* that should be in the same directory. Compile by writing *make from terminal or :make* from Vim.
Good luck | Learning OpenGL in Ubuntu | [
"",
"c++",
"linux",
"opengl",
"ubuntu",
""
] |
I'd like to invoke the user's screen saver if such is defined, in a Windows environment.
I know it can be done using pure C++ code (and then the wrapping in C# is pretty simple), as suggested [here](http://bobmoore.mvps.org/Win32/w32tip22.htm).
Still, for curiosity, I'd like to know if such task can be accomplished by purely managed code using the dot net framework (version 2.0 and above), without p/invoke and without visiting the C++ side (which, in turn, can use windows API pretty easily). | I've an idea, I'm not sure how consistently this would work, so you'd need to research a bit I think, but hopefully it's enough to get you started.
A screen saver is just an executable, and the registry stores the location of this executable in `HKCU\Control Panel\Desktop\SCRNSAVE.EXE`
On my copy of Vista, this worked for me:
```
RegistryKey screenSaverKey = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop");
if (screenSaverKey != null)
{
string screenSaverFilePath = screenSaverKey.GetValue("SCRNSAVE.EXE", string.Empty).ToString();
if (!string.IsNullOrEmpty(screenSaverFilePath) && File.Exists(screenSaverFilePath))
{
Process screenSaverProcess = Process.Start(new ProcessStartInfo(screenSaverFilePath, "/s")); // "/s" for full-screen mode
screenSaverProcess.WaitForExit(); // Wait for the screensaver to be dismissed by the user
}
}
``` | I think having a .Net library function that does this is highly unlikely - I'm not aware of any. A quick search returned this Code Project [tutorial](http://www.codeproject.com/KB/cs/ScreenSaverControl.aspx) which contains an example of a managed wrapper which you mentioned in your question.
P/invoke exists so that you're able to access OS-specific features, of which screen savers are an example. | How to invoke the screen saver in Windows in C#? | [
"",
"c#",
".net",
"windows",
"managed",
"screensaver",
""
] |
I am building a menu that I want to display in a certain way. However, it is to be populated from a database so it cannot be hard-coded.
Essentially I want the `<li>` tags to appear in set places when they are created and was hoping that I could set their class using PHP count() and already having the CSS set up for them.
**Basically, the menu will have no more than 12 `<li>` tags. I want to be able to assign them a CSS id as they are generated. They cannot have a generic class as they have to be absolutely positioned on the page, therefore I was hoping to use count() to return the number of `<li>` tags and and then somehow assign them a unique CSS id**
```
<ul id="work_div">
<li id="one"><a href="detail/one">Project 1</a></li>
<li id="two"><a href="detail/two">Project 2</a></li>
<li id="three"><a href="detail/three">Project 3</a></li>
<li id="four"><a href="detail/four">Project 4</a></li>
</ul>
```
Basically, as the menu is populated I would like to assign the specific id to the `<li>` by using `count()` to work out which one goes where.
I'm thinking that I need to place the database results in to a variable and assign values from there????
Make any sense??
Hopefully! | it is not very clear what do you need count() for.
first of all you have to get associated array of items from database in desired order (sort by id, title, etc)
you can get something like this:
```
//result from database
$array = array(array('page_id'=>'1','sef_title'=>'one','title'=>'Project 1'),array('page_id'=>'2','sef_title'=>'two','title'=>'Project 2'),array('page_id'=>'3','sef_title'=>'three','title'=>'Project 3'));
//create counter starting from 1
$i = 1;
$arrayLinks = array();
foreach($array as $link){
$arrayLinks[] = "<li id=\"link{$i}\"><a href=\"detail/{$link['sef_title']}\">{$link['title']}</a></li>";
$i++;
}
//print result in ul
echo '<ul id="work_div">' . implode("", $arrayLinks) . '</ul>';
```
As result you will receive list with ids 'link1','link2' etc | Ok, first of all have a look at [this](http://il.php.net/manual/en/function.count.php). count() is not a function what you are looking for. It's a good idea to store the id label into database and gain them in them script in order to print later.
Basically code will looks like:
**EDIT**(After reading the comments), elements array can be extended to keep any data type you want, for example another array:
```
$elements = array ( "one" => array ( "Project 1", "detail/one"), "two" => array( "Project 2", "detail/two"));
echo "<ul id='work_div'>";
foreach( $elements as $id => $key)
{
list( $name, $href) = $key;
echo "<li id=$id><a href='$href'>$name</a></li>";
}
echo "</ul>";
```
Instead of $element you will use the row from database. | php count() to help give html elements set attributes | [
"",
"php",
"html",
"count",
""
] |
Can I have a switch statement like this:
...
```
switch (temp)
{
case "NW" or "New":
temp = "new stuff"
break;
}
```
... | No, but you can use (at least in Java)
```
switch (temp) {
case "NW":
case "New":
temp="new stuff";
break;
}
``` | Yes. This is how it is done.
```
switch (temp)
{
case "NW":
case "New":
temp = "new stuff"
break;
}
```
Actually, I answered this very [same question](https://stackoverflow.com/questions/848472/how-add-or-in-case-statements/848475#848475) before. | Can I have a Switch Statement with more than one Case Criteria? | [
"",
"c#",
".net",
"asp.net",
""
] |
So for my current project, there are basically three main Java classes:
1. GUI
2. Instant Messaging
3. Computation
Essentially, there needs to be full communication, so we've decided to use the mediator approach rather than than allow the GUI to run the entire project.
Basically, the mediator is going to encapsulate the communication. The problem we've run into is how to allow the GUI components to update without building a ton of methods for the mediator to call anytime something completes.
Ex. Say the GUI wants to log in the user, it goes through the mediator to create a thread and log in, but then the mediator has to relay the success/failure back to GUI as well as update a status message.
The other issue is things that need to update the GUI but do not need the moderator. Is it practical to just allow the GUI to create an instance of that class and run it or should everything go through the mediator?
Our original design just had the GUI managing everything, but it really killed reusability. Is there a better design method to use in this case? | If you're finding Observer to bring too much overhead, Mediator may be the best way to go. I definitely think that you shouldn't have the GUI run the show. If you're going to use the Mediator pattern, the mediator itself should be in charge. Something you might consider is a variant of the Command pattern. If you were using Ruby, I might recommend passing function callbacks around as a means of avoiding having the mediator contact the GUI for every little thing. But since it's Java, some form of encapsulating an action in Command pattern style may help. | If you don't want the callback/notification to be triggerd by the mediator, you can inject the callback into the login function and have login call it when it finishes.
I don't know how you would go about injecting the callback in Java, though. In a language where functions are first class citizens, you could just pass the function, but you're in Java so I guess you will have to use the command pattern as kmorris suggested. | Does Mediator Pattern work in this situation? | [
"",
"java",
"user-interface",
"design-patterns",
"class",
"mediator",
""
] |
> **Possible Duplicate:**
> [What to do when I want to use database constraints but only mark as deleted instead of deleting?](https://stackoverflow.com/questions/771197/what-to-do-when-i-want-to-use-database-constraints-but-only-mark-as-deleted-inste)
Is it more appropriate to set some kind of "IsDeleted" flag in a heavily used database to simply mark records for deletion (and then delete them later), or should they be deleted directly?
I like the IsDeleted flag approach because it gives an easy option to restore data in case something went terribly wrong, and I could even provide some kind of "Undo" function to the user. The data I'm dealing with is fairly important.
I don't like IsDeleted because it really messes with data retrieval queries, as I'd have to filter by the state of the IsDeleted flag in addition to the regular query. Queries use no more than one index so I'd also assume that this would slow down things tremendously unless I create composite indexes.
So, what is more appropriate? Is there a better "middle way" to get the benefits of both, and what are you using & why? | As a rule of thumb I never delete any data. The type of business I am in there are always questions suchas 'Of the customers that cancelled how many of them had a widget of size 4' If I had deleted the customer how could I get it. Or more likely if had deleted a widget of size 4 from the widget table this would cause a problem with referential integrity. An 'Active' bit flag seems to work for me and with indexing there is no big performance hit. | I would be driven by business requirements. If the client expects you to restore deleted data instantly and undeleting data is part of business logic and/or use cases then *isDeleted* flag makes sense.
Otherwise, by leaving deleted data in the database, you address problems that are more suitable to be addressed by database backups and maintenance procedures. | SQL Server DB - Deleting Records, or setting an IsDeleted flag? | [
"",
"sql",
"database",
""
] |
I've got a C++ app that I'm porting from Win32 to OSX. I'd like to be able to launch arbitrary files as if the user opened them. This is easy on windows using ShellExecute. How do I accomplish the same thing on the Mac?
Thanks! | You can call `system();` in any C++ application. On OSX, you can use the [open](http://developer.apple.com/documentation/Darwin/Reference/Manpages/man1/open.1.html) command to launch things as if they were clicked on.
From the documentation for open:
> The open command opens a file (or a directory or URL), just as if you had double-clicked the file's icon. If no application name is specified, the default application as determined via LaunchServices is used to open the specified files.
All together, it would look like:
```
string command = "open " + filePath;
system(command.c_str());
``` | Another suggestion if you're working with cocoa:
```
[[NSWorkspace sharedWorkspace] openFile:@"pathToFile"];
```
There are other similar methods in `NSWorkspace` as well. For example to open an application or a URL:
```
[[NSWorkspace sharedWorkspace] launchApplication:@"pathToApplication"];
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"URL"]];
```
Working through `[NSWorkspace sharedWorkspace]` can give you a bit more control than the standard C `system()` call.
*Edit:* Note that you can use [Objective-C++](http://developer.apple.com/DOCUMENTATION/Cocoa/Conceptual/ObjectiveC/Articles/ocCPlusPlus.html "How to mix Objective-C and C++") to mix C++ code with Objective-C code and thereby call cocoa methods. | OSX equivalent of ShellExecute? | [
"",
"c++",
"macos",
"shellexecute",
""
] |
I'm looking for feedback on which analyzer to use with an index that has documents from multiple languages. Currently I am using the simpleanalyzer, as it seems to handle the broadest amount of languages. Most of the documents to be indexed will be english, but there will be the occasional double-byte language indexed as well.
Are there any other suggestions or should I just stick with the simpleanalyzer.
Thanks | SimpleAnalyzer really is simple, all it does is lower-case the terms. I'd have thought that the StandardAnalyzer would give better results than SimpleAnalyzer even with non-english language data. You could perhaps improve it slightly by supplying a custom list of stop words in addition to the default english-language ones. | From your description, I presume you have document of multiple languages but each document has text in only one language.
For this case, you can use Nutch's language identification to get the language of the document. Then use respective language analyzer to index. To get the correct results for search, you need apply language identification to the search query and use that analyzer.
The upside here is you will be able to use language-specific stemmer & stopwords, pushing the quality of search up. The extra overhead while indexing should be acceptable. The search queries where language identification fails to identify correct language may suffer though. I have used this couple of years back and the results were better than expected.
For CJK, you can apply similar technique but the tools might be different. | Best cross-language analyzer to use with lucene index | [
"",
"java",
"lucene",
""
] |
I wrote these lines but i have NullReferenceException. please help me how to fix it!
```
string FullPath = TempPath + FileName;
System.Drawing.Image Adimg = null;
Adimg = System.Drawing.Image.FromFile(MapPath(FullPath));
```
I put these lines in a Public bool method and TempPath is class property and FileName is input for the method.
```
exception Detail:
System.NullReferenceException was unhandled by user code
Message="Object reference not set to an instance of an object."
Source="System.Web"
StackTrace:
at System.Web.UI.Page.MapPath(String virtualPath)
at FileIO.HasValidAttributes(String FileName) in g:\MyProjects\ASP.net Projects\ADBridge\adengine2\App_Code\FileIO.cs:line 44
at UploadPage.<Page_Load>b__0(Object sender1, EventArgs e1) in g:\MyProjects\ASP.net Projects\ADBridge\adengine2\UploadPage.aspx.cs:line 29
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
InnerException:
```
I have no Time! | Try calling MapPath on the Server object instead:
```
HttpContext.Current.Server.MapPath(FullPath)
``` | Here's a few tips:
1. Use Path.Combine to build paths from individual pieces
2. Verify that FullPath refer to a file that is
* Present on disk
* Readable by the web process (ie. not running the web process under System Account or similar) | Object reference not set to an instance of an object? | [
"",
"c#",
"file",
"file-io",
"filesystems",
""
] |
I have a database showing up in SQL Enterprise Manager as "(Restoring...)"
If i do SP\_WHO there is no restore process.
The disk and CPU activity on the server is very low
I think it is not restoring at all.
How can I get rid of this?
I've tried renaming the underlying MDF file, but even when I do "NET STOP MSSQLSERVER" it tells me the file is open.
I've tried using PROCEXP to find what process has the file open, but even the latest PROCEXP can't seem to do that on Windows Server 2003 R2 x64. The lower pane view is blank.
In the SQL Server log it says "the database is marked RESTORING and is in a state that does not allow recovery to be run" | Sql Server has two backup types:
* Full backup, contains the entire database
* Transaction log backup, contains only the changes since the last full backup
When restoring, Sql Server asks you if you want to restore additional logs after the full backup. If you choose this option, called WITH NORECOVERY, the database will be left in Restoring state. It will be waiting for more transaction logs to be restored.
You can force it out of Restoring mode with:
```
RESTORE DATABASE <DATABASE_NAME> WITH RECOVERY
```
If this command gives an error, detach the database, remove the MDF files, and start the restore from scratch. If it keeps failing, your backup file might be corrupted.
Here's a screenshot of the restore options, with the default selected. The second option will leave the database in Restoring state.
[Image of the restore options http://img193.imageshack.us/img193/8366/captureu.png](http://img193.imageshack.us/img193/8366/captureu.png)
P.S.1. Are you running the 64 bit version of process explorer? Verify that you see procexp64.exe in the task manager.
P.S.2. This is more like a question for [serverfault](http://serverfault.com). | WITH RECOVERY option is used by default when RESTORE DATABASE/RESTORE LOG commands is executed. If you're stuck in "restoring" process you can bring back a database to online state by executing:
```
RESTORE DATABASE YourDB WITH RECOVERY
GO
```
You can look for more options and some third party tools on this SO post <https://stackoverflow.com/a/21192066/2808398> | SQL Server 2005 Restore Hanging | [
"",
"sql",
"sql-server",
"sql-server-2005",
"restore",
""
] |
I have this code written up to snatch some weather data and make it available on my website:
```
if( ! $xml = simplexml_load_file('http://www.weather.gov/data/current_obs/KBED.xml') )
{
echo 'unable to load XML file';
}
else
{
$temp = $xml->temp_f.' Degrees';
$wind = $xml->wind_mph;
$wind_dir = $xml->wind_dir;
$gust = $xml->wind_gust_mph;
$time = $xml->observation_time;
$pres = $xml->pressure_in;
$weath = $xml->weather;
}
```
And then I just echo them out inside the tags I want them inside. My site is low traffic, but I'm wondering what the "best" way is to do something like this if I were to spike way up in traffic. Should I write those variables I want into a database every hour (when the XML is refreshed) with a cron job to save pinging the server each time, or is that not bad practice? I understand this is a bit subjective, but I have no one else to ask for "best ways". Thanks!! | * Set up a cron job to periodically fetch the XML document, parse it and store the variables in a database.
* When a page is requested, fetch the variables from the database and render your page.
* It is a good idea to store the timestamp of the last update in the database as well, so that you can tell when the data is stale (because the weather website is down or so).
This setup looks very reasonable to me. | I would suggest the following:
* When you first get the content of the xml, parse it, and serialise it to a file, with a timestamp attached to the file in some way (perhaps as part of the serialised data structure)
* Every time the page loads, grab that serialised data, and check the timestamp. If it's passed a certain point, go and grab the xml again and cache it, making sure to update the timestamp. If not, just use that data.
That should work, means you only have to go get the xml occasionally, and also, once the cache has expired, you don't have the waste of going and getting it regularly even though no-one is visiting (since it is only updated on a request). | What's the ideal way to implement this PHP/XML function in a website? | [
"",
"php",
"html",
"xml",
""
] |
I'm just getting started with c++ development and I would like to use emacs to write the code and then compile and run it from within emacs using the visual studio 6 compiler. I have already googled around a bit but just can't seem to find an explanation of how this is done.
Any pointers?
Thanks for your help,
joerg | I have done this as a matter of course over the past few years. There are two ways to do this:
1. In the older versions of VS (including VS 6.0), there is a button to export the nmake file for the project. I do this on occasion and then use nmake to compile. I have
(setq compile-command "nmake debug ")
in my .xemace/init.el for this. You have to add the name of the nmake file, and nmake.exe has to be in your path. (BTW, I modified compilation-error-regexp-alist-alist to help moving through the errors. Let me know if you want this as well.)
2. Newer versions of VS do not have the button to export the nmake file. For these I call devenv.com. In this case I have
(setq compile-command "devenv.com /build Debug ")
in my .xemacs/init.el. You have to add the name of the .sln file. Although I did not do this with VS 6.0, I believe that it may work as well. | I am not sure if you would consider merely swapping the text editor inside of Visual Studio with Emacs, but here is a sf.net project which does just that.
<http://sourceforge.net/projects/visemacs/> | Using Visual Studio 6 C++ compiler from within Emacs | [
"",
"c++",
"visual-studio",
"emacs",
"visual-c++-6",
""
] |
I'm putting together PUT/DELETE links, a la Rails, which when clicked create a POST form with an hidden input labelled \_method that sends the intended request type. I want to make it DRYer, but my jQuery knowledge isn't up to it.
HTML:
```
<a href="/articles/1" class="delete">Destroy Article 1</a>
<a href="/articles/1/publish" class="put">Publish Article 1</a>
```
jQuery:
```
$(document).ready(function() {
$('.delete').click(function() {
if(confirm('Are you sure?')) {
var f = document.createElement('form');
$(this).after($(f).attr({
method: 'post',
action: $(this).attr('href')
}).append('<input type="hidden" name="_method" value="DELETE" />'));
$(f).submit();
}
return false;
});
$('.put').click(function() {
var f = document.createElement('form');
$(this).after($(f).attr({
method: 'post',
action: $(this).attr('href')
}).append('<input type="hidden" name="_method" value="PUT" />'));
$(f).submit();
return false;
});
});
``` | Okay, so I finally tested this. It does what it claims on the box.
```
$(document).ready(function() {
$.fn.getClassInList = function(list){
for(var i = 0; i < list.length; i++)
{
if($(this).hasClass(list[i]))
return list[i];
}
return "";
}
$('.delete,.put').click(function() {
if(confirm('Are you sure?')) {
var f = document.createElement('form');
$(this).after($(f).attr({
method: 'post',
action: $(this).attr('href')
}).append('<input type="hidden" name="_method" value="'
+ $(this).getClassInList(['put', 'delete']).toUpperCase()
+ '" />'));
$(f).submit();
}
return false;
});
});
``` | You can just use forms instead of links and let the [jQuery form plugin](http://www.malsup.com/jquery/form/) handle the submission if you want to use ajax:
```
<form class="delete" method="post" action="/articles/1">
<input type="hidden" name="_method" value="delete"/>
<button type="submit">Delete</button>
</form>
```
jQuery:
```
$(document).ready(function() {
$('form.delete').ajaxForm(options);
});
```
The options variable can contain pre and post-submit callbacks.
Style your buttons like links if that's what you need. | DRY jQuery for RESTful PUT/DELETE links | [
"",
"javascript",
"jquery",
"rest",
""
] |
I'm sending a mail function to myself.
My first line reads 'Order for $name on $date'
The $name variable comes from a form the user fills out.
I would like the $date variable to be today's date, whatever that is on that day.
How can I make the $date variable show today's date? | ```
$date = date('m/d/Y');
```
see <http://en.php.net/manual/en/function.date.php> for the syntax of date() | <https://www.php.net/manual/en/function.date.php> The date() function does that. | How can I have the date from today show up with PHP? | [
"",
"php",
"function",
"date",
"variables",
""
] |
With jQuery code like:
```
$("#myid").click(myfunction);
function myfunction(arg1, arg2) {/* something */}
```
How do I pass arguments to `myfunction` while using jQuery? | The simplest way is to do it like so (assuming you don't want any of the event information passed to the function)...
```
$("#myid").click(function() {
myfunction(arg1, arg2);
});
```
[jsFiddle](http://jsfiddle.net/y4Ak6/).
This create an anonymous function, which is called when the `click` event is triggered. This will in turn call `myfunction()` with the arguments you provide.
If you want to keep the [`ThisBinding`](http://es5.github.io/#x11.1.1) (the value of `this` when the function is invoked, set to the element which triggered the event), then call the function with [`call()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call).
```
$("#myid").click(function() {
myfunction.call(this, arg1, arg2);
});
```
[jsFiddle](http://jsfiddle.net/Tk7yF/).
You can't pass the reference directly in the way your example states, or its single argument will be the [jQuery `event` object](http://api.jquery.com/category/events/event-object/).
If you *do* want to pass the reference, you must leverage jQuery's [`proxy()`](http://api.jquery.com/jQuery.proxy/) function (which is a cross browser wrapper for [`Function.prototype.bind()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)). This lets you pass arguments, which are bound *before* the `event` argument.
```
$("#myid").click($.proxy(myfunction, null, arg1, arg2));
```
[jsFiddle](http://jsfiddle.net/dLPu9/).
In this example, `myfunction()` would be executed with its `ThisBinding` intact (`null` is not an object, so the normal `this` value of the element which triggered the event is used), along with the arguments (in order) `arg1`, `arg2` and finally the jQuery `event` object, which you can ignore if it's not required (don't even name it in the function's arguments).
You could also use use the jQuery `event` object's [`data`](http://api.jquery.com/event.data/) to pass data, but this would require modifying `myfunction()` to access it via `event.data.arg1` (which aren't *function arguments* like your question mentions), or at least introducing a manual proxy function like the former example or a generated one using the latter example. | ```
$("#myid").on('click', {arg1: 'hello', arg2: 'bye'}, myfunction);
function myfunction(e) {
var arg1 = e.data.arg1;
var arg2 = e.data.arg2;
alert(arg1);
alert(arg2);
}
//call method directly:
myfunction({
arg1: 'hello agian',
arg2: 'bye again'
});
```
Also allows you to bind and unbind specific event handlers using the on and off methods.
Example:
```
$("#myid").off('click', myfunction);
```
This would unbind the myfunction handler from #myid | How can I pass arguments to event handlers in jQuery? | [
"",
"javascript",
"jquery",
""
] |
If you were to hire a javascript developer would you expect them to know jquery?
I just started using stack overflow this week and knew that jquery led the pack, but didn't realize the extent of it until I noticed that MooTools (my favorite) has 59 questions while jquery has over 4000. (of course, a good statistician could attribute jquery having more questions to it's usability, rather than it's popularity--but we know that's false)
And then I started noticing that many people post questions with the tag "javascript" but not "jquery" when every line of their code is jquery--like it's the de facto javascript 2.0, or that they don't even realize they aren't writing "javascript" but rather jquery.
Anyway, I ask this because I've always been freelance and could use whatever framework I want on a project. But lately I've been recommended to be the front-end developer for a couple companies. I want a feel for the community's expectations to know if I should put some other personal projects on hold to pick up jquery before exploring the positions that might be offered. | No. I'd expect them to know how JS works. A good JS developer will pick up jQuery in less than a week, probably a few hours.
A developer who knows jQuery but doesn't know JS has a great deal to learn and would only be considered for the most junior roles.
jQuery is definitely not JS2.0 - it's a great standardisation framework if you still need to target IE8 and the like, but it's not great at mobile, it can't be loaded with `async` or `defer`, it doesn't support newer features like passive events, and its primary optimisations are about finding elements in an already built DOM (which means it doesn't add much value for client side DOM builders).
I would expect them to have heard of it, and be able to talk about its strengths and weaknesses against other frameworks. | They should at least know what JQuery is, and be able to tell why they chose it or another framework. Next to that, a basic understanding of the most popular javascript framework can never hurt. | Do javascript developers need to know jquery? | [
"",
"javascript",
"jquery",
"frameworks",
"mootools",
""
] |
I have a binary file that was created on a unix machine. It's just a bunch of records written one after another. The record is defined something like this:
```
struct RECORD {
UINT32 foo;
UINT32 bar;
CHAR fooword[11];
CHAR barword[11];
UNIT16 baz;
}
```
I am trying to figure out how I would read and interpret this data on a Windows machine. I have something like this:
```
fstream f;
f.open("file.bin", ios::in | ios::binary);
RECORD r;
f.read((char*)&detail, sizeof(RECORD));
cout << "fooword = " << r.fooword << endl;
```
I get a bunch of data, but it's not the data I expect. I'm suspect that my problem has to do with the endian difference of the machines, so I've come to ask about that.
I understand that multiple bytes will be stored in little-endian on windows and big-endian in a unix environment, and I get that. For two bytes, 0x1234 on windows will be 0x3412 on a unix system.
Does endianness affect the byte order of the struct as a whole, or of each individual member of the struct? What approaches would I take to convert a struct created on a unix system to one that has the same data on a windows system? Any links that are more in depth than the byte order of a couple bytes would be great, too! | As well as the endian, you need to be aware of padding differences between the two platforms. Particularly if you have odd length char arrays and 16 bit values, you may well find different numbers of pad bytes between some elements.
Edit: if the structure was written out with no packing, then it should be fairly straightforward. Something like this (untested) code should do the job:
```
// Functions to swap the endian of 16 and 32 bit values
inline void SwapEndian(UINT16 &val)
{
val = (val<<8) | (val>>8);
}
inline void SwapEndian(UINT32 &val)
{
val = (val<<24) | ((val<<8) & 0x00ff0000) |
((val>>8) & 0x0000ff00) | (val>>24);
}
```
Then, once you've loaded the struct, just swap each element:
```
SwapEndian(r.foo);
SwapEndian(r.bar);
SwapEndian(r.baz);
``` | Actually, endianness is a property of the underlying hardware, not the OS.
The best solution is to convert to a standard when writing the data -- Google for "network byte order" and you should find the methods to do this.
Edit: here's the link: <http://www.gnu.org/software/hello/manual/libc/Byte-Order.html> | How do I convert a big-endian struct to a little endian-struct? | [
"",
"c++",
"struct",
"endianness",
""
] |
I have been messing around with recursion today. Often a programming technique that is not used enough.
I set out to recursively reverse a string. Here's what I came up with:
```
//A method to reverse a string using recursion
public String reverseString(String s){
char c = s.charAt(s.length()-1);
if(s.length() == 1) return Character.toString(c);
return c + reverseString(s.substring(0,s.length()-1));
}
```
My question: is there a better way in Java? | The best way is not to use recursion. These stuff are usually used to teach students the recursion concept, not actual best practices. So the way you're doing it is just fine. Just don't use recursion in Java for these kind of stuff in real world apps ;)
PS. Aside what I just said, I'd choose `""` as the base case of my recursive function:
```
public String reverseString(String s){
if (s.length() == 0)
return s;
return reverseString(s.substring(1)) + s.charAt(0);
}
``` | If you're going to do this, you want to operate on a character array, because a String is immutable and you're going to be copying Strings all over the place if you do it that way.
This is untested and totally stream of consciousness. It probably has an OB1 somewhere. And very not-Java.
```
public String reverseString(String s)
{
char[] cstr = s.getChars();
reverseCStr(cstr, 0, s.length - 1);
return new String(cstr);
}
/**
* Reverse a character array in place.
*/
private void reverseCStr(char[] a, int s, int e)
{
// This is the middle of the array; we're done.
if (e - s <= 0)
return;
char t = a[s];
a[s] = a[e];
a[e] = t;
reverseCStr(a, s + 1, e - 1);
}
``` | Whats the best way to recursively reverse a string in Java? | [
"",
"java",
"recursion",
"string",
""
] |
I have the following functor:
```
class ComparatorClass {
public:
bool operator () (SimulatedDiskFile * file_1, SimulatedDiskFile * file_2) {
string file_1_name = file_1->getFileName();
string file_2_name = file_2->getFileName();
cout << file_1_name << " and " << file_2_name << ": ";
if (file_1_name < file_2_name) {
cout << "true" << endl;
return true;
}
else {
cout << "false" << endl;
return false;
}
}
};
```
It is supposed to be a strict weak ordering, and it's this long (could be one line only) for debug purposes.
I'm using this functor as a comparator functor for a stl::set. Problem being, it only inserts the first element. By adding console output to the comparator function, I learned that it's actually comparing the file name to itself **every time**.
Other relevant lines are:
```
typedef set<SimulatedDiskFile *, ComparatorClass> FileSet;
```
and
```
// (FileSet files_;) <- SimulatedDisk private class member
void SimulatedDisk::addFile(SimulatedDiskFile * file) {
files_.insert(file);
positions_calculated_ = false;
}
```
**EDIT:** the code that calls .addFile() is:
```
current_request = all_requests.begin();
while (current_request != all_requests.end()) {
SimulatedDiskFile temp_file(current_request->getFileName(), current_request->getResponseSize());
disk.addFile(&temp_file);
current_request++;
}
```
Where all\_requests is a list, and class Request is such that:
```
class Request {
private:
string file_name_;
int response_code_;
int response_size_;
public:
void setFileName(string file_name);
string getFileName();
void setResponseCode(int response_code);
int getResponseCode();
void setResponseSize(int response_size);
int getResponseSize();
};
```
I wish I could offer my hypotesis as to what's going on, but I actually have no idea. Thanks in advance for any pointers. | There's nothing wrong with the code you've posted, functionally speaking. Here's a complete test program - I've only filled in the blanks, not changing your code at all.
```
#include <iostream>
#include <string>
#include <set>
using namespace std;
class SimulatedDiskFile
{
public:
string getFileName() { return name; }
SimulatedDiskFile(const string &n)
: name(n) { }
string name;
};
class ComparatorClass {
public:
bool operator () (SimulatedDiskFile * file_1, SimulatedDiskFile * file_2) {
string file_1_name = file_1->getFileName();
string file_2_name = file_2->getFileName();
cout << file_1_name << " and " << file_2_name << ": ";
if (file_1_name < file_2_name) {
cout << "true" << endl;
return true;
}
else {
cout << "false" << endl;
return false;
}
}
};
typedef set<SimulatedDiskFile *, ComparatorClass> FileSet;
int main()
{
FileSet files;
files.insert(new SimulatedDiskFile("a"));
files.insert(new SimulatedDiskFile("z"));
files.insert(new SimulatedDiskFile("m"));
FileSet::iterator f;
for (f = files.begin(); f != files.end(); f++)
cout << (*f)->name << std::endl;
return 0;
}
```
I get this output:
```
z and a: false
a and z: true
z and a: false
m and a: false
m and z: true
z and m: false
a and m: true
m and a: false
a
m
z
```
Note that the set ends up with all three things stored in it, and your comparison logging shows sensible behaviour.
**Edit:**
Your bug is in these line:
```
SimulatedDiskFile temp_file(current_request->getFileName(), current_request->getResponseSize());
disk.addFile(&temp_file);
```
You're taking the address of a local object. Each time around the loop that object is destroyed and the next object is allocated into exactly the same space. So only the final object still exists at the end of the loop and you've added multiple pointers to that same object. Outside the loop, all bets are off because now none of the objects exist.
Either allocate each SimulatedDiskFile with new (like in my test, but then you'll have to figure out when to delete them), or else don't use pointers at all (far easier if it fits the constraints of your problem). | And here is the problem:
```
SimulatedDiskFile temp_file(current_request->getFileName(),
current_request->getResponseSize());
disk.addFile(&temp_file);
```
You are adding a pointer to a variable which is immediately destroyed. You need to dynamically create your SDF objects. | STL string comparison functor | [
"",
"c++",
"string",
"stl",
"functor",
""
] |
I would like to send dynamically created images to my users, such as charts, graphs etc. These images are "throw-away" images, they will be only sent to one user and then destroyed, hence the "no files involved".
I would like to send the image directly to the user, without saving it on the file system first. With PHP this could be achieved by linking an image in your HTML files to a PHP script such as:
edit: SO swallowed my image tag:
```
<img src="someScript.php?param1=xyz">
```
The script then sent the correct headers (filetype=>jpeg etc) to the browser and directly wrote the image back to the client, without temporarily saving it to the file system.
How could I do something like this with a WSGI application. Currently I am using Python's internal SimpleWSGI Server. I am aware that this server was mainly meant for demonstration purposes and not for actual use, as it lacks multi threading capabilities, so please don't point this out to me, I am aware of that, and for now it fulfills my requirements :)
Is it really as simple as putting the URL into the image tags and handling the request with WSGI, or is there a better practise?
Has anyone had any experience with this and could give me a few pointers (no 32Bit ones please)
Thanks,
Tom | It is not related to WSGI or php or any other specific web technology. consider
```
<img src="someScript.php?param1=xyz">
```
in general for url `someScript.php?param1=xyz` server should return data of image type and it would work
Consider this example:
```
from wsgiref.simple_server import make_server
def serveImage(environ, start_response):
status = '200 OK'
headers = [('Content-type', 'image/png')]
start_response(status, headers)
return open("about.png", "rb").read()
httpd = make_server('', 8000, serveImage)
httpd.serve_forever()
```
here any url pointing to serveImage will return a valid image and you can use it in any `img` tag or any other tag place where a image can be used e.g. css or background images
Image data can be generated on the fly using many third party libraries e.g. PIL etc
e.g see examples of generating images dynamically using python imaging library
<http://lost-theory.org/python/dynamicimg.html> | YES. It is as simple as putting the url in the page.
```
<img src="url_to_my_application">
```
And your application just have to return it with the correct mimetype, just like on PHP or anything else. Simplest example possible:
```
def application(environ, start_response):
data = open('test.jpg', 'rb').read() # simulate entire image on memory
start_response('200 OK', [('content-type': 'image/jpeg'),
('content-length', str(len(data)))])
return [data]
```
Of course, if you use a framework/helper library, it might have helper functions that will make it easier for you.
I'd like to add as a side comment that multi-threading capabilities are not quintessential on a web server. If correctly done, you don't need threads to have a good performance.
If you have a well-developed event loop that switches between different requests, and write your request-handling code in a threadless-friendly manner (by returning control to the server as often as possible), you can get even *better* performance than using threads, since they don't make anything run faster and add overhead.
See [twisted.web](http://twistedmatrix.com/trac/wiki/TwistedWeb) for a good python web server implementation that doesn't use threads. | Creating dynamic images with WSGI, no files involved | [
"",
"python",
"image-processing",
"wsgi",
""
] |
We've been doing a lot of work with LINQ lately, mainly in a LINQ-to-Objects sense. Unfortunately, some of our queries can be a little complicated, especially when they start to involve multiple sequences in combinations. It can be hard to tell exactly what's going on, when you get queries that start to look like:
```
IEnumerable<LongType> myCompanies = relevantBusiness.Children_Companies
.Select(ca => ca.PR_ContractItemId)
.Distinct()
.Select(id => new ContractedItem(id))
.Select(ci => ci.PR_ContractPcrId)
.Distinct()
.Select(id => new ContractedProdCompReg(id))
.Select(cpcr => cpcr.PR_CompanyId)
.Distinct();
var currentNewItems = myCompanies
.Where(currentCompanyId => !currentLic.Children_Appointments.Select(app => app.PR_CompanyId).Any(item => item == currentCompanyId))
.Select(currentId => new AppointmentStub(currentLic, currentId))
.Where(currentStub=>!existingItems.Any(existing=>existing.IsMatch(currentStub)));
Items = existingItems.Union(newItems).ToList();
```
etc., etc...
Even when you debug, it can be difficult to tell who's doing what to who and when. Short of gratuitously calling "ToList" on sequences to get things I can examine more easily, does anyone have any good suggestions for how to debug "complicated" LINQ? | A query like that seems to indicate to me that you're not doing a good job choosing appropriate data structures, or doing a good job with encapsulation and separation of tasks. I'd suggest taking a look at it and breaking it up.
In general, though, if I want to debug a LINQ query that isn't obviously correct, I'd break it up into subqueries and examine the results one-at-a-time in the debugger. | I know my answer is "a bit" late, but I had to share this:
Just discovered **[LinqPad](http://www.linqpad.net/)** and it's AMAZING (not to mention free).
Can't believe I've written Linq for so long without knowing about this tool.
As far as I understand, it's the work of the author(s?) of O'Reilly's ["C# 3.0 in a Nutshell"](http://www.albahari.com/nutshell/) and ["C# 4.0 in a Nutshell"](http://www.albahari.com/nutshell/) . | Debugging LINQ Queries | [
"",
"c#",
"linq",
"debugging",
""
] |
I have a a web flow where I need to capture data on one of the screens.
This data is stored in an object which will be held in a list in the bean.
On submitting the page I want to be able to create an object, and add it to the list in the bean.
Is this possible?
Thanks | In the end I managed to get it working with the following flows.
I created a helper bean to hold a function for adding to the list held in the form bean.
```
<view-state id="page2" view="page2">
<transition on="save" to="addToList">
<action bean="form" method="bindAndValidate"/>
</transition>
<transition on="back" to="page1">
<action bean="formAction" method="bindAndValidate"/>
</transition>
<transition on="next" to="page3">
<action bean="formAction" method="bindAndValidate"/>
</transition>
</view-state>
<action-state id="addToList">
<bean-action bean="helperbean" method="addToList">
<method-arguments>
<argument expression="conversationScope.form"/>
</method-arguments>
</bean-action>
<transition on="success" to="page2"/>
</action-state>
```
It then displays the original page again | You need to do a couple of things:
1. Place an object into the flow scope (or add an extra field on an existing object like your Form) to give a fixed binding path to to the object you want to edit. If you don't do this, you can't take advantage of Spring's databinding.
2. Write a method on your FormAction to place this object into your list, and set this method to run on the transition followed when you submit the current page. This method can clean up the flowscope-level resources used in (1) as required.
**Edit** The Webflow documentation has good examples of how to execute actions on transitions. For Webflow version 2 check out [Executing view transitions](http://static.springframework.org/spring-webflow/docs/2.0.x/reference/html/ch04s12.html) and [Executing actions](http://static.springframework.org/spring-webflow/docs/2.0.x/reference/html/ch05.html). For version 1, see [Flow definition](http://static.springframework.org/spring-webflow/docs/1.0.x/reference/flow-definition.html). | When using Spring Web Flow 1, how do I add an object to a list in a bean? | [
"",
"java",
"spring",
"spring-webflow",
""
] |
I'm having some issues with a bit of LINQ syntax and I believe I'm missing something very simple here.
I've got a basic class defined as:
```
public class ParseData
{
public int Offset { get; set; }
public int Length { get; set; }
public string AssociatedCode { get; set; }
}
```
I have a collection of these class items that will be processed:
```
public ObservableCollection<ParseData> OffsetList { get; set; }
```
I have a method that queries this collection to see if there are any entries that match a particular criteria and based on whether or not any do, will process the items involved differently.
Here's the syntax I'm using (LINQ syntax first in while loop):
```
private void ParseText()
{
//Prep code for while loop
while (currentSpacePosition != -1)
{
var possibleOffset = OffsetList.Where(offset => offset.Offset.Equals(currentCursorPosition)).ToList<ParseData>();
nextCursorPosition = currentSpacePosition + 1;
currentTextBlock = Text.Substring(currentCursorPosition,(currentSpacePosition - currentCursorPosition) + 1);
if (possibleOffset.Count != 0)
{
//Process one way;
AddHyperlinkButton(currentTextBlock);
}
else
{
//Process another way.
AddTextBlock(currentTextBlock);
}
currentCursorPosition = nextCursorPosition;
currentSpacePosition = Text.IndexOf(' ', currentCursorPosition);
}
//More processing
}
```
What am I missing here? The poosibleOffset variable keeps returning an empty list, though if I step through the code, there is an an item in the OffsetList that contains an offset prerty that will meet my criteria for selection, which suggest that my syntax isn't correct when trying to check values.
If you need more code or information about the process, I'll be happy to provide it.
Thanks in advance.
Cheers,
Steve | Ladies and gentlemen, please allow me to apologize for wasting your valuable time. I however, am a massive idiot. In the process of debugging some issues, I commented out the code that initialized the property OffsetList, which was the key element in my search criteria. Had I noticed this earlier, the LINQ query would have worked the first time out of the gate.
Thanks to all of you who tried to save me from my own stupidity. I will leave the question up for a short while so that you can all point and laugh, then I will close. | There's nothing wrong with your use of Linq really:
```
public class ParseData
{
public int Offset { get; set; }
}
public ObservableCollection<ParseData> OffsetList { get; set; }
public Program()
{
OffsetList = new ObservableCollection<ParseData> { new ParseData { Offset = 5 } };
int offset = 5;
int found = OffsetList.Where(o => o.Offset.Equals(offset)).ToList().Count;
Console.WriteLine("Found: " + found);
}
```
Output:
```
Found: 1
``` | Linq Syntax issue | [
"",
"c#",
"linq",
""
] |
For people suggesting throwing an exception:
Throwing an exception doesn't give me a compile-time error, it gives me a runtime error. I know I can throw an exception, I'd rather die during compilation than during runtime.
First-off, I am using eclipse 3.4.
I have a data model that has a mode property that is an Enum.
```
enum Mode {on(...), off(...), standby(...); ...}
```
I am currently writing a view of this model and I have the code
```
...
switch(model.getMode()) {
case on:
return getOnColor();
case off:
return getOffColor();
case standby:
return getStandbyColor();
}
...
```
I am getting an error "This method must return a result of type java.awt.Color" because I have no default case and no return xxx at the end of the function.
**I *want* a compilation error in the case where someone adds another type to the enum (e.g. shuttingdown) so I don't want to put a default case that throws an AssertionError, as this will compile with a modified Mode and not be seen as an error until runtime.**
My question is this:
Why does EclipseBuilder (and javac) not recognize that this switch covers all possibilities (or does it cover them?) and stop warning me about needing a return type. Is there a way I can do what I want without adding methods to Mode?
Failing that, is there an option to warn/error on switch statements that don't cover all of the Enum's possible values?
Edit:
Rob: It is a compile *error*. I just tried compiling it with javac and I get a "missing return statement" error targeting the last } of the method. Eclispe just places the error at the top of the method. | You could always use the Enum with Visitor pattern:
```
enum Mode {
on {
public <E> E accept( ModeVisitor<E> visitor ) {
return visitor.visitOn();
}
},
off {
public <E> E accept( ModeVisitor<E> visitor ) {
return visitor.visitOff();
}
},
standby {
public <E> E accept( ModeVisitor<E> visitor ) {
return visitor.visitStandby();
}
}
public abstract <E> E accept( ModeVisitor<E> visitor );
public interface ModeVisitor<E> {
E visitOn();
E visitOff();
E visitStandby();
}
}
```
Then you would implement something like the following:
```
public final class ModeColorVisitor implements ModeVisitor<Color> {
public Color visitOn() {
return getOnColor();
}
public Color visitOff() {
return getOffColor();
}
public Color visitStandby() {
return getStandbyColor();
}
}
```
You'd use it as follows:
```
return model.getMode().accept( new ModeColorVisitor() );
```
This is a lot more verbose but you'd immediately get a compile error if a new enum was declared. | You have to enable in Eclipse (window -> preferences) settings "Enum type constant not covered in switch" with Error level.
Throw an exception at the end of the method, but don't use default case.
```
public String method(Foo foo)
switch(foo) {
case x: return "x";
case y: return "y";
}
throw new IllegalArgumentException();
}
```
Now if someone adds new case later, Eclipse will make him know he's missing a case. So don't ever use default unless you have really good reasons to do so. | Java Enums and Switch Statements - the default case? | [
"",
"java",
"enums",
""
] |
I am trying to configure Log4Net purely by code, but when I did with a minimal configuration, I was flooded by logging messages from NHibernate and the fluent interface.
So, what I am trying to do is simple. Tell Log4Net to show me only log messages of my single class. I toyed around a little bit, but can't figure it out...
Can anyone help, I think the following code illustrates my idea:
```
var filter = new log4net.Filter.LoggerMatchFilter();
filter.LoggerToMatch = typeof(DatabaseDirectory).ToString();
filter.AcceptOnMatch = false;
var x = new log4net.Appender.ConsoleAppender();
x.Layout = new log4net.Layout.SimpleLayout();
x.AddFilter(filter);
log4net.Config.BasicConfigurator.Configure(x);
```
Ok, thanks for your help, but there must be some issue here. But I get closer. I tried the XML configuration, which has much more documentation. And I managed to achieve the desired result using the following XML configuration. There must be some misconfiguration in the "pure code" version above.
The following XML configuration provides the "correct" output, which is not the same than the config in code above. Anybody sees the difference?
```
<log4net>
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
</root>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
<filter type="log4net.Filter.LoggerMatchFilter">
<loggerToMatch value="Examples.FirstProject.Entities.DatabaseDirectory"/>
</filter>
<filter type="log4net.Filter.DenyAllFilter" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="[%C.%M] %-5p %m%n" />
</layout>
</appender>
``` | I figured it out.. Sometimes, just writing it down opens your eyes...
```
var filter = new log4net.Filter.LoggerMatchFilter();
filter.LoggerToMatch = typeof(DatabaseDirectory).ToString();
filter.AcceptOnMatch = true;
var filterDeny = new log4net.Filter.DenyAllFilter();
var x = new log4net.Appender.ConsoleAppender();
x.Layout = new log4net.Layout.SimpleLayout();
x.AddFilter(filter);
x.AddFilter(filterDeny);
log4net.Config.BasicConfigurator.Configure(x);
```
See what was missing :-) The denyALL filter!!
Some more code examples:
```
public static void AllToConsoleSetup()
{
var x = new log4net.Appender.ConsoleAppender { Layout = new log4net.Layout.SimpleLayout() };
log4net.Config.BasicConfigurator.Configure(x);
SetupDone = true;
}
public static void ShowOnlyLogOf(Type t)
{
var filter = new log4net.Filter.LoggerMatchFilter {LoggerToMatch = t.ToString(), AcceptOnMatch = true};
var filterDeny = new log4net.Filter.DenyAllFilter();
var x = new log4net.Appender.ConsoleAppender {Layout = new log4net.Layout.SimpleLayout()};
x.AddFilter(filter);
x.AddFilter(filterDeny);
log4net.Config.BasicConfigurator.Configure(x);
SetupDone = true;
}
```
Really UGLY but working (it screws up the highlighting, do not miss the last lines):
```
public static void DefaultSetup()
{
// AllToConsoleSetup();
XmlConfigurator.Configure(XmlSetup());
// DbConfig();
}
private static Stream XmlSetup()
{
const string x = @" <log4net>
<root>
<level value=""ALL"" />
<appender-ref ref=""AdoNetAppender"">
</appender-ref>
</root>
<appender name=""AdoNetAppender"" type=""log4net.Appender.AdoNetAppender"">
<bufferSize value=""1"" />
<connectionType value=""System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"" />
<connectionString value=""data source=Christian-PC\SQLEXPRESS;initial catalog=log4net_2;integrated security=false;persist security info=True;User ID=log4net;Password=XXXX"" />
<commandText value=""INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)"" />
<parameter>
<parameterName value=""@log_date"" />
<dbType value=""DateTime"" />
<layout type=""log4net.Layout.RawTimeStampLayout"" />
</parameter>
<parameter>
<parameterName value=""@thread"" />
<dbType value=""String"" />
<size value=""655"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%thread"" />
</layout>
</parameter>
<parameter>
<parameterName value=""@log_level"" />
<dbType value=""String"" />
<size value=""50"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%level"" />
</layout>
</parameter>
<parameter>
<parameterName value=""@logger"" />
<dbType value=""String"" />
<size value=""655"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%logger"" />
</layout>
</parameter>
<parameter>
<parameterName value=""@message"" />
<dbType value=""String"" />
<size value=""4000"" />
<layout type=""log4net.Layout.PatternLayout"">
<conversionPattern value=""%message"" />
</layout>
</parameter>
<parameter>
<parameterName value=""@exception"" />
<dbType value=""String"" />
<size value=""2000"" />
<layout type=""log4net.Layout.ExceptionLayout"" />
</parameter>
<filter type=""log4net.Filter.LoggerMatchFilter"">
<param name=""LoggerToMatch"" value=""Ruppert"" />
</filter>
<filter type=""log4net.Filter.DenyAllFilter"">
</filter>
</appender>
</log4net>";
return new MemoryStream(ASCIIEncoding.Default.GetBytes(x));
}
``` | Here is anohter way to configure log4net with XML via code using XmlDocument to load the xml. The difference from Christian's example is that I am using the `XmlConfigurator.Configure` overload that takes an `XmlElement` as a parameter. I also used single tick marks rather than doubling up the double quotation marks. All in all, I think that it is the tiniest bit cleaner.
```
string xml =
@"<log4net>
<appender name='file1' type='log4net.Appender.RollingFileAppender'>
<!-- Log file locaation -->
<param name='File' value='log4net.log'/>
<param name='AppendToFile' value='true'/>
<!-- Maximum size of a log file -->
<maximumFileSize value='2KB'/>
<!--Maximum number of log file -->
<maxSizeRollBackups value='8'/>
<!--Set rolling style of log file -->
<param name='RollingStyle' value='Composite'/>
<param name='StaticLogFileName' value='false'/>
<param name='DatePattern' value='.yyyy-MM-dd.lo\g'/>
<layout type='log4net.Layout.PatternLayout'>
<param name='ConversionPattern' value='%d [%t] %-5p %m%n'/>
</layout>
</appender>
<!-- Appender layout fix to view in console-->
<appender name='console' type='log4net.Appender.ConsoleAppender'>
<layout type='log4net.Layout.PatternLayout'>
<param name='Header' value='[Header]\r\n'/>
<param name='Footer' value='[Footer]\r\n'/>
<param name='ConversionPattern' value='%d [%t] %-5p %m%n'/>
</layout>
</appender>
<appender name='debug' type='log4net.Appender.DebugAppender'>
<layout type='log4net.Layout.PatternLayout'>
<param name='ConversionPattern' value='%d [%t] %logger %-5p %m%n'/>
</layout>
</appender>
<root>
<level value='INFO'/>
<!--
Log level priority in descending order:
FATAL = 1 show log -> FATAL
ERROR = 2 show log -> FATAL ERROR
WARN = 3 show log -> FATAL ERROR WARN
INFO = 4 show log -> FATAL ERROR WARN INFO
DEBUG = 5 show log -> FATAL ERROR WARN INFO DEBUG
-->
<!-- To write log in file -->
<appender-ref ref='debug'/>
<appender-ref ref='file1'/>
</root>
</log4net>";
//
// Use XmlDocument to load the xml string then pass the DocumentElement to
// XmlConfigurator.Configure.
//
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
log4net.Config.XmlConfigurator.Configure(doc.DocumentElement);
``` | log4net pure code configuration with filter in c# | [
"",
"c#",
"configuration",
"log4net",
""
] |
I am using `String.Format("{0:C2}", -1234)` to format numbers.
It always formats the amount to a positive number, while I want it to become $ **-** 1234 | I think I will simply use:
```
FormatCurrency(-1234.56, 2, UseParensForNegativeNumbers:=TriState.False)
```
(in Microsoft.VisualBasic.Strings module)
Or in shorter words (this is what im actually going to use):
```
FormatCurrency(-1234.56, 2, 0, 0)
```
Or I will make myself a custom formatcurrency function that uses the VB function passing my custom params.
For further details take a look at the [FormatCurrency Function (Visual Basic)](http://msdn.microsoft.com/en-us/library/3352e6f5(VS.80).aspx) in the msdn. | Am I right in saying it's putting it in brackets, i.e. it's formatting it as `($1,234.00)` ? If so, I believe that's the intended behaviour for the US.
However, you can create your own `NumberFormatInfo` which doesn't behave this way. Take an existing `NumberFormatInfo` which is "mostly right", call `Clone()` to make a mutable copy, and then set the [`CurrencyNegativePattern`](http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern.aspx) appropriately (I think you want value 2).
For example:
```
using System;
using System.Globalization;
class Test
{
static void Main()
{
var usCulture = CultureInfo.CreateSpecificCulture("en-US");
var clonedNumbers = (NumberFormatInfo) usCulture.NumberFormat.Clone();
clonedNumbers.CurrencyNegativePattern = 2;
string formatted = string.Format(clonedNumbers, "{0:C2}", -1234);
Console.WriteLine(formatted);
}
}
```
This prints $-1,234.00. If you actually want exactly $-1234, you'll need to set the [`CurrencyGroupSizes`](http://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencygroupsizes.aspx) property to `new int[]{0}` and use `"{0:C0}"` instead of `"{0:C2}"` as the format string.
EDIT: Here's a helper method you can use which basically does the same thing:
```
private static readonly NumberFormatInfo CurrencyFormat = CreateCurrencyFormat();
private static NumberFormatInfo CreateCurrencyFormat()
{
var usCulture = CultureInfo.CreateSpecificCulture("en-US");
var clonedNumbers = (NumberFormatInfo) usCulture.NumberFormat.Clone();
clonedNumbers.CurrencyNegativePattern = 2;
return clonedNumbers;
}
public static string FormatCurrency(decimal value)
{
return value.ToString("C2", CurrencyFormat);
}
``` | String.Format("{0:C2}", -1234) (Currency format) treats negative numbers as positive | [
"",
"c#",
"vb.net",
"string-formatting",
"currency",
"string.format",
""
] |
I'm trying to change my PYTHONPATH. I've tried to change it in "My Computer" etc, but it doesn't exist there. I searched in the registry in some places, and even ran a whole search for the word 'PYTHONPATH', but to no avail.
However, it Python I can easily see it exists. So where is it? | Python does some stuff up front when it is started, probably also setting that path in windows. Just set it and see, if it is changed in `sys.path`.
[Setting environment variables](http://docs.python.org/using/windows.html#excursus-setting-environment-variables) in the Python docs say:
```
My Computer ‣ Properties ‣ Advanced ‣ Environment Variables
``` | At runtime, you can change it with:
```
import sys
sys.path.append('...')
```
In My Computer, right-click Properties (or press Win-Break), System tab, Environment Variables, System. You can add it if it's not already there.
Finally, in the CMD prompt:
```
set PYTHONPATH C:\Python25\Lib;C:\MyPythonLib
```
Or in `bash`:
```
PYTHONPATH=/usr/share/python/lib:/home/me/python
export PYTHONPATH
```
Or, more succinctly:
```
export PYTHONPATH=/home/me/python
``` | Can't find my PYTHONPATH | [
"",
"python",
"windows",
"path",
""
] |
I'm maintaining some C# 2.0 code, and the programmer uses a pattern of reading a collection of business objects by opening a DataReader and then passing it to the object's constructor. I can't see anything obviously wrong with this, but it feels bad to me. Is this OK to do?
```
private static void GetObjects()
{
List<MyObject> objects = new List<MyObject>();
string sql = "Select ...";
SqlConnection connection = GetConnection();
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
objects.Add(new MyObject(reader));
reader.Close();
}
public MyObject(SqlDataReader reader)
{
field0 = reader.GetString(0);
field1 = reader.GetString(1);
field2 = reader.GetString(2);
}
``` | By passing the DataReader to the object's constructor, you establish a very tight coupling between the business object and your choice of persistence technology.
At the very least, this tight coupling will make reuse and testing difficult; at worst, it could result in the business objects knowing far too much about the database.
Resolving this isn't too difficult - you'd simply move object initialization out of the constructor and into a distinct factory class. | Passing a reader around makes me cringe, unless it's a non-public helper method to deal with copying one row. Definitely not to a constructor though.
Passing a reader connects your constructor (you didn't put MyObject in a class but you call `new MyObject()`) to your data storage and I presume your object isn't written to be such?
If it were me:
```
private static void GetObjects()
{
List<MyObject> objects = new List<MyObject>();
string sql = "Select ...";
using (SqlConnection connection = GetConnection())
{
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
using(SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection);)
{
while (reader.Read())
objects.Add(_ReadRow(reader));
}
}
}
private static MyObject _ReadRow(SqlDataReader reader)
{
MyObject o = new MyObject();
o.field0 = reader.GetString(0);
o.field1 = reader.GetString(1);
o.field2 = reader.GetString(2);
// Do other manipulation to object before returning
return o;
}
class MyObject{}
``` | Is it OK to pass DataReaders to constructors? | [
"",
"c#",
"constructor",
"sqldatareader",
""
] |
Suppose I am developing an application for a product distributor in C#.
The distributor does the following 3 types of transactions:
(1) Indent
(2) Sell
(3) Stock
I am designing my classes as follows:
```
public abstract class Transaction
{
}
public class Indent : Transaction
{
}
public class Sell : Transaction
{
}
public class Stock : Transaction
{
}
```
Now if I want to save these three types of information in three separate tables then how should I design my DA layer?
Should I build separate DA classes like
```
(1) IndentDA
(2) SellDA
(3) StockDA
```
or a single class `TransactionDA` and perform CRUD operations by checking their types by using `as/is` operators?
Or what else can I do? Any suggestions? | Firstly, if you created a single class TransactionDA and checked types inside the class to perform CRUD operations, you would be violating the [Open/Closed Principle](http://en.wikipedia.org/wiki/Open/closed_principle), so I would definitely not go down that path.
As for suggestions on how to accomplish building out your DAL, I would suggest following some blog posts on people much smarter than I on what they think about this topic.
[Repository is the new Singleton](http://ayende.com/Blog/archive/2009/04/17/repository-is-the-new-singleton.aspx)
[Repository is Dead: Long Live Repository](http://codebetter.com/blogs/gregyoung/archive/2009/04/23/repository-is-dead-long-live-repository.aspx)
[Night of the Living Repositories](http://ayende.com/Blog/archive/2009/04/23/night-of-the-living-repositories.aspx)
The conversation continues, I believe, but that should get you started. | I would use entity subtypes here. Create one table for the transactions (and as an earlier poster said, perhaps a different term would be better) and store everything that's common in there. Then create one "sub-type" table for each specialization. These subtype tables should have the same primary key as the main table (the "strong" entity) and the fields that are unique to that particular specialization. Each subtype is related to the strong entity in a one-to-one manner, with optional participation on the subtype end and required participation on the strong entity end.
Then, to make querying easier, define a view that (outer) joins the strong entity with all of the entity subtypes so that you can easily "see" everything.
Here's a simple (and common) example of how to set this up:
```
create table Employee (
eid int primary key,
first_name text,
last_name text not null
)
create table Salaried (
eid int primary key,
annualSalaryUSD money not null
)
create table Hourly (
eid int primary key,
hourlyRateUSD money not null
)
``` | OO Design vs Database Design | [
"",
"c#",
"oop",
"n-tier-architecture",
""
] |
I am using the DOMPDF library to create an invoice in PDF. This document can be in French, Russian or English, but I am having trouble printing Russian characters.
First, I tried to use UTF-8 encoding and placed the `meta` tag in the head of the HTML page to be converted:
> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
But that didn't work.
Then I inserted this `meta` tag inside the `BODY` tag, and it helped solve the problem with French characters.
But Russian characters still don't work. I have also tried to convert Russian characters into HTML entities, but that too does not work.
I use R&OS CPDF class, not PDFLib as a backend.
Can anyone help? | Problem is with fonts default dompdf uses (that is it doesn't have all unicode characters, whick are by now over 5000). Usually arialuni.ttf is what you need. You can download localized russian version at <http://chernev.ru/dompdf.rar> {broken link}
Updated link: <https://code.google.com/p/ipwn/downloads/detail?name=arialuni.ttf> | if you will use DejaVu font you can see cyrillic characters
> The DejaVu TrueType fonts have been pre-installed to give dompdf decent Unicode character coverage by default. To use the DejaVu fonts reference the font in your stylesheet, e.g. body { font-family: DejaVu Sans; } (for DejaVu Sans).
DOMPDF include DejaVu font be default
```
$html = "<html><head><style>body { font-family: DejaVu Sans }</style>".
"<body>А вот и кириллица</body>".
"</head></html>";
$dompdf = new \DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
echo file_put_contents('cyrillic.pdf', $dompdf->output());
```
You can also set change **def** for font by default in **dompdf\_config.inc.php**
```
def("DOMPDF_DEFAULT_FONT", "DejaVu Sans");
``` | DOMPDF problem with Cyrillic characters | [
"",
"php",
"pdf",
"pdf-generation",
"dompdf",
""
] |
I have a 3rd party JAR file that is compiled using Java 1.4. Is there a tool that can make the jar file compatible with Java 1.6? (Something like 'retrotranslator' but what does the reverse of it).
I tried decompiling the class files and re compile them in 1.6 but it fails.
---
Here is the issue:
My project uses 'rsadapter.jar' for was 5.1 and I had my project setup in Eclipse 2.0 + JDK 1.4 and it used to work fine. Now, I have migrated to Java 1.6 and Eclipse Ganymede (as per the requirements) and the same project (exactly same setup) started complaining about the missing class files in the 'rsadapter.jar'. I put the JAR in classpath explicitly too but it still could not load the classes. Then I changed the Java Compiler version to 1.4 and it started working.
Regards,
- Ashish | Classes compiled by JDK 1.4 should be usable in a Java 6 runtime as-is. If you have actually encountered a problem, please describe it.
---
*Update:* I can only reproduce this with types in the "default" package (that is, not in a package). Are the classes you are trying to use in the default package? Also, this happens to me regardless of the JDK version used to compile.
---
*Update:* Okay, after a little research, I realized that you can never reference a type in the unnamed package from a named package. Makes sense, but definitely not what you are running into.
I can compile code under JDK 1.4.2\_19 and utilize it just fine in a Java 6 Eclipse project. I think that this problem is something specific to your environment. In this situation, I would backup Eclipse and recreate everything (JDK installation, workspace, projects) from scratch, to see if I could clear it up. | I had another issue with some legacy code written in Java 1.4.x: the authors loved enumerations and loved to name the corresponding variables 'enum'. They even used it for package names. And this prevents from compiling the code under Java 1.5 (or higher) quite successfully.
Changing **that** automatically is quite an issue. | Java : Is there a tool to make code (in a 3rd party JAR) forward compatible (1.4 - 1.6) | [
"",
"java",
"decompiling",
""
] |
How can I determine the address in memory of the Java heap for a JVM running in the current process? That is, get a void\* pointer or equivalent to the contiguous area of memory that the JVM has allocated for the heap, using Java, C, or other calls?
Matlab has a JVM embedded in its process. The memory the JVM allocates is unavailable for Matlab arrays, and of this, the heap is important, because it takes a big contiguous chunk of memory and never shrinks, and Matlab also needs contiguous memory for its arrays. If the heap is reallocated during expansion, that could cause fragmentation.
I'd like to instrument my process to examine the interaction between the Java heap and Matlab's view of memory, and to find out when it moves due to resizing, preferably all from within the process. This needs the address of the heap. It's easy to find the heap size from java.lang.Runtime, but not its address in memory. How can this be done?
I'm running Sun's JRE 1.6.0\_04 in a Matlab R2008b process on Windows XP and Server 2003. I realize this probably needs to be a vendor-specific technique. The process runs code we've written, so we can use custom Java, Matlab, JNI, and C/C++ code. Java method calls or supported hooks in the JVM would be preferred to low-level hackery.
EDIT: The goal of this is to examine the interaction between the JVM's GC and Matlab's GC. I have no need to see into the Java heap and won't be reading anything from that memory; I just want to see where it is in the context of the overall virtual memory space that Matlab's GC is also trying to fit data into. | A quick 'n dirty way to get the actual heap address of the JVM is to jump into WinDbg, attaching to the JVM and issue a single !address command. Somewhere around 0x2??????? (It differes between jvm versions but remains static for that version) will be a large VAD marked PAGE\_EXECUTE\_READWRITE, this is your JVM's heap in the process's memory.
To confirm, you can set a breakpoint on kernel32!VirtualAlloc and upon JVM initilization in the module JVM.DLL you will hit on the call to VirtualAlloc showing you the jvm allocation its heap. If you check out the code around this call you can see how the address is calculated. | Stepping back a bit... Could you go with a fixed-size Java heap? At that point concerns about reallocation and fragmentation go away.
On a stand-alone Java invocation, that involve specifying something like -Xmx500m and -Xms500m for a 500Mb heap. You'd have to translate that into what matlab wants. | How to get the memory address of the Java heap? | [
"",
"java",
"matlab",
""
] |
I want to make a simple news system using PHP and MySQL, right now I got a working post and read system but there is only one problem, I want it to show the 10 latest news but instead it shows the 10 oldest news.
My question is: Is there a way to make MySQL return the results from the bottom of a table or do I have to first get the number of posts and then limit it to the very last 10 ones?
Here is the insert (title and text is escaped and time is time(), poster is not done yet):
```
mysql_query("INSERT INTO news (title, poster, text, time) VALUES ('$newstitle', '1', '$newstext', '$time')") or die(mysql_error());
```
And to retrive it (addnews echos it):
```
$myqr = mysql_query('SELECT * FROM news LIMIT 10') or die("Error running news query: ". mysql_error());
while($myres = mysql_fetch_array($myqr))
{
addnews($myres['id'], $myres['title'], "admin", date('l jS F Y - H:i:s', $myres['time']), $myres['text']);
}
```
So, short: I want to read the database backwards, is it possible? | Check out the [ORDER BY](http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html) clause. It allows you to sort rows by a column in ascending or descending order. The following query will return 10 news items, sorted by time in descending order.
```
SELECT * FROM news ORDER BY time DESC LIMIT 10
``` | Simple, just add an "ORDER BY" clause to your SQL, e.g.
```
SELECT * FROM news ORDER BY time DESC LIMIT 10
``` | Making MySQL return the table backwards | [
"",
"php",
"mysql",
""
] |
I want to show a modal popup when a user click on an asp button. The user must select an option of a panel. The value of the option selected must be saved to an input hidden and then the asp.net button **must do** a **PostBack**.
Can I do that?
Thank you! | Finally, I've decided to use jQuery to show a ModalPopUp. The following question has the answer to this question:
[jQuery UI's Dialog doesn't work on ASP.NET](https://stackoverflow.com/questions/2325431/jquery-uis-dialog-doesnt-work-on-asp-net)
If you are not agree, tell me. | It is possible for a ModalPopupExtender to be displayed using a postback. You'll need an invisible target control. The extender is attached to this hidden control.
```
<asp:Button runat="server" ID="btnShowModal" Text="Show"
OnClick="btnShowModal_Click" />
<asp:Button runat="server" ID="HiddenForModal" style="display: none" />
<ajaxToolKit:ModalPopupExtender ID="Modal1" runat="server"
TargetControlID="HiddenForModal" PopupControlID="PopupPanel" />
```
In your message handler in code-behind, you'll show the ModalPopupExtender:
```
Modal1.Show();
```
And in the code you're using to dismiss the Modal, call the ModalPopupExtender's Hide function:
```
Modal1.Hide();
```
I use this method for showing a modal that displays detailed data that I retrieve from a database based on what's selected in a GridView. | ASP.NET AJAX Control Toolkit: Show a ModalPopup and then do PostBack | [
"",
"c#",
"asp.net-ajax",
"ajaxcontroltoolkit",
"modal-popup",
""
] |
Does someone know.. how to read files to STDIN in Netbeans.
I have a Problem my Program in Netbeans. The Program works like this :
```
./myprog < in.txt
```
It's a C++ Project.
Any Ideas ?
Edit : I have Proglems with setting up netbeans . where can i say : READ/USE THIS FILE ?
On the Console it just works fine ! | I don't believe there's a way to ask NetBeans to pipe input to your program (that functionality is handled by your shell). If you want to test or debug your program in the IDE, the best way is to allow it to take a filename as a parameter, or fall back on standard input if no filename is given. Then you can adjust your project run configuration and supply the test filename as an argument.
Note that if you try to use "< file" in the run configuration, that will simply be passed directly to your program, because there is no shell intercepting it.
[Edit] I found a way, though it's a bit weak.
NetBeans (at least on my Mac) runs C++ programs via a script called dorun.sh, which is under the .netbeans folder in my home directory. It includes a line near the end like this:
"$pgm" "$@"
The quotes escape any use of the < operator in your project properties, so you could remove the quotes (and accept the consequences), or include a < between them:
"$pgm" < "$@"
and simply include the filename as an argument.
If you don't know where to find the arguments, it's in the project properties, off the file menu.
If you're using NetBeans on Windows, I'm not sure what kind of script (if any) it uses to launch your program. Also note that this doesn't work if you use the output window instead of an external terminal (this setting is in the same window).
[Edit edit] This is also no good when trying to debug your program... probably best just to amend your code to deal with reading from either a file or stdin. | I agree with JimG regarding the best way to handle this (via filename as parameter, falling back on stdin if none). You can also pass a flag to your code via a make flag and conditionally use freopen in your code, like this:
```
#ifdef NETBEANS
freopen("input.txt", "r", stdin);
#endif
```
Then in Project Properties -> Build -> Make -> Build command, you could do something like:
```
${MAKE} -f Makefile "DEBUG_FLAGS=-DNETBEANS"
```
Your Makefile would obviously have to be passing along DEBUG\_FLAGS, something like this:
```
.cpp.o: $<
$(CC) $(DEBUG_FLAGS) $(CFLAGS) $(INCLUDES) -o $@ $<
```
I use this method since I always use the same recycled make file inside and outside netbeans, and it's a 3 line fix in the code itself. I suppose parsing the cmdline is all in one spot, but to each his own. | STDIN in Netbeans | [
"",
"c++",
"netbeans",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.