Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
GUIs, whether written in WinForms or XAML, seem to have the most widely differing naming conventions between projects I see. For a simple `TextBox` for a person's name, I've seen various naming conventions:
```
TextBox tbName // Hungarian notation
TextBox txtName // Alternative Hungarian
TextBox NameTextBox // Not even camelCase
TextBox nameTextBox // Field after field with TextBox on the end
TextBox TextBoxName // Suggested in an answer...
TextBox textBoxName // Suggested in an answer...
TextBox uxName // Suggested in an answer...
TextBox name // Deceptive since you need name.Text to get the real value
TextBox textBox1 // Default name, as bad as you can get
```
I abide by the StyleCop rules for all my .cs files normally, and see others do so as well, but the GUI tends to break these rules or vary wildly. I haven't seen any Microsoft guidelines that specifically refer to GUI elements instead of just normal variables, or even examples that would apply outside of a console application.
**What are the best practices for naming elements in a GUI?** | I use the old school hungarian... txt for TextBox, btn for Button, followed by a generalized word, then a more specific word. i.e.:
```
btnUserEmail
```
Have had a lot of people say things like **"omg thats so old, VB6 calling!"** But in a UI Rich winforms app, I can find and modify things quicker because usually the first thing you know about a control is it's type, then it's category, then get specific. While the newer style naming convention guys are stuck trying to remember what they named that text box.
[The original specification for controls is here (archived).](https://jeffpar.github.io/kbarchive/kb/173/Q173738/) | I use:
```
TextBox nameTextBox;
```
Just like I would use:
```
MailAddress homeAddress;
```
The reason for this is that in these cases "TextBox" and "Address" is descriptive of what the object represents, not how it is stored or used. But in another case like storing a person's full name I would use:
```
string fullName;
```
Not:
```
string fullNameString;
```
Because "String" is not descriptive of what the object represents, but only how it is stored. | Best practices for C# GUI naming conventions? | [
"",
"c#",
"winforms",
"user-interface",
"naming-conventions",
""
] |
I am trying to parse a heavily namespaced SOAP message (source can be found also [here](http://tinyurl.com/n3av6k)):
```
<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Header>
<ns1:TransactionID soapenv:mustUnderstand="1" xsi:type="xsd:string" xmlns:ns1="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-5-MM7-1-2">0a00f556419041c08d8479fbaad02a3c</ns1:TransactionID>
</soapenv:Header>
<soapenv:Body>
<SubmitRsp xmlns="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-5-MM7-1-2">
<MM7Version>5.3.0</MM7Version>
<Status>
<StatusCode xsi:type="ns2:responseStatusType_StatusCode" xmlns:ns2="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-5-MM7-1-2" xmlns="">1000</StatusCode>
<StatusText xsi:type="ns3:statusTextType" xmlns:ns3="http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-5-MM7-1-2" xmlns="">Success</StatusText>
</Status>
<MessageID>B08CF7B847DAD89C752334BDEBB69B5B</MessageID>
</SubmitRsp>
</soapenv:Body>
</soapenv:Envelope>
```
Just for the context, this is a response of *MM7 Submit* message.
How can I get the following values:
TransactionID, StatusCode, StatusText, MessageID
I tried Linq-Xml but no luck when the query includes a value like "soapenv:Body". | If you're trying to build an `XName` with a namespace you need to build it from an `XNamespace` plus a string, e.g.
```
XNamespace soapenv = "http://schemas.xmlsoap.org/soap/envelope/";
XName body = soapenv + "Body";
```
Then when you use the `XName` "`body`" with Linq-to-XML it will match the `<soapenv:Body>` element in your document.
You can do similar things to allow building the names of other elements with namespaces. | There's an even simpler way. You can simply specify the namespace inline using {} notation:
```
var soap = XElement.Load(soapPath);
var transactionID =
from e in soap.Descendants("{http://www.3gpp.org/ftp/Specs/archive/23_series/23.140/schema/REL-5-MM7-1-2}TransactionID")
select e.Value;
``` | Parse and query SOAP in C# | [
"",
"c#",
"parsing",
"soap",
"xml-namespaces",
"mm7",
""
] |
Here is the code that will help you understand my question:
```
create table con ( content_id number);
create table mat ( material_id number, content_id number, resolution number, file_location varchar2(50));
create table con_groups (content_group_id number, content_id number);
insert into con values (99);
insert into mat values (1, 99, 7, 'C:\foo.jpg');
insert into mat values (2, 99, 2, '\\server\xyz.mov');
insert into mat values (3, 99, 5, '\\server2\xyz.wav');
insert into con values (100);
insert into mat values (4, 100, 5, 'C:\bar.png');
insert into mat values (5, 100, 3, '\\server\xyz.mov');
insert into mat values (6, 100, 7, '\\server2\xyz.wav');
insert into con_groups values (10, 99);
insert into con_groups values (10, 100);
commit;
SELECT m.material_id,
(SELECT file_location
FROM (SELECT file_location
FROM mat
WHERE mat.content_id = m.content_id
ORDER BY resolution DESC) special_mats_for_this_content
WHERE rownum = 1) special_mat_file_location
FROM mat m
WHERE m.material_id IN (select material_id
from mat
inner join con on con.content_id = mat.content_id
inner join con_groups on con_groups.content_id = con.content_id
where con_groups.content_group_id = 10);
```
Please consider the number 10 at the end of the query to be a parameter. In other words this value is just hardcoded in this example; it would change depending on the input.
My question is: Why do I get the error
```
"M"."CONTENT_ID": invalid identifier
```
for the nested, correlated subquery? Is there some sort of nesting limit? This subquery needs to be ran for every row in the resultset because the results will change based on the content\_id, which can be different for each row. How can I accomplish this with Oracle?
Not that I'm trying to start a SQL Server vs Oracle discussion, but I come from a SQL Server background and I'd like to point out that the following, equivalent query runs fine on SQL Server:
```
create table con ( content_id int);
create table mat ( material_id int, content_id int, resolution int, file_location varchar(50));
create table con_groups (content_group_id int, content_id int);
insert into con values (99);
insert into mat values (1, 99, 7, 'C:\foo.jpg');
insert into mat values (2, 99, 2, '\\server\xyz.mov');
insert into mat values (3, 99, 5, '\\server2\xyz.wav');
insert into con values (100);
insert into mat values (4, 100, 5, 'C:\bar.png');
insert into mat values (5, 100, 3, '\\server\xyz.mov');
insert into mat values (6, 100, 7, '\\server2\xyz.wav');
insert into con_groups values (10, 99);
insert into con_groups values (10, 100);
SELECT m.material_id,
(SELECT file_location
FROM (SELECT TOP 1 file_location
FROM mat
WHERE mat.content_id = m.content_id
ORDER BY resolution DESC) special_mats_for_this_content
) special_mat_file_location
FROM mat m
WHERE m.material_id IN (select material_id
from mat
inner join con on con.content_id = mat.content_id
inner join con_groups on con_groups.content_id = con.content_id
where con_groups.content_group_id = 10);
```
Can you please help me understand why I can do this in SQL Server but not Oracle 9i? If there is a nesting limit, how can I accomplish this in a single select query in Oracle without resorting to looping and/or temporary tables? | Recent versions of Oracle do not have a limit but most older versions of Oracle have a nesting limit of `1` level deep.
This works on all versions:
```
SELECT (
SELECT *
FROM dual dn
WHERE dn.dummy = do.dummy
)
FROM dual do
```
This query works in 12c and 18c but does not work in 10g and 11g. (However, there is at least one version of 10g that allowed this query. And there is a patch to enable this behavior in 11g.)
```
SELECT (
SELECT *
FROM (
SELECT *
FROM dual dn
WHERE dn.dummy = do.dummy
)
WHERE rownum = 1
)
FROM dual do
```
If necessary you can workaround this limitation with window functions (which you can use in `SQL Server` too:)
```
SELECT *
FROM (
SELECT m.material_id, ROW_NUMBER() OVER (PARTITION BY content_id ORDER BY resolution DESC) AS rn
FROM mat m
WHERE m.material_id IN
(
SELECT con.content_id
FROM con_groups
JOIN con
ON con.content_id = con_groups.content_id
WHERE con_groups.content_group_id = 10
)
)
WHERE rn = 1
``` | [@Quassnoi](https://stackoverflow.com/users/55159/quassnoi) This was the case in oracle 9. From Oracle 10 ...
> From [Oracle Database SQL Reference 10g Release 1 (10.1)](http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10759/queries007.htm#sthref2296)
> Oracle performs a correlated subquery when a nested subquery references a column from a table referred to a parent statement **any number of levels** above the subquery
>
> From [Oracle9i SQL Reference Release 2 (9.2)](http://download-west.oracle.com/docs/cd/B14117_01/server.101/b10759/queries007.htm#sthref2296)
> Oracle performs a correlated subquery when the subquery references a column from a table referred to in the **parent** statement.
>
> A subquery in the **WHERE** clause of a SELECT statement is also called a nested subquery. You can nest up to 255 levels of subqueries in the a nested subquery.
I don't think it works if you have something like **select \* from (select \* from ( select \* from ( ....))))**
Just **select \* from TableName alias where colName = (select \* from SomeTable where someCol = (select \* from SomeTable x where x.id = alias.col))**
Check out <http://forums.oracle.com/forums/thread.jspa?threadID=378604> | Is there a nesting limit for correlated subqueries in some versions of Oracle? | [
"",
"sql",
"oracle",
""
] |
A **user** can have **suspensions**. I want to select a **user** and his **suspensions**, but I only want the suspensions where the **suspensions.suspended\_date > now()**. I want to return the user regardless.
It sounds like a left join, but:
```
SELECT *
FROM users
LEFT JOIN suspensions ON suspensions.user_id=users.id
WHERE suspensions.suspended_date > now()
```
Would work fine if they DO have suspensions, but would cause trouble if they don't have any, because the where clause would always fail.
How can I write this with one query? | you could try moving the filter from the WHERE to the JOIN statement
```
SELECT *
FROM users
LEFT JOIN suspensions
ON suspensions.user_id=users.id AND suspensions.suspended_date > now()
``` | ```
SELECT *
FROM users
LEFT JOIN suspensions ON suspensions.user_id=users.id
WHERE suspensions.suspended_date > now() or suspensions.suspended_date is null
```
That should do it. | How to do this kind of query? | [
"",
"sql",
""
] |
I've been looking boost::tokenizer, and I've found that the documentation is very thin. Is it possible to make it tokenize a string such as "dolphin--monkey--baboon" and make every word a token, as well as every double dash a token? From the examples I've only seen single character delimiters being allowed. Is the library not advanced enough for more complicated delimiters? | It looks like you will need to write your own [TokenizerFunction](http://www.boost.org/doc/libs/1_39_0/libs/tokenizer/tokenizerfunction.htm) to do what you want. | using iter\_split allows you to use multiple character tokens.
The code below would produce the following:
dolphin
mon-key
baboon
```
#include <iostream>
#include <boost/foreach.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/iter_find.hpp>
// code starts here
std::string s = "dolphin--mon-key--baboon";
std::list<std::string> stringList;
boost::iter_split(stringList, s, boost::first_finder("--"));
BOOST_FOREACH(std::string token, stringList)
{
std::cout << token << '\n'; ;
}
``` | Using boost::tokenizer with string delimiters | [
"",
"c++",
"string",
"boost",
"tokenize",
""
] |
In a PHP file when I need to redirect a user and headers are already sent so I can not use php's header function, in this case which is the best method to redirect a user?
Fastest and most reliable method regardless of the users browser brand?
```
echo '<script type="text/javascript">window.top.location="http://localhost/";</script>';
// OR
echo '<meta http-equiv="refresh" content="0;url=' .$location. '">';
```
**UPDATE**
Here is my end result code I am using now, if headers are already sent where I cannot redirect to the homepage, I just bring the homepage to me, so instead of including the body page, it will include my homepage and footer
```
function validlogin($url) {
if (!isset($_SESSION['auto_id']) || ($_SESSION['auto_id']=='')) {
$_SESSION['sess_login_msg'] = 'Please login';
$_SESSION['backurl'] = $url;
$temp = '';
if (headers_sent() === false){
header("Location: /");
exit();
}else{
//header is already sent so we will just bring the homepage to us instead of going to it!!!
include 'mainbody.inc.php';
include 'footer.inc.php';
exit();
}
}
}
``` | ```
function Redirect($url, $permanent = false)
{
if (headers_sent() === false)
{
header('Location: ' . $url, true, ($permanent === true) ? 301 : 302);
}
exit();
}
Redirect('http://www.google.com/', false);
```
Again, use ob\_start(); | Don't use any of these! You should always use HTTP redirects.
Use `ob_start()` to buffer content and avoid problem of headers already sent.
You might also try to write MVC application, where you would know whether you need to redirect before outputting anything (but with `ob_start()` that is not necessary). | Best redirect methods? | [
"",
"php",
"redirect",
"header",
""
] |
In the context of a DNN module, what's a good generic way to find out what the URL to the login functionality is? | Here is a utility method that gets the login URL:
C#
```
/// <summary>
/// Gets the login URL for the given portal from the current <paramref name="request"/>.
/// </summary>
/// <param name="portalSettings">The portal settings.</param>
/// <param name="request">The request.</param>
/// <returns>The URL for the login page</returns>
/// <exception cref="ArgumentNullException">if <paramref name="portalSettings"/> or <paramref name="request"/> is null.</exception>
public static string GetLoginUrl(PortalSettings portalSettings, HttpRequest request)
{
if (portalSettings != null && request != null)
{
int tabId = portalSettings.ActiveTab.TabID;
string controlKey = "Login";
string returnUrl = request.RawUrl;
if (returnUrl.IndexOf("?returnurl=", StringComparison.OrdinalIgnoreCase) > -1)
{
returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=", StringComparison.OrdinalIgnoreCase));
}
returnUrl = HttpUtility.UrlEncode(returnUrl);
if (!Null.IsNull(portalSettings.LoginTabId) && string.IsNullOrEmpty(request.QueryString["override"]))
{
// user defined tab
controlKey = string.Empty;
tabId = portalSettings.LoginTabId;
}
else if (!Null.IsNull(portalSettings.HomeTabId))
{
// portal tab
tabId = portalSettings.HomeTabId;
}
// else current tab
return Globals.NavigateURL(tabId, controlKey, new string[] { "returnUrl=" + returnUrl });
}
throw new ArgumentNullException(portalSettings == null ? "portalSettings" : "request");
}
```
VB.NET
```
''' <summary>
''' Gets the login URL for the given portal from the current <paramref name="request"/>.
''' </summary>
''' <param name="portalSettings">The portal settings.</param>
''' <param name="request">The request.</param>
''' <returns>The URL for the login page</returns>
''' <exception cref="ArgumentNullException">if <paramref name="portalSettings"/> or <paramref name="request"/> is null.</exception>
Public Shared Function GetLoginUrl(portalSettings As PortalSettings, request As HttpRequest) As String
If portalSettings <> Nothing AndAlso request <> Nothing Then
Dim tabId As Integer = portalSettings.ActiveTab.TabID
Dim controlKey As String = "Login"
Dim returnUrl As String = request.RawUrl
If returnUrl.IndexOf("?returnurl=", StringComparison.OrdinalIgnoreCase) > -1 Then
returnUrl = returnUrl.Substring(0, returnUrl.IndexOf("?returnurl=", StringComparison.OrdinalIgnoreCase))
End If
returnUrl = HttpUtility.UrlEncode(returnUrl)
If Not Null.IsNull(portalSettings.LoginTabId) AndAlso String.IsNullOrEmpty(request.QueryString("override")) Then
' user defined tab
controlKey = String.Empty
tabId = portalSettings.LoginTabId
ElseIf Not Null.IsNull(portalSettings.HomeTabId) Then
' portal tab
tabId = portalSettings.HomeTabId
End If
' else current tab
Return Globals.NavigateURL(tabId, controlKey, New String() {"returnUrl=" + returnUrl})
End If
Throw New ArgumentNullException(If(portalSettings = Nothing, "portalSettings", "request"))
End Function
``` | Globals.LoginURL
```
public static string LoginURL(
string returnURL,
bool override
)
``` | How do I get the portal's current login URL in DotNetNuke? | [
"",
"c#",
"asp.net",
"vb.net",
"dotnetnuke",
""
] |
I'm trying to create a dynamic filter for various classes. We would only know at runtime what type we're dealing with. I need the ColumnName to be the actual column (not a string value).
Is there an easy way to convert the string into a column?
```
public static List<T> Filter<T>
(this List<T> Source, string ColumnName,
string TypeOfCompare, string CompValue)
{
IQueryable<T> matches = Source.AsQueryable();
if (ColumnName.Length > 0)
{
matches = (IEnumerable)matches.Where(a => ColumnName == CompValue)
}
List<T> ReturnList2 = new List<T>();
ReturnList2 = matches.ToList();
return ReturnList2;
}
``` | Basically you need to build an expression tree. It's not terribly hard, fortunately, using [`Expression.Property`](http://msdn.microsoft.com/en-us/library/bb341554.aspx). You can either pass that to `Queryable.Where`, or compile it and pass it to `Enumerable.Where`. (Obviously you'll need to use something like [`Expression.Equal`](http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.equal.aspx)
as well, depending on the type of comparison you're trying to make.)
Is `CompValue` meant to be an actual value? What's `TypeOfCompare` meant to be?
I'm not sure where LINQ to Entities fits into this, either... you're only using LINQ to Objects really, as far as I can see.
EDIT: Okay, here's a sample. It assumes you want equality, but it does what you want if so. I don't know what the performance impact of compiling an expression tree every time is - you may want to cache the delegate for any given name/value combination:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
static class Extensions
{
public static List<T> Filter<T>
(this List<T> source, string columnName,
string compValue)
{
ParameterExpression parameter = Expression.Parameter(typeof(T), "x");
Expression property = Expression.Property(parameter, columnName);
Expression constant = Expression.Constant(compValue);
Expression equality = Expression.Equal(property, constant);
Expression<Func<T, bool>> predicate =
Expression.Lambda<Func<T, bool>>(equality, parameter);
Func<T, bool> compiled = predicate.Compile();
return source.Where(compiled).ToList();
}
}
class Test
{
static void Main()
{
var people = new[] {
new { FirstName = "John", LastName = "Smith" },
new { FirstName = "John", LastName = "Noakes" },
new { FirstName = "Linda", LastName = "Smith" },
new { FirstName = "Richard", LastName = "Smith" },
new { FirstName = "Richard", LastName = "Littlejohn" },
}.ToList();
foreach (var person in people.Filter("LastName", "Smith"))
{
Console.WriteLine(person);
}
}
}
``` | Instead of a string `ColumnName`, can't you pass a selector for that column (I realize this isn't always possible, but just in case it is …)? This you could use, then.
By the way, the code is way too complicated. This should work:
```
public static List<T> Filter<T>(
this List<T> Source, Func<T, string> selector, string CompValue)
{
return Source.Where(a => selector(a) == CompValue).ToList();
}
```
You could then call the code as follows:
```
var result = myList.Filter(x => x.ColumnName, "foo");
``` | Dynamic Where for List<T> | [
"",
"c#",
"linq-to-entities",
""
] |
is it possible ? any samples/patterns or ideas on how to go about it ?
Update -
this essentially becomes a text browser which displays various tables of information based on various commands on the prompt like typing the url in a browser
now instead of typing various commands like
prompt>command arg1 arg2
if only you could say "click" on the text in a certain "column"/"row" which would execute the command say
prompt>commandX arg1
it'd be somewhat faster/easier
Now, before someone mentions doing a typical browser/asp.net mvc/whatever app, i already have that running but have encountered some limitations esp. with accesing network files. etc. Now that's taken care of using a service-broker service which reads the file etc. but having added numerous extensions to it, it'd be somewhat easier if you could just run the app as a console prompt with a mvc pattern and add extensions to it etc. etc.
if only the text is clickable, it'd make it more friendly for use !! | The window's shell doesn't support clickable hyperlinks, so no, this isn't possible.
What are you trying to do that warrants the need for hyperlinks in the command shell? Perhaps this application would be better built as a WinForms/WPF or ASP.NET application. | Assuming no mouse, I would just launch the URL as a new process based on some keyboard trigger.
```
// this will launch the default browser
ProcessStartInfo psi = new ProcessStartInfo("https://stackoverflow.com");
Process p = new Process(psi);
p.Start();
```
---
`VB` syntax:
```
// this will launch the default browser
Dim psi = New ProcessStartInfo("https://stackoverflow.com")
Dim p As Process = Process.Start(psi)
``` | .net console app with hyperlinks? | [
"",
"c#",
".net",
"console",
"console-application",
""
] |
Is there any tool that will inspect either asp.net or sql server and report all the queries that are run against the database? The reason I ask is I am using Linq for a project and want to double check what its actually doing for each page.
Ideally I'd like to view a page in a browser and have a report of all the queries that were run to create that page.
I know I can view the SQL it runs for individual queries using debugging/breakpoints, and I know about LinqPad, but I'm afraid Linq is making several more queries on its own to get related data that I may not be directly aware of. Is there anything (tool/program/report/etc) like what I described? Thanks!
EDIT: Is there any *FREE* tool that can do this? I am using Sql Server 2008 Express and don't have SQL Profiler unfortunately. | Absolutely, There is a SQL tool called [SQL Profiler](http://msdn.microsoft.com/en-us/library/aa173918%28SQL.80%29.aspx). It does require elevated database permissions in order to run profiler.
There is a decent tutorial on how to run Profiler on [TechRepublic](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-5054787.html).
Another option out there is the [NHibernate Profiler](http://nhprof.com/). I know that it is not as "free" as SQL Profiler, have never used it, but the screen shots for it look pretty cool. | Profiler is the best tool of them all for this but it can be expensive in inexperienced hands.
You can also try to do "exec sp\_who" and then a "dbcc inputbuffer (111)" - just put the process id in the place of 111. | Is there any tool to see the queries run against the database? | [
"",
"asp.net",
"sql",
"sql-server",
"linq-to-sql",
"reporting",
""
] |
I am launching another process from by C# application, and came to a problem: is there any way to read process output char-by-char, not line-by-line? I desperately need that because the other process is a command-line engine, and I need to send a command to it, read output and somehow understand when it is done. The way it indicates that is to write a prompt WITHOUT a newline, so I have no chance to ever capture that. Using fragile timer stuff now, and looking for a better solution.
C# Process API as outlined in MSDN and [other places](https://stackoverflow.com/questions/1060799/c-shell-io-redirection) only allows for line-by-line input - even in async way. | I haven't tried it, but the following approach might work to avoid busy looping:
1. Redirect the command line output to a file.
2. Use the FindFirstChangeNotification from the Win32 API (with flag FILE\_NOTIFY\_CHANGE\_SIZE) to detect file size changes.
That's an awful lot of work just to prevent busy looping however. Personally, I'd suggest an incremental backoff wait loop, to prevent using too much system resources. Something like (pseudocode):
```
int waittime = 1;
bool done = false;
while (true)
{
ReadAsMuchAsIsAvailable();
if (TheAvailableOutputEndsInAPrompt())
{
break;
}
Sleep (waittime);
waittime++; // increase wait time
waittime = min(waittime, 1000); // max 1 second
}
```
This will yield quick end-of-operation detection for quick commands, and slower for slow commands. That means that you can do a large series of quick commands and have their ends be detected quickly, while longer commands may have an overhead of up to 1 second (which won't be noticeable given the size of the commands themselves). | This is a sample program that starts a process, and reads standard output, character by character and not line by line:
```
static void Main(string[] args)
{
var process = new Process();
process.StartInfo = new ProcessStartInfo(@"C:\Windows\System32\cmd.exe", "/c dir");
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.Start();
var outReader = process.StandardOutput;
while (true)
{
if (!outReader.EndOfStream)
Console.Write((char)outReader.Read() + ".");
if (outReader.EndOfStream)
Thread.Sleep(1);
}
}
```
A small disclaimer--this was knocked up in no time, and I haven't proved out the issues around timing (what if the process exits before we've grabbed standard output -- very unlikely, I know). As far as your particular issue is concerned however, it shows that one doesn't need to read line by line (you're dealing with a `StreamReader` after all).
**UPDATE**: As per suggestions, included a `Thread.Sleep(1)` to yield the thread. Apparently there are issues with using `Thread.Sleep(0)`, *despite* MSDN documentation on the matter (lower priority threads aren't given time). And *yes*, this is an infinite loop, and there'd have to be some thread management stuff involved to finish-off once the process has completed. | .NET IO redirection - read output char by char | [
"",
"c#",
".net",
"windows",
""
] |
Consider the current algorithm below that iterates through a `GridView`'s rows to find whether the contained `Checkbox` is selected/checked.
```
List<int> checkedIDs = new List<int>();
foreach (GridViewRow msgRow in messagesGrid.Rows)
{
CheckBox chk = (CheckBox)msgRow.FindControl("chkUpdateStatus");
if (chk.Checked){
//we want the GridViewRow's DataKey value
checkedMsgIDs.Add(int.Parse(messagesGrid.DataKeys[msgRow.RowIndex].Value.ToString()));
}
}
```
This works as expected: you're left with a fully populated `List<int>`.
**Question**: How would you or could you re-write or improve this algorithm using LINQ to search the `GridView` for all the rows who have their `Checkbox` selected/checked? | I'm pretty sure you're not going to get any performance improvement from this, but it might make it *slightly* easier to read:
```
var checkedIDs = from GridViewRow msgRow in messagesGrid.Rows
where ((CheckBox)msgRow.FindControl("chkUpdateStatus")).Checked
select Int32.Parse(messagesGrid.DataKeys[msgRow.RowIndex].Value.ToString());
```
Again, not sure it makes a difference. Also, why are you converting to a string then to an int? Is there something `Convert.ToInt32` can't do for you? | I am not sure if Rows is IEnumerable they may not be, but I am going to assume they are
```
List<int> checkedIDs = messagesGrid.Rows
.Where<GridViewRow>(i => (CheckBox)i.FindControl("chkUpdateStatus").Checked)
.Select<GridViewRow, int>(i => return int.Parse(messagesGrid.DataKeys[i.RowIndex].Value.ToString()))
.ToList<int>();
```
I just did this in notepad, there might be a compile error in there. But this is how you could do the same thing with Linq. | LINQ: find all checked checkboxes in a GridView | [
"",
"c#",
"asp.net",
"linq",
"webforms",
"ienumerable",
""
] |
I'm new to Python / GAE / Django. I get that with GAE there are no in-memory sessions per se... but I think I want something equivalent. I [read](http://docs.djangoproject.com/en/dev/topics/http/sessions/) that Django sessions [can be backed](http://code.google.com/appengine/articles/appengine_helper_for_django.html) by BigTable or MemCache, but I never got them working. I guess what I'm asking is "Should I..."
1. Persist with getting Django sessions working?
2. Look at some other webapp framework for sessions in particular, or the site in general?
3. Roll my own?
It seems to me that sessions are not supported out-of-the-box and are somehow not first class citizens. What do you do?!
Thanks. | The reason django sessions are not supported by App engine out of the box is because django uses database table (model) based sessions, and the django ORM is not supported on appengine.
A solution to this is to make django models work out of the box on appengine. And it has been done by patching django code, in the [App Engine Patch](http://code.google.com/p/app-engine-patch/) project.
Using this patch, as django models work, you get to access django admin, django auth along with the latest django release.
You may also find this blog post on deploying a django application on App engine, useful: <http://uswaretech.com/blog/2009/04/develop-twitter-api-application-in-django-and-deploy-on-google-app-engine/> | The gaeutilities library comes with a session management class that works well:
* <http://gaeutilities.appspot.com/> | How to get started with Sessions in Google App Engine / Django? | [
"",
"python",
"django",
"google-app-engine",
""
] |
How do I pull a spring bean manually? I have a rather large web application, and in a given service, a transient object requires access to a bean that is machine specific (database connection info.) Since the application runs in a cluster, this transient object (which can bounce between servers) always needs to grab the correct connection been from the current spring context and server.
So, what's the best way to manually pull a bean out of spring? | You could have your service implement [ApplicationContextAware](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/context/ApplicationContextAware.html) so that you have access to the ApplicationContext itself and can call getBean() directly on it. | ```
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
Object o = ctx.getBean("dataSource");
```
Of course you can cast the bean like this:
```
DataSource d = (DataSource) ctx.getBean("dataSource");
``` | Best way to manually pull a spring bean? | [
"",
"java",
"spring",
"tomcat",
"javabeans",
""
] |
> **Possible Duplicate:**
> [How to retrieve duration of MP3 in .NET?](https://stackoverflow.com/questions/383164/how-to-retrieve-duration-of-mp3-in-net)
I'm makin' a little mp3 player here and I've pretty much got everything covered. I would like to be able to display the duration of the song but am kinda confused as to go about doing so. I've searched around the net and have seen so many examples that seem so long which makes me wonder if there's an easier way to get the duration of a song? | You may be interested in [Mp3Sharp](http://robburke.net/mle/mp3sharp/). I haven't used it much, but I see functions such as BitsPerSample, which may be useful for what you're trying to accomplish. | The only way to make sure the duration of an MP3 is to decode it.
Especially when it's VBR encoded, it's hard to guess the length by the file size. Some MP3s have the length in the ID3 tag, so you can take that as a hint; but in my experience, even that's not always accurate. | Err.. Duration of Song? | [
"",
"c#",
"mp3",
"media-player",
""
] |
I'm working on a project synching a facebook application with a regular website.
The db has got a users table, but the table only has got the user ID of each user of the application. The user id is the facebook user id of the people.
For each user in the users table, I need to fetch their name, and other info from facebook. The client is using a facebook application, so I believe he should have a developer key, and anything else needed.
My question is, how can I retrieve the users' name and other info from facebook using their facebook user id? | First of all make sure that your plan is d'accord with the [Facebook Developer Policy](http://wiki.developers.facebook.com/index.php/Platform_Policy_Overview#6._Storing_and_Using_Data_You_Receive_From_Facebook).
> you cannot store data you receive from
> Facebook, except certain "Storable
> Data".
<http://wiki.developers.facebook.com/index.php/Platform_Policy_Overview#6._Storing_and_Using_Data_You_Receive_From_Facebook>
To answer your Question.
**The hack way:**
A Batched FQL statement for several Users should do the trick. You can either use the API Function (also batchable) or the API Call for FQL Queries.
**The better and more feature-rich way:**
You want to **Connect** your Website to **Facebook**. What you are actually looking for is [Facebook Connect.](http://wiki.developers.facebook.com/index.php/Facebook_Connect)
Facebook Connect is simply said a Javascript Layer that replaces Placeholder tags. With Facebook Connect you are able to say `<fb:photo pid="54321" uid="6789"></fb:photo>.` or in your case | With the following FQL statement:
```
SELECT name FROM user WHERE uid=211031
```
For more details read <http://wiki.developers.facebook.com/index.php/FQL> | Facebook developemt in PHP - newbie questions | [
"",
"php",
"facebook",
""
] |
I am having some trouble with the classic javascript local variable scope topic, but dealing with a JSON variable. I have looked at other questions here regarding the same thing, but nothing has matched my case exactly, so here goes. I have a class that I have made from javascript that has 3 methods: func1, func2, and func3. I also have a local JSON variable that is being set in one of the methods from an ajax call I am making with jquery, but is not set when I call a method that returns that local variables value. I know the ajax is working fine, b/c I can display the data that is being returned and being set to the json variable fine with no problem. It is only happening when I call another method that interacts with that JSON variable. Here is a basic version of my code:
```
function func1(){
func2();
}
function func2(){
$.getJSON("http://webservice.mydomain.com/methodname&jsoncallback=?",
function(data){
this.z = eval("(" + data.d + ")");
alert(data.d); //this displays the data!
alert(this.z.ArrayProperty[0].Property1); //this displays
//the correct data too!
}
);
}
function func3(){
return this.z.ArrayProperty[0].Property1;
}
function myClass(var1, var2){
this.x = var1;
this.y = var2;
this.z = "";
this.func1 = func1;
this.func2 = func2;
this.func3 = func3;
}
```
And then in my .html page, I am having the following code:
```
var obj = new myClass(1,2);
obj.func1("abc");
alert(obj.func3()); //ERROR: this.z.ArrayProperty is undefined
```
Any ideas?!?! I am racking my mind!
Thanks | I don't think this is anything to do with scope.
Remember that the AJAX call is asynchronous so func3 is being called before the JSON has been returned and your anonymous function has had a chance to set this.z to anything. | I don't think "this" inside your callback is the same "this" that defined func2. Using the Prototype JavaScript library, you can use bind() to get around this.
You may be able to just add a new variable in func2, or use a bind function in whatever library you are using.
```
func2() {
var me = this;
$.getJSON("http://webservice.mydomain.com/methodname&jsoncallback=?",
function(data){
me.z = eval("(" + data.d + ")");
success = true;
alert(data.d); //this displays the data!
alert(this.z.ArrayProperty[0].Property1);
}
);
}
``` | Custom javascript class and private variable scope issue | [
"",
"javascript",
"json",
"oop",
"scope",
""
] |
I only want the Keys and not the Values of a Dictionary.
I haven't been able to get any code to do this yet. Using another array proved to be too much work as I use remove also.
**How do I get a List of the Keys in a Dictionary?** | Use the [`Dictionary<TKey,TValue>.Keys`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keys) property:
```
List<string> keyList = new List<string>(this.yourDictionary.Keys);
``` | You should be able to just look at `.Keys`:
```
Dictionary<string, int> data = new Dictionary<string, int>();
data.Add("abc", 123);
data.Add("def", 456);
foreach (string key in data.Keys)
{
Console.WriteLine(key);
}
``` | How do I get the list of keys in a Dictionary? | [
"",
"c#",
"list",
"dictionary",
""
] |
What is the best way to strip all non alphanumeric characters from a string, using Python?
The solutions presented in the [PHP variant of this question](https://stackoverflow.com/questions/840948) will probably work with some minor adjustments, but don't seem very 'pythonic' to me.
For the record, I don't just want to strip periods and commas (and other punctuation), but also quotes, brackets, etc. | I just timed some functions out of curiosity. In these tests I'm removing non-alphanumeric characters from the string `string.printable` (part of the built-in `string` module). The use of compiled `'[\W_]+'` and `pattern.sub('', str)` was found to be fastest.
```
$ python -m timeit -s \
"import string" \
"''.join(ch for ch in string.printable if ch.isalnum())"
10000 loops, best of 3: 57.6 usec per loop
$ python -m timeit -s \
"import string" \
"filter(str.isalnum, string.printable)"
10000 loops, best of 3: 37.9 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]', '', string.printable)"
10000 loops, best of 3: 27.5 usec per loop
$ python -m timeit -s \
"import re, string" \
"re.sub('[\W_]+', '', string.printable)"
100000 loops, best of 3: 15 usec per loop
$ python -m timeit -s \
"import re, string; pattern = re.compile('[\W_]+')" \
"pattern.sub('', string.printable)"
100000 loops, best of 3: 11.2 usec per loop
``` | Regular expressions to the rescue:
```
import re
re.sub(r'\W+', '', your_string)
```
> By Python definition `'\W` == `[^a-zA-Z0-9_]`, which excludes all `numbers`, `letters` and `_` | Stripping everything but alphanumeric chars from a string in Python | [
"",
"python",
"string",
"non-alphanumeric",
""
] |
I'm making a website which allows people to upload files, html pages, etc... Now I'm having a problem. I have a directory structure like this:
```
-/USERS
-/DEMO1
-/DEMO2
-/DEMO3
-/etc... (every user has his own direcory here)
-index.php
-control_panel.php
-.htaccess
```
Now I want to disable PHP, but enable Server-side includes in the direcories and subdirectories inside /USERS
Can this be done (and if so, how)?
I use WAMP server | Try to disable the [`engine` option](http://docs.php.net/manual/en/apache.configuration.php#ini.engine) in your .htaccess file:
```
php_flag engine off
``` | To disable all access to sub dirs (safest) use:
```
<Directory full-path-to/USERS>
Order Deny,Allow
Deny from All
</Directory>
```
If you want to block only PHP files from being served directly, then do:
1 - Make sure you know what file extensions the server recognizes as PHP (and dont' allow people to override in htaccess). One of my servers is set to:
```
# Example of existing recognized extenstions:
AddType application/x-httpd-php .php .phtml .php3
```
2 - Based on the extensions add a Regular Expression to FilesMatch (or LocationMatch)
```
<Directory full-path-to/USERS>
<FilesMatch "(?i)\.(php|php3?|phtml)$">
Order Deny,Allow
Deny from All
</FilesMatch>
</Directory>
```
Or use *Location* to match php files (I prefer the above files approach)
```
<LocationMatch "/USERS/.*(?i)\.(php3?|phtml)$">
Order Deny,Allow
Deny from All
</LocationMatch>
``` | Disable PHP in directory (including all sub-directories) with .htaccess | [
"",
"php",
"apache",
".htaccess",
""
] |
Is there a difference between compiling php with the parameter:
```
--with-[extension name]
```
as opposed to just compiling it as a shared module and including it that way? Is there any performance benefit? If not, why would you want to do this? | Any performance benefit would be negligible. It’s simply another option for packaging up your PHP build.
On my Mac I use [Marc Liyange’s build of PHP](http://www.entropy.ch/software/macosx/php/), which includes, among other things, built-in PostgreSQL support. It was built with the `--with-pdo-pgsql` flag. As a result it does not need to be distributed with the pdo-pgsql shared library.
If he did not build with `--with-pdo-pgsql`, he would have needed to distribute the pdo-pgsql shared library and include a directive in `php.ini` to load it. Sure, it’s just a minor difference, but if you know you are going to be using that functionality, it’s fine to build it into PHP itself. | Maybe it won't be a full answer to your question, but here's what I've been able to find so far : there is some kind of a partial answer in the book "**Extending and Embedding PHP**", written by Sara Golemon ([amazon](https://rads.stackoverflow.com/amzn/click/com/067232704X) ; some parts are also available on google books).
The relevant part *(a note at the top of page 56)* is :
> Ever wonder why some extensions are
> configured using `--enable-extname` and
> some are configured using
> `--with-extname`? Functionally, there is no difference between the two. In
> practice, however, `--enable` is meant
> for features that can be turned on
> without requiring any third-party
> libraries. `--with`, by contrast, is
> meant for features that do have such
> prerequisites.
So, not a single word about performance (I guess, if there is a difference, it is only a matter of "*loading one more file*" vs "*loading one bigger file*") ; but there is a technical reason behind this possibility.
I guess this is done so PHP itself doesn't **require** an additional external library because of some extension ; using the right option allows for users to enable or disable the extension themselves, depending on whether or not they already have that external library. | Compiling php with modules vs using shared modules? | [
"",
"php",
""
] |
the problem is in centered layout of components, GridBagLayout always 'sits' in center of JPanel, so I don't care how it will layout components inside, my problem is where these components will start laying out on a panel.
I tried with:
```
panel.setAlignmentX( JPanel.LEFT_ALIGNMENT );
```
but it did not helped.
Any idea? | You need to add at least one component that will fill the horizontal space. If you don't have such a component you can try this:
```
GridBagConstraints noFill = new GridBagConstraints();
noFill.anchor = GridBagConstraints.WEST;
noFill.fill = GridBagConstraints.NONE;
GridBagConstraints horizontalFill = new GridBagConstraints();
horizontalFill.anchor = GridBagConstraints.WEST;
horizontalFill.fill = GridBagConstraints.HORIZONTAL;
panel.add(new JLabel("Left Aligned"), noFill);
panel.add(Box.createHorizontalGlue(), horizontalFill);
``` | In addition to setting the `anchor` and `fill` fields, you will likely need to set the `weightx` field. This helps specify resizing behavior.
[Quote](http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html):
> Unless you specify at least one non-zero value for weightx or weighty, all the components clump together in the center of their container. This is because when the weight is 0.0 (the default), the GridBagLayout puts any extra space between its grid of cells and the edges of the container.
The following will keep `myComponent` anchored to the `NORTHWEST` corner. Assuming `this` is `JPanel` or similar:
```
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Specify horizontal fill, with top-left corner anchoring
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.NORTHWEST;
// Select x- and y-direction weight. Without a non-zero weight,
// the component will still be centered in the given direction.
c.weightx = 1;
c.weighty = 1;
// Add child component
add(myComponent, c);
```
To keep child components left-aligned yet vertically-centered, just set `anchor = WEST` and remove `weighty = 1;`. | How to push GridbagLayout not to lay components in the center of JPanel | [
"",
"java",
"user-interface",
"swing",
"layout",
""
] |
Is there any way to replace a regexp with modified content of capture group?
Example:
```
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher(text);
resultString = regexMatcher.replaceAll("$1"); // *3 ??
```
And I'd like to replace all occurrence with $1 multiplied by 3.
**edit:**
Looks like, something's wrong :(
If I use
```
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll(regexMatcher.group(1));
} catch (Exception e) {
e.printStackTrace();
}
```
It throws an IllegalStateException: No match found
But
```
Pattern regex = Pattern.compile("(\\d{1,2})");
Matcher regexMatcher = regex.matcher("12 54 1 65");
try {
String resultString = regexMatcher.replaceAll("$1");
} catch (Exception e) {
e.printStackTrace();
}
```
works fine, but I can't change the $1 :(
**edit:**
Now, it's working :) | How about:
```
if (regexMatcher.find()) {
resultString = regexMatcher.replaceAll(
String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}
```
To get the first match, use `#find()`. After that, you can use `#group(1)` to refer to this first match, and replace all matches by the first maches value multiplied by 3.
And in case you want to replace each match with that match's value multiplied by 3:
```
Pattern p = Pattern.compile("(\\d{1,2})");
Matcher m = p.matcher("12 54 1 65");
StringBuffer s = new StringBuffer();
while (m.find())
m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
System.out.println(s.toString());
```
You may want to look through [`Matcher`'s documentation](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html), where this and a lot more stuff is covered in detail. | earl's answer gives you the solution, but I thought I'd add what the problem is that's causing your `IllegalStateException`. You're calling `group(1)` without having first called a matching operation (such as `find()`). This isn't needed if you're just using `$1` since the `replaceAll()` is the matching operation. | Java Regex Replace with Capturing Group | [
"",
"java",
"regex",
""
] |
I am curious, is there a size limit on serialize in PHP. Would it be possible to serialize an array with 5,000 keys and values so it can be stored into a cache?
I am hoping to cache a users friend list on a social network site, the cache will need to be updated fairly often but it will need to be read almost every page load.
On a single server setup I am assuming APC would be better then memcache for this. | As quite a couple other people answered already, just for fun, here's a very quick benchmark *(do I dare calling it that ? )* ; consider the following code :
```
$num = 1;
$list = array_fill(0, 5000, str_repeat('1234567890', $num));
$before = microtime(true);
for ($i=0 ; $i<10000 ; $i++) {
$str = serialize($list);
}
$after = microtime(true);
var_dump($after-$before);
var_dump(memory_get_peak_usage());
```
*I'm running this on PHP 5.2.6 (the one bundled with Ubuntu jaunty).*
*And, yes, there are only values ; no keys ; and the values are quite simple : no object, no sub-array, no nothing but string.*
For `$num = 1`, you get :
```
float(11.8147978783)
int(1702688)
```
For `$num = 10`, you get :
```
float(13.1230671406)
int(2612104)
```
And, for `$num = 100`, you get :
```
float(63.2925770283)
int(11621760)
```
So, it seems the bigger each element of the array is, the longer it takes *(seems fair, actually)*. But, for elements 100 times bigger, you don't take 100 times much longer...
Now, with an array of 50000 elements, instead of 5000, which means this part of the code is changed :
```
$list = array_fill(0, 50000, str_repeat('1234567890', $num));
```
With `$num = 1`, you get :
```
float(158.236332178)
int(15750752)
```
Considering the time it took for 1, I won't be running this for either $num = 10 nor $num = 100...
Yes, of course, in a real situation, you wouldn't be doing this 10000 times ; so let's try with only 10 iterations of the for loop.
For `$num = 1` :
```
float(0.206310987473)
int(15750752)
```
For `$num = 10` :
```
float(0.272629022598)
int(24849832)
```
And for `$num = 100` :
```
float(0.895547151566)
int(114949792)
```
Yeah, that's almost 1 second -- and quite a bit of memory used ^^
*(No, this is not a production server : I have a pretty high memory\_limit on this development machine ^^ )*
So, in the end, to be a bit shorter than those number *-- and, yes, you can have numbers say whatever you want them to --* I wouldn't say there is a "limit" as in "hardcoded" in PHP, but you'll end up facing one of those :
* `max_execution_time` (generally, on a webserver, it's never more than 30 seconds)
* `memory_limit` (on a webserver, it's generally not muco more than 32MB)
* the load you webserver will have : while 1 of those big serialize-loop was running, it took 1 of my CPU ; if you are having quite a couple of users on the same page at the same time, I let you imagine what it will give ;-)
* the patience of your user ^^
But, except if you are really serializing **long arrays of big data**, I am not sure it will matter that much...
And you must take into consideration the amount of time/CPU-load using that cache might help you gain ;-)
Still, the best way to know would be to test by yourself, with real data ;-)
And you might also want to take a look at what [Xdebug](http://xdebug.org/) can do when it comes to [profiling](http://xdebug.org/docs/profiler) : this kind of situation is one of those it is useful for! | The [serialize()](http://us.php.net/serialize) function is only limited by available memory. | serialize a large array in PHP? | [
"",
"php",
"serialization",
""
] |
i'm trying to develop an interface like Windows Task Manager -> Performance Tab using Java. Can you suggest any Java Graphic Library to ease my development ? | If your question is about how to generate charts like the processor usage chart in Windows Task Manager / Performance, have a look at for example [JFreeChart](http://www.jfree.org/jfreechart/).
Java has a powerful 2D graphics API built-in, see [Trail: 2D Graphics](http://java.sun.com/docs/books/tutorial/2d/index.html) in Sun's Java Tutorials. | <http://en.wikipedia.org/wiki/Java2D>
Or, for more advanced graphics, you can use OpenGL
<http://en.wikipedia.org/wiki/Java_OpenGL> | java graphic library | [
"",
"java",
"graphics",
""
] |
I have an ugly piece of Serial Port code which is very unstable.
```
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
while (port.BytesToRead > 0)
{
var count = port.BytesToRead;
byte[] buffer = new byte[count];
var read = port.Read(buffer, 0, count);
if (DataEncapsulator != null)
buffer = DataEncapsulator.UnWrap(buffer);
var response = dataCollector.Collect(buffer);
if (response != null)
{
this.OnDataReceived(response);
}
Thread.Sleep(100);
}
}
```
If I remove either Thread.Sleep(100) calls the code stops working.
Of course this really slows things down and if lots of data streams in,
it stops working as well unless I make the sleep even bigger.
(Stops working as in pure deadlock)
Please note the DataEncapsulator and DataCollector are components
provided by MEF, but their performance is quite good.
The class has a Listen() method which starts a background worker to
receive data.
```
public void Listen(IDataCollector dataCollector)
{
this.dataCollector = dataCollector;
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerAsync();
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
port = new SerialPort();
//Event handlers
port.ReceivedBytesThreshold = 15;
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
..... remainder of code ...
```
Suggestions are welcome!
**Update:**
\*Just a quick note about what the IDataCollector classes do.
There is no way to know if all bytes of the data that has been sent
are read in a single read operation. So everytime data is read it is
passed to the DataColllector which returns true when a complete and
valid protocol message has been received. In this case here it just
checks for a sync byte, length , crc and tail byte. The real work
is done later by other classes.
\*
**Update 2:**
I replaced the code now as suggested, but still there is something wrong:
```
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
var count = port.BytesToRead;
byte[] buffer = new byte[count];
var read = port.Read(buffer, 0, count);
if (DataEncapsulator != null)
buffer = DataEncapsulator.UnWrap(buffer);
var response = dataCollector.Collect(buffer);
if (response != null)
{
this.OnDataReceived(response);
}
}
```
You see this works fine with a fast and stable connection.
But OnDataReceived is NOT called every time data is received.
(See the MSDN docs for more). So if the data gets fragmented
and you only read once within the event data gets lost.
And now I remember why I had the loop in the first place, because
it actually does have to read multiple times if the connection is slow or unstable.
Obviously I can't go back to the while loop solution, so what can I do? | My first concern with the original while-based code fragment is the constant allocation of memory for the byte buffer. Putting a "new" statement here specifically going to the .NET memory manager to allocate memory for the buffer, while taking the memory allocated in the last iteration and sending it back into the unused pool for eventual garbage collection. That seems like an awful lot of work to do in a relatively tight loop.
I am curious as to the performance improvement you would gain by creating this buffer at design-time with a reasonable size, say 8K, so you don't have all of this memory allocation and deallocation and fragmentation. Would that help?
```
private byte[] buffer = new byte[8192];
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
while (port.BytesToRead > 0)
{
var count = port.BytesToRead;
var read = port.Read(buffer, 0, count);
// ... more code
}
}
```
My other concern with re-allocating this buffer on every iteration of the loop is that the reallocation may be unnecessary if the buffer is already large enough. Consider the following:
* Loop Iteration 1: 100 bytes received; allocate buffer of 100 bytes
* Loop Iteration 2: 75 bytes received; allocate buffer of 75 bytes
In this scenario, you don't really need to re-allocate the buffer, because the buffer of 100 bytes allocated in Loop Iteration 1 is more than enough to handle the 75 bytes received in Loop Iteration 2. There is no need to destroy the 100 byte buffer and create a 75 byte buffer. (This is moot, of course, if you just statically create the buffer and move it out of the loop altogether.)
On another tangent, I might suggest that the DataReceived loop concern itself only with the reception of the data. I am not sure what those MEF components are doing, but I question if their work has to be done in the data reception loop. Is it possible for the received data to be put on some sort of queue and the MEF components can pick them up there? I am interested in keeping the DataReceived loop as speedy as possible. Perhaps the received data can be put on a queue so that it can go right back to work receiving more data. You can set up another thread, perhaps, to watch for data arriving on the queue and have the MEF components pick up the data from there and do their work from there. That may be more coding, but it may help the data reception loop be as responsive as possible. | And it can be so simple...
Either you use DataReceived handler but without a loop and certainly without Sleep(), read what data is ready and push it somewhere (to a Queue or MemoryStream),
or
Start a Thread (BgWorker) and do a (blocking) serialPort1.Read(...), and again, push or assemble the data you get.
### Edit:
From what you posted I would say: drop the eventhandler and just Read the bytes inside Dowork(). That has the benefit you can specify how much data you want, as long as it is (a lot) smaller than the ReadBufferSize.
### Edit2, regarding Update2:
You will still be much better of with a while loop inside a BgWorker, not using the event at all. The simple way:
```
byte[] buffer = new byte[128]; // 128 = (average) size of a record
while(port.IsOpen && ! worker.CancelationPending)
{
int count = port.Read(buffer, 0, 128);
// proccess count bytes
}
```
Now maybe your records are variable-sized and you don't don't want to wait for the next 126 bytes to come in to complete one. You can tune this by reducing the buffer size or set a ReadTimeOut. To get very fine-grained you could use port.ReadByte(). Since that reads from the ReadBuffer it's not really any slower. | How can I improve this underperforming, terrible Serial Port code? | [
"",
"c#",
".net",
"performance",
"serial-port",
""
] |
Does `null` have a type? How is a null value represented internally? What is happening in the following code?
```
void Foo(string bar) {...}
void Foo(object bar) {...}
Foo((string)null);
```
Edit: The answers so far have been unspecific and too high-level. I understand that a reference type object consists of a pointer on the stack which points to a location on the heap which contains a sync block index, a type handle and the object's fields. When I set an instance of an object to `null`, where does the pointer on the stack point to, exactly? And in the code snippet, is the cast simply used by the C# compiler to decide which overload to call, and there is not *really* any casting of null going on?
I am looking for an in-depth answer by someone who understands the CLR internals. | The cast to `string` in your code sample doesn't give the `null` a type, as `null` cannot have a type itself. If you want proof of this, then execute the following code where you can see that `null` is always equal to itself, irrespective of what the type of variable it was assigned to is:
```
string s = null;
IPAddress i = null;
Console.WriteLine(object.Equals(s, i)); // prints "True"
Console.WriteLine(object.ReferenceEquals(s, i)); // prints "True"
```
What the cast does is tell the compiler which overload to choose. As `null` doesn't have a type it does not know whether to choose the overload that takes an `object` or a `string` as the value could be interpreted as either. So you're helping it out by saying "Here's a null value that should be treated as if it was a string".
---
If you want to see what's going on underneath, then look at the IL from your code. The relevant bit for the method call is something like the following in textual IL (depending on your namespace and class name, etc):
```
ldnull
call void ConsoleApplication1.Program::Foo(string)
```
So all that's happening is that a null is being loaded on the stack, and then this is consumed by the overload that takes the string, as overload resolution is performed at compile time so the method to call is baked into the IL.
If you want to see what `ldnull` does, and why it's different from just using something like `ldc.i4.0` to load a zero onto the stack then see [this answer](https://stackoverflow.com/questions/398966/how-is-null-represented-in-net/398978#398978) (if you don't want to follow the link, the reason is that it's a size-agnostic zero which otherwise doesn't exist in the CLR). | null does not have type, and "And in the code snippet, is the cast simply used by the C# compiler to decide which overload to call, and there is not really any casting of null going on?" is exactly what is going on. Let's look at the generated IL.
```
IL_0001: ldnull
IL_0002: call void ConsoleApplication1.Program::Foo(string)
```
Notice the ldnull loading null to the stack. It is simply null, not null as a string or something else. What matters is the second line, where IL is explicitly calling the overload that receives a string. Here is what happens if you call, casting to object:
```
IL_0001: ldnull
IL_0002: call void ConsoleApplication1.Program::Foo(object)
```
So, yes, the cast is a C# artifact so the compiler knows what overload to call. | In .Net/C#, is null strongly-typed? | [
"",
"c#",
".net",
""
] |
Threads are light weight processes, what does it mean? | According to [Wikipedia's definition](http://en.wikipedia.org/wiki/Light-weight_process) some resources like memory can be shared between threads.
Hope this will help you. | It means that creating and maintaining a process is a relatively large amount of work in many operating systems, primarily because each process has its own address space. Threads within a process share their address space, and therefore creating lots of short-lived threads is much less resource-intensive than creating an equal number of processes would be.
For example, early CGI-based web applications would have the web server create a separate process to handle each request. But such applications couldn't handle much load, a few dozen requests per second would overwhelm them (this being in the late 90s, on much slower hardware as well). Web applications that use threads to handle individual requests, such as those based on Java Servlets, are much more scalable - Even back then, Servlet apps running on comparatively slow JVMs were easily outperforming traditional CGI apps written in C, because the process creation overhead outweighted the speed advantages of C.
Read more about this [on Wikipedia](http://en.wikipedia.org/wiki/Thread_(computing)#Processes.2C_kernel_threads.2C_user_threads.2C_and_fibers). | What does light weight process mean? | [
"",
"java",
"multithreading",
"process",
""
] |
I have an MFC C++ project compiler under Visual Studio 2008.
I'm adding a \_AFX\_NO\_DEBUG\_CRT in my stdafx.h before the #include to avoid all the debug new and deletes that MFC provides (I wish to provide my own for better cross platform compatibility).
However when I do this I get a stream of errors such as the following:
```
>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : '__asm'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ')' before '{'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before '{'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : warning C4091: '' : ignored on left of 'int' when no variable is declared
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before 'constant'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before '}'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2143: syntax error : missing ';' before ','
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')'
1>c:\program files\microsoft visual studio 9.0\vc\atlmfc\include\afxtls_.h(62) : error C2059: syntax error : ')'
1
```
I "think" it may have something to do with an \_\_asm int 3 call but I cannot be sure. Has anyone had this problem before? If so, how did you fix it? Am i stuck with MFC's memory tracking? I really hope not because it will make my libraries a lot less cross platform :(
Any help would be hugely appreciated! | I've come up with one method which involves using the /FORCE:MULTIPLE command line to force it to use mine instead of the MFC one. It all seems to be working quite nicely. I can, now, even track "mallocs" and "new"s performed by functions not owned by me :)
If anyone has any better solutions then please post them but for now this seems to solve my problem :) | I tried messing with the `_AFX_NO_DAO_SUPPORT` macro in the past and all it did was lead to endless crashes. I eventually came across this article:
[PRB: Problems Occur When Defining `_AFX_NO_XXX`](http://support.microsoft.com/kb/140751)
It doesn't specifically list the one you are attempting to use, but it may still apply. | #define _AFX_NO_DEBUG_CRT causes a stream of compilation errors | [
"",
"c++",
"visual-studio-2008",
"mfc",
""
] |
I draw two spheres in 3d WPF which has points like Point3D(0,0,0) and Point3D(-1.0,1.0,2.0) with the radius is 0.10
Now i want to draw a Cylinder joining these spheres, the only thing i have for this is radius 0.02. I want to know how to calculate the 3d point, height, direction etc for this cylinder.
I tried by finding the midpoint btw sphere points, it's placing the cylinder in the middle of those two spheres but not in the right direction. I want to rotate the cylinder in the right angle. I used Vector3D.angleBetween(v1,v2) to find the angle it's giving me "NaN". I put the code which i am using in below.
```
Vector3D v1 = new Vector3D(0, 0, 0);
Vector3D v2 = new Vector3D(1.0, -1.0, 2.0);
Vector3D center = v1+ v2/2;
Vector3D axis = Vector3D.CrossProduct(v1, v2);
double angle = Vector3D.AngleBetween(v1, v2);
AxisAngleRotation3D axisAngle = new AxisAngleRotation3D(axis, angle);
RotateTransform3D myRotateTransform = new RotateTransform3D(axisAngle, center);
center.X = myRotateTransform.CenterX;
center.Y = myRotateTransform.CenterY;
center.Z = myRotateTransform.CenterZ;
```
[EDIT]
First of all thank you so much for the response. I am having some issues with this code it's working good with your example. but with my points
It's not drawing the cylinder btw the two circle points in a right direction and also not until the end point (it's only connecting to second point) One more thing,
if the mid point of the Z-axis is (midpoint.Z = 0), it not even drawing the cylinder.
I am just wondering, is it because of the way i am drawing my circle. Please take a look
```
public ModelVisual3D CreateSphere(Point3D center, double radius, int u, int v, Color color)
{
Model3DGroup spear = new Model3DGroup();
if (u < 2 || v < 2)
return null;
Point3D[,] pts = new Point3D[u, v];
for (int i = 0; i < u; i++)
{
for (int j = 0; j < v; j++)
{
pts[i, j] = GetPosition(radius,
i * 180 / (u - 1), j * 360 / (v - 1));
pts[i, j] += (Vector3D)center;
}
}
Point3D[] p = new Point3D[4];
for (int i = 0; i < u - 1; i++)
{
for (int j = 0; j < v - 1; j++)
{
p[0] = pts[i, j];
p[1] = pts[i + 1, j];
p[2] = pts[i + 1, j + 1];
p[3] = pts[i, j + 1];
spear.Children.Add(CreateTriangleModel(p[0], p[1], p[2], color));
spear.Children.Add(CreateTriangleModel(p[2], p[3], p[0], color));
}
}
ModelVisual3D model = new ModelVisual3D();
model.Content = spear;
return model;
}
private Point3D GetPosition(double radius, double theta, double phi)
{
Point3D pt = new Point3D();
double snt = Math.Sin(theta * Math.PI / 180);
double cnt = Math.Cos(theta * Math.PI / 180);
double snp = Math.Sin(phi * Math.PI / 180);
double cnp = Math.Cos(phi * Math.PI / 180);
pt.X = radius * snt * cnp;
pt.Y = radius * cnt;
pt.Z = -radius * snt * snp;
return pt;
}
public Model3DGroup CreateTriangleFace(Point3D p0, Point3D p1, Point3D p2, Color color)
{
MeshGeometry3D mesh = new MeshGeometry3D();
mesh.Positions.Add(p0);
mesh.Positions.Add(p1);
mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);
Vector3D normal = VectorHelper.CalcNormal(p0, p1, p2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
Material material = new DiffuseMaterial(new SolidColorBrush(color));
GeometryModel3D model = new GeometryModel3D(mesh, material);
Model3DGroup group = new Model3DGroup();
group.Children.Add(model);
return group;
}
private class VectorHelper
{
public static Vector3D CalcNormal(Point3D p0, Point3D p1, Point3D p2)
{
Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3D v1 = new Vector3D( p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}
}
```
almost same as your code>
```
my sample point are :
p1 = Point3D(0,0,0)
p2= Point3D(-1.0, 1.0, 2.0)
p3= Point3D(-1.0, 1.0, 2.0)
p4 =Point3D(1.0, -1.0, 2.0)
```
i want to draw cylinders btw p1 to p2 ,p1 to p3, p1 to p4
p2 to p3 , p2 to p4
Please Let me know if you need any more clarification, I have to get this out.
Thanks for all your time. | I've integrated your sphere code with my example and it works fine - the cylinder connects both spheres.
Heres the code ...
Cheers, Andy
ViewPort as before ...
```
<Window x:Class="wpfspin.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Viewport3D Name="mainViewport" ClipToBounds="True" HorizontalAlignment="Stretch" Height="300">
<Viewport3D.Camera>
<PerspectiveCamera
LookDirection="0,0,-20"
UpDirection="0,1,0"
Position="0,0,100"
/>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup x:Name="group3d">
<SpotLight Position="30,30,30" x:Name="mySpotLight" Color="Yellow" InnerConeAngle="100" OuterConeAngle="1000" Range="100" />
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</StackPanel>
```
... and heres the code behind ...
```
using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
namespace wpfspin
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Init(new Point3D(0, 0, 30), new Point3D(0, 0, -30));
}
private Timer _timer;
private readonly List<ModelVisual3D> _models = new List<ModelVisual3D>();
private double _angle;
public void Init(Point3D firstPoint, Point3D secondPoint)
{
var midPoint = firstPoint - secondPoint;
_models.Add(CreateSphere(firstPoint, 10, 10, 10, Colors.AliceBlue ));
_models.Add(CreateSphere(secondPoint, 10, 10, 10, Colors.AliceBlue));
_models.Add(GetCylinder(GetSurfaceMaterial(Colors.Red), secondPoint, 2, midPoint.Z));
_models.ForEach(x => mainViewport.Children.Add(x));
_timer = new Timer(10);
_timer.Elapsed += TimerElapsed;
_timer.Enabled = true;
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<double>(Transform), 0.5d);
}
public MaterialGroup GetSurfaceMaterial(Color colour)
{
var materialGroup = new MaterialGroup();
var emmMat = new EmissiveMaterial(new SolidColorBrush(colour));
materialGroup.Children.Add(emmMat);
materialGroup.Children.Add(new DiffuseMaterial(new SolidColorBrush(colour)));
var specMat = new SpecularMaterial(new SolidColorBrush(Colors.White), 30);
materialGroup.Children.Add(specMat);
return materialGroup;
}
public ModelVisual3D GetCube(MaterialGroup materialGroup, Point3D point, Size3D size)
{
var farPoint = new Point3D(point.X - (size.X / 2), point.Y - (size.Y / 2), point.Z - (size.Z / 2));
var nearPoint = new Point3D(point.X + (size.X / 2), point.Y + (size.Y / 2), point.Z + (size.Z / 2));
var cube = new Model3DGroup();
var p0 = new Point3D(farPoint.X, farPoint.Y, farPoint.Z);
var p1 = new Point3D(nearPoint.X, farPoint.Y, farPoint.Z);
var p2 = new Point3D(nearPoint.X, farPoint.Y, nearPoint.Z);
var p3 = new Point3D(farPoint.X, farPoint.Y, nearPoint.Z);
var p4 = new Point3D(farPoint.X, nearPoint.Y, farPoint.Z);
var p5 = new Point3D(nearPoint.X, nearPoint.Y, farPoint.Z);
var p6 = new Point3D(nearPoint.X, nearPoint.Y, nearPoint.Z);
var p7 = new Point3D(farPoint.X, nearPoint.Y, nearPoint.Z);
//front side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p3, p2, p6));
cube.Children.Add(CreateTriangleModel(materialGroup, p3, p6, p7));
//right side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p1, p5));
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p5, p6));
//back side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p1, p0, p4));
cube.Children.Add(CreateTriangleModel(materialGroup, p1, p4, p5));
//left side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p0, p3, p7));
cube.Children.Add(CreateTriangleModel(materialGroup, p0, p7, p4));
//top side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p7, p6, p5));
cube.Children.Add(CreateTriangleModel(materialGroup, p7, p5, p4));
//bottom side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p3, p0));
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p0, p1));
var model = new ModelVisual3D();
model.Content = cube;
return model;
}
private Model3DGroup CreateTriangleModel(MaterialGroup materialGroup, Triangle triangle)
{
return CreateTriangleModel(materialGroup, triangle.P0, triangle.P1, triangle.P2);
}
private Model3DGroup CreateTriangleModel(Material material, Point3D p0, Point3D p1, Point3D p2)
{
var mesh = new MeshGeometry3D();
mesh.Positions.Add(p0);
mesh.Positions.Add(p1);
mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);
var normal = CalculateNormal(p0, p1, p2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
var model = new GeometryModel3D(mesh, material);
var group = new Model3DGroup();
group.Children.Add(model);
return group;
}
private Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2)
{
var v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
var v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}
void Transform(double adjustBy)
{
_angle += adjustBy;
var rotateTransform3D = new RotateTransform3D { CenterX = 0, CenterZ = 0 };
var axisAngleRotation3D = new AxisAngleRotation3D { Axis = new Vector3D(1, 1, 1), Angle = _angle };
rotateTransform3D.Rotation = axisAngleRotation3D;
var myTransform3DGroup = new Transform3DGroup();
myTransform3DGroup.Children.Add(rotateTransform3D);
_models.ForEach(x => x.Transform = myTransform3DGroup);
}
public ModelVisual3D GetCylinder(MaterialGroup materialGroup, Point3D midPoint, double radius, double depth)
{
var cylinder = new Model3DGroup();
var nearCircle = new CircleAssitor();
var farCircle = new CircleAssitor();
var twoPi = Math.PI * 2;
var firstPass = true;
double x;
double y;
var increment = 0.1d;
for (double i = 0; i < twoPi + increment; i = i + increment)
{
x = (radius * Math.Cos(i));
y = (-radius * Math.Sin(i));
farCircle.CurrentTriangle.P0 = midPoint;
farCircle.CurrentTriangle.P1 = farCircle.LastPoint;
farCircle.CurrentTriangle.P2 = new Point3D(x + midPoint.X, y + midPoint.Y, midPoint.Z);
nearCircle.CurrentTriangle = farCircle.CurrentTriangle.Clone(depth, true);
if (!firstPass)
{
cylinder.Children.Add(CreateTriangleModel(materialGroup, farCircle.CurrentTriangle));
cylinder.Children.Add(CreateTriangleModel(materialGroup, nearCircle.CurrentTriangle));
cylinder.Children.Add(CreateTriangleModel(materialGroup, farCircle.CurrentTriangle.P2, farCircle.CurrentTriangle.P1, nearCircle.CurrentTriangle.P2));
cylinder.Children.Add(CreateTriangleModel(materialGroup, nearCircle.CurrentTriangle.P2, nearCircle.CurrentTriangle.P1, farCircle.CurrentTriangle.P2));
}
else
{
farCircle.FirstPoint = farCircle.CurrentTriangle.P1;
nearCircle.FirstPoint = nearCircle.CurrentTriangle.P1;
firstPass = false;
}
farCircle.LastPoint = farCircle.CurrentTriangle.P2;
nearCircle.LastPoint = nearCircle.CurrentTriangle.P2;
}
var model = new ModelVisual3D { Content = cylinder };
return model;
}
public ModelVisual3D CreateSphere(Point3D center, double radius, int u, int v, Color color)
{
Model3DGroup spear = new Model3DGroup();
if (u < 2 || v < 2)
return null;
Point3D[,] pts = new Point3D[u, v];
for (int i = 0; i < u; i++)
{
for (int j = 0; j < v; j++)
{
pts[i, j] = GetPosition(radius,
i * 180 / (u - 1), j * 360 / (v - 1));
pts[i, j] += (Vector3D)center;
}
}
Point3D[] p = new Point3D[4];
for (int i = 0; i < u - 1; i++)
{
for (int j = 0; j < v - 1; j++)
{
p[0] = pts[i, j];
p[1] = pts[i + 1, j];
p[2] = pts[i + 1, j + 1];
p[3] = pts[i, j + 1];
spear.Children.Add(CreateTriangleFace(p[0], p[1], p[2], color));
spear.Children.Add(CreateTriangleFace(p[2], p[3], p[0], color));
}
}
ModelVisual3D model = new ModelVisual3D();
model.Content = spear;
return model;
}
private Point3D GetPosition(double radius, double theta, double phi)
{
Point3D pt = new Point3D();
double snt = Math.Sin(theta * Math.PI / 180);
double cnt = Math.Cos(theta * Math.PI / 180);
double snp = Math.Sin(phi * Math.PI / 180);
double cnp = Math.Cos(phi * Math.PI / 180);
pt.X = radius * snt * cnp;
pt.Y = radius * cnt;
pt.Z = -radius * snt * snp;
return pt;
}
public Model3DGroup CreateTriangleFace(Point3D p0, Point3D p1, Point3D p2, Color color)
{
MeshGeometry3D mesh = new MeshGeometry3D(); mesh.Positions.Add(p0); mesh.Positions.Add(p1); mesh.Positions.Add(p2); mesh.TriangleIndices.Add(0); mesh.TriangleIndices.Add(1); mesh.TriangleIndices.Add(2);
Vector3D normal = VectorHelper.CalcNormal(p0, p1, p2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
Material material = new DiffuseMaterial(
new SolidColorBrush(color));
GeometryModel3D model = new GeometryModel3D(
mesh, material);
Model3DGroup group = new Model3DGroup();
group.Children.Add(model);
return group;
}
private class VectorHelper
{
public static Vector3D CalcNormal(Point3D p0, Point3D p1, Point3D p2)
{
Vector3D v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
Vector3D v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}
}
}
public class CircleAssitor
{
public CircleAssitor()
{
CurrentTriangle = new Triangle();
}
public Point3D FirstPoint { get; set; }
public Point3D LastPoint { get; set; }
public Triangle CurrentTriangle { get; set; }
}
public class Triangle
{
public Point3D P0 { get; set; }
public Point3D P1 { get; set; }
public Point3D P2 { get; set; }
public Triangle Clone(double z, bool switchP1andP2)
{
var newTriangle = new Triangle();
newTriangle.P0 = GetPointAdjustedBy(this.P0, new Point3D(0, 0, z));
var point1 = GetPointAdjustedBy(this.P1, new Point3D(0, 0, z));
var point2 = GetPointAdjustedBy(this.P2, new Point3D(0, 0, z));
if (!switchP1andP2)
{
newTriangle.P1 = point1;
newTriangle.P2 = point2;
}
else
{
newTriangle.P1 = point2;
newTriangle.P2 = point1;
}
return newTriangle;
}
private Point3D GetPointAdjustedBy(Point3D point, Point3D adjustBy)
{
var newPoint = new Point3D { X = point.X, Y = point.Y, Z = point.Z };
newPoint.Offset(adjustBy.X, adjustBy.Y, adjustBy.Z);
return newPoint;
}
}
```
} | I don't know whether this will be of use to you, but you commented on some similar code I recently posted, asking for assistance - so I thought I'd convert that code into two objects, connected by a cylinder spinning around in 3D space - the Init() method takes two points, creates 10x10x10 cubes at the points and then connects them with a cylinder.
I think this is roughly what your trying to achieve, though I admit that my example is a little contrived, (you can only change the Z axis on each of the two points in!!!), but hopefully you'll get something from it!
Sorry the code is a bit of a mess but I've compiled it from a number of my classes to get it into one easy cut and paste-able lump!
Anyway, hope this helps ...
Heres the XAML ... this just sets up the ViewPort and light source ...
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<StackPanel>
<Viewport3D Name="mainViewport" ClipToBounds="True" HorizontalAlignment="Stretch" Height="300">
<Viewport3D.Camera>
<PerspectiveCamera
LookDirection="0,0,-20"
UpDirection="0,1,0"
Position="0,0,100"
/>
</Viewport3D.Camera>
<ModelVisual3D>
<ModelVisual3D.Content>
<Model3DGroup x:Name="group3d">
<SpotLight Position="30,30,30" x:Name="mySpotLight" Color="Yellow" InnerConeAngle="100" OuterConeAngle="1000" Range="100" />
</Model3DGroup>
</ModelVisual3D.Content>
</ModelVisual3D>
</Viewport3D>
</StackPanel>
```
... and heres the code behind ...
```
using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using System.Windows.Threading;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
Init(new Point3D(0, 0, 30), new Point3D(0,0,-30));
}
private Timer _timer;
private readonly List<ModelVisual3D> _models = new List<ModelVisual3D>();
private double _angle;
public void Init(Point3D firstPoint, Point3D secondPoint)
{
var midPoint = firstPoint - secondPoint;
var size = new Size3D(10,10,10);
_models.Add(GetCube(GetSurfaceMaterial(Colors.Green), firstPoint, size));
_models.Add(GetCube(GetSurfaceMaterial(Colors.Green), secondPoint, size));
_models.Add(GetCylinder(GetSurfaceMaterial(Colors.Red), secondPoint, 2, midPoint.Z));
_models.ForEach(x => mainViewport.Children.Add(x));
_timer = new Timer(10);
_timer.Elapsed += TimerElapsed;
_timer.Enabled = true;
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<double>(Transform), 0.5d);
}
public MaterialGroup GetSurfaceMaterial(Color colour)
{
var materialGroup = new MaterialGroup();
var emmMat = new EmissiveMaterial(new SolidColorBrush(colour));
materialGroup.Children.Add(emmMat);
materialGroup.Children.Add(new DiffuseMaterial(new SolidColorBrush(colour)));
var specMat = new SpecularMaterial(new SolidColorBrush(Colors.White), 30);
materialGroup.Children.Add(specMat);
return materialGroup;
}
public ModelVisual3D GetCube(MaterialGroup materialGroup, Point3D point, Size3D size)
{
var farPoint = new Point3D(point.X - (size.X / 2), point.Y - (size.Y / 2), point.Z - (size.Z / 2));
var nearPoint = new Point3D(point.X + (size.X / 2), point.Y + (size.Y / 2), point.Z + (size.Z / 2));
var cube = new Model3DGroup();
var p0 = new Point3D(farPoint.X, farPoint.Y, farPoint.Z);
var p1 = new Point3D(nearPoint.X, farPoint.Y, farPoint.Z);
var p2 = new Point3D(nearPoint.X, farPoint.Y, nearPoint.Z);
var p3 = new Point3D(farPoint.X, farPoint.Y, nearPoint.Z);
var p4 = new Point3D(farPoint.X, nearPoint.Y, farPoint.Z);
var p5 = new Point3D(nearPoint.X, nearPoint.Y, farPoint.Z);
var p6 = new Point3D(nearPoint.X, nearPoint.Y, nearPoint.Z);
var p7 = new Point3D(farPoint.X, nearPoint.Y, nearPoint.Z);
//front side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p3, p2, p6));
cube.Children.Add(CreateTriangleModel(materialGroup, p3, p6, p7));
//right side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p1, p5));
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p5, p6));
//back side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p1, p0, p4));
cube.Children.Add(CreateTriangleModel(materialGroup, p1, p4, p5));
//left side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p0, p3, p7));
cube.Children.Add(CreateTriangleModel(materialGroup, p0, p7, p4));
//top side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p7, p6, p5));
cube.Children.Add(CreateTriangleModel(materialGroup, p7, p5, p4));
//bottom side triangles
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p3, p0));
cube.Children.Add(CreateTriangleModel(materialGroup, p2, p0, p1));
var model = new ModelVisual3D();
model.Content = cube;
return model;
}
private Model3DGroup CreateTriangleModel(MaterialGroup materialGroup, Triangle triangle)
{
return CreateTriangleModel(materialGroup, triangle.P0, triangle.P1, triangle.P2);
}
private Model3DGroup CreateTriangleModel(Material material, Point3D p0, Point3D p1, Point3D p2)
{
var mesh = new MeshGeometry3D();
mesh.Positions.Add(p0);
mesh.Positions.Add(p1);
mesh.Positions.Add(p2);
mesh.TriangleIndices.Add(0);
mesh.TriangleIndices.Add(1);
mesh.TriangleIndices.Add(2);
var normal = CalculateNormal(p0, p1, p2);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
mesh.Normals.Add(normal);
var model = new GeometryModel3D(mesh, material);
var group = new Model3DGroup();
group.Children.Add(model);
return group;
}
private Vector3D CalculateNormal(Point3D p0, Point3D p1, Point3D p2)
{
var v0 = new Vector3D(p1.X - p0.X, p1.Y - p0.Y, p1.Z - p0.Z);
var v1 = new Vector3D(p2.X - p1.X, p2.Y - p1.Y, p2.Z - p1.Z);
return Vector3D.CrossProduct(v0, v1);
}
void Transform(double adjustBy)
{
_angle += adjustBy;
var rotateTransform3D = new RotateTransform3D {CenterX = 0, CenterZ = 0};
var axisAngleRotation3D = new AxisAngleRotation3D {Axis = new Vector3D(1, 1, 1), Angle = _angle};
rotateTransform3D.Rotation = axisAngleRotation3D;
var myTransform3DGroup = new Transform3DGroup();
myTransform3DGroup.Children.Add(rotateTransform3D);
_models.ForEach(x => x.Transform = myTransform3DGroup);
}
public ModelVisual3D GetCylinder(MaterialGroup materialGroup, Point3D midPoint, double radius, double depth)
{
var cylinder = new Model3DGroup();
var nearCircle = new CircleAssitor();
var farCircle = new CircleAssitor();
var twoPi = Math.PI * 2;
var firstPass = true;
double x;
double y;
var increment = 0.1d;
for (double i = 0; i < twoPi + increment; i = i + increment)
{
x = (radius * Math.Cos(i));
y = (-radius * Math.Sin(i));
farCircle.CurrentTriangle.P0 = midPoint;
farCircle.CurrentTriangle.P1 = farCircle.LastPoint;
farCircle.CurrentTriangle.P2 = new Point3D(x + midPoint.X, y + midPoint.Y, midPoint.Z);
nearCircle.CurrentTriangle = farCircle.CurrentTriangle.Clone(depth, true);
if (!firstPass)
{
cylinder.Children.Add(CreateTriangleModel(materialGroup, farCircle.CurrentTriangle));
cylinder.Children.Add(CreateTriangleModel(materialGroup, nearCircle.CurrentTriangle));
cylinder.Children.Add(CreateTriangleModel(materialGroup, farCircle.CurrentTriangle.P2, farCircle.CurrentTriangle.P1, nearCircle.CurrentTriangle.P2));
cylinder.Children.Add(CreateTriangleModel(materialGroup, nearCircle.CurrentTriangle.P2, nearCircle.CurrentTriangle.P1, farCircle.CurrentTriangle.P2));
}
else
{
farCircle.FirstPoint = farCircle.CurrentTriangle.P1;
nearCircle.FirstPoint = nearCircle.CurrentTriangle.P1;
firstPass = false;
}
farCircle.LastPoint = farCircle.CurrentTriangle.P2;
nearCircle.LastPoint = nearCircle.CurrentTriangle.P2;
}
var model = new ModelVisual3D {Content = cylinder};
return model;
}
}
public class CircleAssitor
{
public CircleAssitor()
{
CurrentTriangle = new Triangle();
}
public Point3D FirstPoint { get; set; }
public Point3D LastPoint { get; set; }
public Triangle CurrentTriangle { get; set; }
}
public class Triangle
{
public Point3D P0 { get; set; }
public Point3D P1 { get; set; }
public Point3D P2 { get; set; }
public Triangle Clone(double z, bool switchP1andP2)
{
var newTriangle = new Triangle();
newTriangle.P0 = GetPointAdjustedBy(this.P0, new Point3D(0, 0, z));
var point1 = GetPointAdjustedBy(this.P1, new Point3D(0, 0, z));
var point2 = GetPointAdjustedBy(this.P2, new Point3D(0, 0, z));
if (!switchP1andP2)
{
newTriangle.P1 = point1;
newTriangle.P2 = point2;
}
else
{
newTriangle.P1 = point2;
newTriangle.P2 = point1;
}
return newTriangle;
}
private Point3D GetPointAdjustedBy(Point3D point, Point3D adjustBy)
{
var newPoint = new Point3D { X = point.X, Y = point.Y, Z = point.Z };
newPoint.Offset(adjustBy.X, adjustBy.Y, adjustBy.Z);
return newPoint;
}
}
}
``` | 3D transformation WPF | [
"",
"c#",
"wpf",
"3d",
""
] |
I have a function that takes a pointer to a pointer an as argument.
```
func(double **arr, int i);
```
where in the main function the array is defined as follows:
```
double arr[][] = //some initialization here;
```
How can I call this function from my main code. I tried the following but it gives an error
```
func (&arr);
```
Doesn't work. Any help would be much appreciated.
Thanks | A `double **p` is not the same thing as a `double[][] a`, so you can't pass one as the other.
In particular the two-dimensional array variable is a (single!) block of memory containing doubles which you can access with the `[][]` syntax. This *requires* that the compiler know the dimension of the array, so that it can compute the correct offset to each element. It can also decay transparently to an pointer to that block of memory, but doing so loses the understanding of how to access that memory as a two dimensional array: it becomes effectively a pointer to double.
```
+----+ +---------+---------+---------+
| (a---------->) | a[0][0] | a[0][1] | a[0][2] | ...
+----+ +---------+---------+---------+
| a[1][0] | a[1][2] | ...
+---------+---------+
...
```
The thing expected by the function is a pointer to a block of memory which contains one or more pointers to additional blocks of memory containing doubles.
```
+---+ +------+ +---------+---------+
| p-------->| p[0]------->| p[0][0] | p[0][3] | ...
+---+ +------+ +---------+---------+
| p[1]--\
+------+ \ +---------+---------+
... --->| p[1][0] | p[1][4] | ...
+---------+---------+
```
While the syntax looks similar, these two structures have totally different semantics.
---
For a more complete discussion, see [my answer](https://stackoverflow.com/questions/917783/how-do-i-work-with-dynamic-multi-dimensional-arrays-in-c/918121#918121) to a [previous questions](https://stackoverflow.com/questions/917783/how-do-i-work-with-dynamic-multi-dimensional-arrays-in-c) (which actually address c, but the issues are the same). | The type of `arr` is `double[X][Y]` - that is, an array of X arrays of Y doubles - where `X` and `Y` depend on your initializers. This is *not* the same as pointer type. However, according to C conversion rules, an array can decay into a pointer to its element. In your case, the type resulting from such decay will be double(\*)[Y] - a pointer to an array of Y doubles. Note that this is a *pointer to array*, not an *array of pointers*, so it will not decay any further. At this point, you get a type mismatch, since your function expects `double**`.
The correct way to handle this is to treat the array as single-dimensional, and pass width along. So:
```
void func(double* arr, int w) {
// arr[2][3]
arr[2*w + 3] = ...;
}
double x[6][8] = { ... };
func(&x[0][0], 8);
```
In C++ in particular, if you always have statically allocated arrays of well-known (but different) types, you may be able to use templates and references like this:
```
template <int W, int H>
inline void func(const double (&arr)[W][H]) {
arr[2][3] = ...;
}
double x[6][8] = { ... };
func(x); // W and H are deduced automatically
```
However, this won't work when all you have is a pointer (e.g. when the array is `new`-allocated, and its size is calculated at runtime). For the most general case, you should use C++ containers instead. With standard library only, one typically uses vector of vectors:
```
#include <vector>
void func(std::vector<std::vector<double> > arr) {
arr[2][3] = ...;
}
std::vector<std::vector<double> > x(6, std::vector<double>(8));
x[0][0] = ...;
...
func(x);
```
If you can use Boost, it has a very nice MultiArray library in it:
```
void func(boost::multi_array<double, 2> arr) { // 2 means "2-dimensional"
arr[2][3] = ...;
}
boost::multi_array<double, 2> x(boost::extents[6][8]);
x[0][0] = ...;
...
func(x);
```
**[EDIT]** you say that you cannot change the definition of your function. If so, then it really is a function treating its argument as an array of pointers, so you should just allocate your data structure accordingly. For example:
```
double x1[8] = { 1, 2, ... };
double x2[8] = { 3, 4, ... };
...
double* x[6] = { x1, x2, ... };
func(x);
``` | 2D arrays with C++ | [
"",
"c++",
"multidimensional-array",
""
] |
This might be a duplicate ([question](https://stackoverflow.com/questions/824055/how-to-securely-store-database-connection-details "question")) but I am looking specifically for the .NET best practice.
How to store database connection strings, username and password etc. in a safe way? Is an encrypted app.config best in most cases?
I would also like to be able to set the password in the config file and then have it encrypted as soon as the application starts. (I am not asking for a solution as I have solved this before, I'm just looking for best practise(s)).
I'm also interested in alternative solutions that you have good experiences with. | I think the best practice is to use integrated security if possible, for 2 reasons... It is the easiest solution to manage and it is the easiest solution to get right.
If for some reason you can't use integrated security and you have to use username and password encrypt them using something like the [Enterprise Library](http://www.codeplex.com/entlib)'s Config Manager to encrypt sections of your web.config. | There are several things that we should know about protecting connection strings:
<http://msdn.microsoft.com/en-us/library/89211k9b.aspx>
In my view the best way to store them (the one that combines flexibility and security) is
"Encrypting Configuration File Sections Using Protected Configuration":
<http://msdn.microsoft.com/en-us/library/ms254494.aspx> | What is the best practice for storing database connection details in .NET? | [
"",
"c#",
".net",
"database",
".net-3.5",
""
] |
I would like to filter this list,
```
[0, 1, 1, 2, 2]
```
to only leave
```
[0]
```
I'm struggling to do it in a 'pythonic' way. Is it possible without nested loops? | Here's another dictionary oriented way:
```
l = [0, 1, 1, 2, 2]
d = {}
for i in l: d[i] = i in d
[k for k in d if not d[k]] # unordered, loop over the dictionary
[k for k in l if not d[k]] # ordered, loop over the original list
``` | You'll need two loops (or equivalently a loop and a listcomp, like below), but not nested ones:
```
import collections
d = collections.defaultdict(int)
for x in L: d[x] += 1
L[:] = [x for x in L if d[x] == 1]
```
This solution assumes that the list items are *hashable*, that is, that they're usable as indices into dicts, members of sets, etc.
The OP indicates they care about object IDENTITY and not VALUE (so for example two sublists both worth `[1,2,3` which are equal but may not be identical would not be considered duplicates). If that's indeed the case then this code is usable, just replace `d[x]` with `d[id(x)]` in both occurrences and it will work for ANY types of objects in list L.
Mutable objects (lists, dicts, sets, ...) are typically not hashable and therefore cannot be used in such ways. User-defined objects are by default hashable (with `hash(x) == id(x)`) unless their class defines comparison special methods (`__eq__`, `__cmp__`, ...) in which case they're hashable if and only if their class also defines a `__hash__` method.
If list L's items are not hashable, but *are* comparable for inequality (and therefore sortable), and you don't care about their order within the list, you can perform the task in time `O(N log N)` by first sorting the list and then applying `itertools.groupby` (almost but not quite in the way another answer suggested).
Other approaches, of gradually decreasing perfomance and increasing generality, can deal with unhashable sortables when you DO care about the list's original order (make a sorted copy and in a second loop check out repetitions on it with the help of `bisect` -- also O(N log N) but a tad slower), and with objects whose only applicable property is that they're comparable for equality (no way to avoid the dreaded O(N\*\*2) performance in that maximally general case).
If the OP can clarify which case applies to his specific problem I'll be glad to help (and in particular, if the objects in his are ARE hashable, the code I've already given above should suffice;-). | Filter a list to only leave objects that occur once | [
"",
"python",
"list",
"filter",
""
] |
I am interested to trigger a certain action upon receiving an email from specific
address with specific subject. In order to be able to do so I need to implement
monitoring of my mailbox, checking every incoming mail (in particular, i use gmail).
what is the easiest way to do that? | Gmail provides the ability to connect over POP, which you can turn on in the gmail settings panel. Python can make connections over POP pretty easily:
```
import poplib
from email import parser
pop_conn = poplib.POP3_SSL('pop.gmail.com')
pop_conn.user('username')
pop_conn.pass_('password')
#Get messages from server:
messages = [pop_conn.retr(i) for i in range(1, len(pop_conn.list()[1]) + 1)]
# Concat message pieces:
messages = ["\n".join(mssg[1]) for mssg in messages]
#Parse message intom an email object:
messages = [parser.Parser().parsestr(mssg) for mssg in messages]
for message in messages:
print message['subject']
pop_conn.quit()
```
You would just need to run this script as a cron job. Not sure what platform you're on so YMMV as to how that's done. | Gmail provides an atom [feed](https://mail.google.com/mail/feed/atom) for new email messages. You should be able to monitor this by authenticating with py cURL (or some other net library) and pulling down the feed. Making a GET request for each new message should mark it as read, so you won't have to keep track of which emails you've read. | Checking email with Python | [
"",
"python",
"email",
""
] |
How do I implement a progress bar and backgroundworker for database calls in C#?
I do have some methods that deal with large amounts of data. They are relatively long running operations, so I want to implement a progress bar to let the user know that something is actually happening.
I thought of using progress bar or status strip label, but since there is a single UI thread, the thread where the database-dealing methods are executed, UI controls are not updated, making the progress bar or status strip label are useless to me.
I've already seen some examples, but they deal with for-loops, ex:
```
for(int i = 0; i < count; i++)
{
System.Threading.Thread.Sleep(70);
// ... do analysis ...
bgWorker.ReportProgress((100 * i) / count);
}
private void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = Math.Min(e.ProgressPercentage, 100);
}
```
I'm looking for better examples. | Some people may not like it, but this is what I do:
```
private void StartBackgroundWork() {
if (Application.RenderWithVisualStyles)
progressBar.Style = ProgressBarStyle.Marquee;
else {
progressBar.Style = ProgressBarStyle.Continuous;
progressBar.Maximum = 100;
progressBar.Value = 0;
timer.Enabled = true;
}
backgroundWorker.RunWorkerAsync();
}
private void timer_Tick(object sender, EventArgs e) {
if (progressBar.Value < progressBar.Maximum)
progressBar.Increment(5);
else
progressBar.Value = progressBar.Minimum;
}
```
The Marquee style requires VisualStyles to be enabled, but it continuously scrolls on its own without needing to be updated. I use that for database operations that don't report their progress. | If you can't know the progress you should not fake it by abusing a progress bar, instead just display some sort of busy icon like en.wikipedia.org/wiki/Throbber#Spinning\_wheel Show it when starting the task and hide it when it's finished. That would make for a more "honest" GUI. | How do I implement a progress bar in C#? | [
"",
"c#",
".net",
"winforms",
"progress-bar",
""
] |
I've decided on PostSharp (indistinguishable from magic) to read attributes and [memoize functions](http://en.wikipedia.org/wiki/Memoization). The hash of the function call will be the key and the cached (in [Velocity](http://msdn.microsoft.com/en-us/data/cc655792.aspx)) result will be returned instead of calling the function again. Easy peasy, mac-and-cheesy.
I've already [given up](https://stackoverflow.com/questions/1194898/how-can-i-programmatically-detect-side-effects-compile-time-or-run-time) on being able to detect side effects in decorated functions, which turned out to be a "hard problem", even for the experts, which I am certainly not. Next, I've got to figure out what other functions are candidates for memoization.
* What about methods that take complex reference types as parameters?
* What about methods that depend on data inside of the instances they're called from?
ActiveRecord-esque data objects come to mind on that last one.
Am I going to have to refactor week-old code to support memoization? | You can only memoize a function if all of its inputs are value types or immutable reference types, if it returns either a value type or a new instance of a reference type, and if it has no side effects. Period.
Memoization depends on a deterministic mapping between inputs and outputs. Every call to `F(a, b, c)` in which a, b, and c contain the same values must return the same result in order for memoization to be possible.
If a parameter's a reference type, then even though its value doesn't change, multiple calls to the function using it may produce a different result. A trivial example:
```
public int MyFunction(MyType t)
{
return t.Value;
}
Console.WriteLine(MyFunction(t));
t.Value++;
Console.WriteLine(MyFunction(t));
```
Similarly, if a function depends on a value external to it, then multiple calls to that function with the same parameters can return different results:
```
int Value = 0;
public int MyFunction(int input)
{
return Value;
}
Console.WriteLine(MyFunction(1));
Value++;
Console.WriteLine(MyFunction(1));
```
And heaven help you if your memoized function does something other than return a value or a new reference type:
```
int Value = 0;
public int MyFunction(int input)
{
Value++;
return input;
}
```
If you call that function 10 times, `Value` will be 10. If you refactor it to use memoization and then call it 10 times, `Value` will be 1.
You can start going down the path of figuring out how to memoize state, so that you can phony up a function that memoizes a reference type. But what you're really memoizing is the set of values that the function works on. You can similarly hack a memoized function that has side effects so that its side effects occur before the memoization. But this is all begging for trouble.
If you want to implement memoization into a function that takes a reference type, the proper approach is to refactor out the part of the function that only works on value types, and memoize that function, e.g.:
```
public int MyFunction(MyType t)
{
return t.Value + 1;
}
```
to this:
```
public int MyFunction(MyType t)
{
return MyMemoizableFunction(t.Value);
}
private int MyMemoizableFunction(int value)
{
return value + 1;
}
```
Any other approach to implementing memoization that you take either a) does the same thing, through more obscure means, or b) won't work. | Well, any function, theoretically, is a candidate for memoization. However, remember that memoization is all about trading space for speed -
In general, this means that, the more state a function requires or depends on in order to compute an answer, the higher the space cost, which reduces the desirability to memoize the method.
Both of your examples are basically cases where more state would need to be saved. This has two side effects.
First, this will require a lot more memory space in order to memoize the function, since more information will need to be saved.
Second, this will potentially slow down the memoized function, since the larger the space, the higher the cost of the lookup of the answer, as well as the higher the cost in finding whether or not a result was previously saved.
In general, I tend to only consider functions that have few possible inputs and low storage requirements, unless there is a very high cost in calculating the answer.
I acknoledge that this is vague, but this is part of the "artistry" in architecture. There's no "right" answer without implementing both options (memozied and non-memoized functions), profiling, and measuring. | What kinds of functions are candidates for memoization? | [
"",
"c#",
"memoization",
""
] |
How can I increase my proficiency in programming? I have a grasp of the basics of C#, but don't feel too confident about my ability. | * Code something in C#
* Read C# Code and try to understand it.
* Read a C# Book (and please none of the C# in 21 Days books)
**The confidence comes with the experience.** | Read Stack Overflow every day :)
Seriously. Try to solve interesting problems. Even if you don't post your solution, come back later and see if other people came up with something similar, why their solution might be different, etc. | Improve proficiency in programming | [
"",
"c#",
"language-agnostic",
""
] |
Looking at some code I noticed that another dev had changed every instance of true to !false.
Why would you do that?
thx | There is no good reason to write !false instead of true.
Bad reasons could include obfuscation (making the code harder to read), personal preferences, badly considered global search-and-replace, and shenanigans converting boolean values to integers.
It's possible that some confusion has been caused by the TRUE and FALSE definitions in Win32, which are not of bool type but ints, and which may trigger warnings when used in boolean statements. Mainly, anything non-zero is "true", but if you want to make sure that "true" is always one when using integers instead of booleans, you sometimes see shenanigans like this. It's still not a good reason ;-) | I have no idea and I've been writing C++ for a while. I suspect whatever he reasons were they weren't good ones. | MS VC++ 6 : Why return !false rather than true? | [
"",
"c++",
"visual-c++-6",
"boolean",
""
] |
I'm looking at taking a set of objects, let's say there's 3 objects alive at the moment, which all implement a common interface, and then wrap those objects inside a fourth object, also implementing the same interface.
The fourth object's implementations of methods and properties would simply call the relevant bits on those 3 underlying objects. I know that there will be cases here where it won't make sense to do that, but this is for a service multicast architecture so there's already a good set of limitations in place.
My question is where to start. The generation of that fourth object should be done in memory, at runtime, so I'm thinking `Reflection.Emit`, unfortunately I don't have enough experience with that to even know where to begin.
Do I have to construct an in-memory assembly? It sure looks that way, but I'd just like a quick pointer to where I should start.
Basically I'm looking at taking an interface, and a list of object instances all implementing that interface, and constructing a new object, also implementing that interface, which should "multicast" all method calls and property access to all the underlying objects, at least as much as possible. There will be heaps of problems with exceptions and such but I'll tackle those bits when I get to them.
This is for a service-oriented architecture, where I would like to have existing code that takes, as an example, a logger-service, to now access multiple logger services, without having to change the code that uses the services. Instead, I'd like to runtime-generate a logger-service-wrapper that internally simply calls the relevant methods on multiple underlying objects.
This is for .NET 3.5 and C#. | (I'm justifying an answer here by adding extra context/info)
Yes, at the moment `Reflection.Emit` is the only way to solve this.
In .NET 4.0, the `Expression` class has been extended to support both loops and statement blocks, so for **single method** usage, a compiled `Expression` would be a good idea. But even this won't support multi-method interfaces (just single-method delegates).
Fortunately, I've done this previously; see [How can I write a generic container class that implements a given interface in C#?](https://stackoverflow.com/questions/847809/how-can-i-write-a-generic-container-class-that-implements-a-given-interface-in-c/847975#847975) | I'll post my own implementation here, if anyone's interested.
This is heavily influenced and copied from Marc's answer, which I accepted.
The code can be used to wrap a set of objects, all implementing a common interface, inside a new object, also implementing said interface. When methods and properties on the returned object is accessed, the corresponding methods and properties on the underlying objects are accessed in the same way.
**Here there be dragons**: This is for a specific usage. There's potential for odd problems with this, in particular since the code does not ensure that all underlying objects are given the exact same objects as the callee is passing (or rather, it does not prohibit one of the underlying objects from messing with the arguments), and for methods that returns a value, only the last return value will be returned. As for out/ref arguments, I haven't even tested how that works, but it probably doesn't. **You have been warned.**
```
#region Using
using System;
using System.Linq;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using LVK.Collections;
#endregion
namespace LVK.IoC
{
/// <summary>
/// This class implements a service wrapper that can wrap multiple services into a single multicast
/// service, that will in turn dispatch all method calls down into all the underlying services.
/// </summary>
/// <remarks>
/// This code is heavily influenced and copied from Marc Gravell's implementation which he
/// posted on Stack Overflow here: http://stackoverflow.com/questions/847809
/// </remarks>
public static class MulticastService
{
/// <summary>
/// Wrap the specified services in a single multicast service object.
/// </summary>
/// <typeparam name="TService">
/// The type of service to implement a multicast service for.
/// </typeparam>
/// <param name="services">
/// The underlying service objects to multicast all method calls to.
/// </param>
/// <returns>
/// The multicast service instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="services"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> contains a <c>null</c> reference.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><typeparamref name="TService"/> is not an interface type.</para>
/// </exception>
public static TService Wrap<TService>(params TService[] services)
where TService: class
{
return (TService)Wrap(typeof(TService), (Object[])services);
}
/// <summary>
/// Wrap the specified services in a single multicast service object.
/// </summary>
/// <param name="serviceInterfaceType">
/// The <see cref="Type"/> object for the service interface to implement a multicast service for.
/// </param>
/// <param name="services">
/// The underlying service objects to multicast all method calls to.
/// </param>
/// <returns>
/// The multicast service instance.
/// </returns>
/// <exception cref="ArgumentNullException">
/// <para><paramref name="serviceInterfaceType"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> is <c>null</c>.</para>
/// <para>- or -</para>
/// <para><paramref name="services"/> contains a <c>null</c> reference.</para>
/// </exception>
/// <exception cref="ArgumentException">
/// <para><typeparamref name="TService"/> is not an interface type.</para>
/// </exception>
/// <exception cref="InvalidOperationException">
/// <para>One or more of the service objects in <paramref name="services"/> does not implement
/// the <paramref name="serviceInterfaceType"/> interface.</para>
/// </exception>
public static Object Wrap(Type serviceInterfaceType, params Object[] services)
{
#region Parameter Validation
if (Object.ReferenceEquals(null, serviceInterfaceType))
throw new ArgumentNullException("serviceInterfaceType");
if (!serviceInterfaceType.IsInterface)
throw new ArgumentException("serviceInterfaceType");
if (Object.ReferenceEquals(null, services) || services.Length == 0)
throw new ArgumentNullException("services");
foreach (var service in services)
{
if (Object.ReferenceEquals(null, service))
throw new ArgumentNullException("services");
if (!serviceInterfaceType.IsAssignableFrom(service.GetType()))
throw new InvalidOperationException("One of the specified services does not implement the specified service interface");
}
#endregion
if (services.Length == 1)
return services[0];
AssemblyName assemblyName = new AssemblyName(String.Format("tmp_{0}", serviceInterfaceType.FullName));
String moduleName = String.Format("{0}.dll", assemblyName.Name);
String ns = serviceInterfaceType.Namespace;
if (!String.IsNullOrEmpty(ns))
ns += ".";
var assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName,
AssemblyBuilderAccess.RunAndSave);
var module = assembly.DefineDynamicModule(moduleName, false);
var type = module.DefineType(String.Format("{0}Multicast_{1}", ns, serviceInterfaceType.Name),
TypeAttributes.Class |
TypeAttributes.AnsiClass |
TypeAttributes.Sealed |
TypeAttributes.NotPublic);
type.AddInterfaceImplementation(serviceInterfaceType);
var ar = Array.CreateInstance(serviceInterfaceType, services.Length);
for (Int32 index = 0; index < services.Length; index++)
ar.SetValue(services[index], index);
// Define _Service0..N-1 private service fields
FieldBuilder[] fields = new FieldBuilder[services.Length];
var cab = new CustomAttributeBuilder(
typeof(DebuggerBrowsableAttribute).GetConstructor(new Type[] { typeof(DebuggerBrowsableState) }),
new Object[] { DebuggerBrowsableState.Never });
for (Int32 index = 0; index < services.Length; index++)
{
fields[index] = type.DefineField(String.Format("_Service{0}", index),
serviceInterfaceType, FieldAttributes.Private);
// Ensure the field don't show up in the debugger tooltips
fields[index].SetCustomAttribute(cab);
}
// Define a simple constructor that takes all our services as arguments
var ctor = type.DefineConstructor(MethodAttributes.Public,
CallingConventions.HasThis,
Sequences.Repeat(serviceInterfaceType, services.Length).ToArray());
var generator = ctor.GetILGenerator();
// Store each service into its own fields
for (Int32 index = 0; index < services.Length; index++)
{
generator.Emit(OpCodes.Ldarg_0);
switch (index)
{
case 0:
generator.Emit(OpCodes.Ldarg_1);
break;
case 1:
generator.Emit(OpCodes.Ldarg_2);
break;
case 2:
generator.Emit(OpCodes.Ldarg_3);
break;
default:
generator.Emit(OpCodes.Ldarg, index + 1);
break;
}
generator.Emit(OpCodes.Stfld, fields[index]);
}
generator.Emit(OpCodes.Ret);
// Implement all the methods of the interface
foreach (var method in serviceInterfaceType.GetMethods())
{
var args = method.GetParameters();
var methodImpl = type.DefineMethod(method.Name,
MethodAttributes.Private | MethodAttributes.Virtual,
method.ReturnType, (from arg in args select arg.ParameterType).ToArray());
type.DefineMethodOverride(methodImpl, method);
// Generate code to simply call down into each service object
// Any return values are discarded, except the last one, which is returned
generator = methodImpl.GetILGenerator();
for (Int32 index = 0; index < services.Length; index++)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Ldfld, fields[index]);
for (Int32 paramIndex = 0; paramIndex < args.Length; paramIndex++)
{
switch (paramIndex)
{
case 0:
generator.Emit(OpCodes.Ldarg_1);
break;
case 1:
generator.Emit(OpCodes.Ldarg_2);
break;
case 2:
generator.Emit(OpCodes.Ldarg_3);
break;
default:
generator.Emit((paramIndex < 255)
? OpCodes.Ldarg_S
: OpCodes.Ldarg,
paramIndex + 1);
break;
}
}
generator.Emit(OpCodes.Callvirt, method);
if (method.ReturnType != typeof(void) && index < services.Length - 1)
generator.Emit(OpCodes.Pop); // discard N-1 return values
}
generator.Emit(OpCodes.Ret);
}
return Activator.CreateInstance(type.CreateType(), services);
}
}
}
``` | Creating a class for an interface at runtime, in C# | [
"",
"c#",
"code-generation",
"multicast",
"reflection.emit",
""
] |
What's the most compact way to compute the number of lines of a file?
I need this information to create/initialize a matrix data structure.
Later I have to go through the file again and store the information inside a matrix.
**Update:** Based on Dave Gamble's. But why this doesn't compile?
Note that the file could be very large. So I try to avoid using container
to save memory.
```
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main ( int arg_count, char *arg_vec[] ) {
if (arg_count !=2 ) {
cerr << "expected one argument" << endl;
return EXIT_FAILURE;
}
string line;
ifstream myfile (arg_vec[1]);
FILE *f=fopen(myfile,"rb");
int c=0,b;
while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;
fseek(f,0,SEEK_SET);
return 0;
}
``` | ```
FILE *f=fopen(filename,"rb");
int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET);
```
Answer in c.
That kind of compact? | If the reason you need to "go back again" is because you cannot continue without the size, try re-ordering your setup.
That is, read through the file, storing each line in a `std::vector<string>` or something. Then you have the size, along with the lines in the file:
```
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
std::vector<std::string> fileData;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
fileData.push_back(dummy);
}
// and size is available, along with the file
// being in memory (faster than hard drive)
size_t fileLines = fileData.size();
std::cout << "Number of lines: " << fileLines << std::endl;
}
```
---
Here is a solution without the container:
```
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
int main(void)
{
std::fstream file("main.cpp");
size_t fileLines = 0;
// read in each line
std::string dummy;
while (getline(file, dummy))
{
++fileLines;
}
std::cout << "Number of lines: " << fileLines << std::endl;
}
```
Though I doubt that's the most efficient way. The benefit of this method was the ability to store the lines in memory as you went. | Most Compact Way to Count Number of Lines in a File in C++ | [
"",
"c++",
"linux",
"unix",
"line-numbers",
""
] |
How play standard system sounds from a Python script?
I'm writing a GUI program in wxPython that needs to beep on events to attract user's attention, maybe there are functions in wxPython I can utilize? | from the [documentation](http://docs.wxwidgets.org/stable/wx_dialogfunctions.html#wxbell), you could use wx.Bell() function (not tested though) | on windows you could use [`winsound`](http://docs.python.org/library/winsound.html#module-winsound) and I suppose [`curses.beep`](http://docs.python.org/library/curses.html#curses.beep) on Unix. | System standard sound in Python | [
"",
"python",
"audio",
"wxpython",
"system-sounds",
""
] |
Is there anyway to programmatically add a strong named assembly to the GAC using C# code ?
Thanks | This Microsoft Support article, [*How to install an assembly into the Global Assembly Cache in Visual C#*](http://support.microsoft.com/kb/815808), should explain all you need to know.
This is typically a task performed by the installer, so I'm not sure why you'd want to do it from within a .NET program (unless I've misunderstood your question). However, you can simply use the `System.Diagnostics.Process` class to run all the necessary programs as an installer might. | The Global Assembly Cache is configured through a COM-like interface(<http://support.microsoft.com/default.aspx?scid=kb;en-us;317540>).
For all questions about the GAC, Jungfen Zhang's blog is the source of choice.
<http://blogs.msdn.com/junfeng/articles/229648.aspx>
<http://blogs.msdn.com/junfeng/articles/229649.aspx>
For more information, search for "managed GAC API".
> Gacutil.exe is only for development
> purposes and should not be used to
> install production assemblies into the
> global assembly cache.
>
> [Microsoft Installer] is the recommended
> and most common way to add assemblies
> to the global assembly cache. The
> installer provides reference counting
> of assemblies in the global assembly
> cache, plus other benefits. | Programmatically add a strong named assembly to the GAC | [
"",
"c#",
".net",
"assemblies",
"gac",
""
] |
In both Microsoft VC2005 and g++ compilers, the following results in an error:
On win32 VC2005: *sizeof(wchar\_t) is 2*
```
wchar_t *foo = 0;
static_cast<unsigned short *>(foo);
```
Results in
```
error C2440: 'static_cast' : cannot convert from 'wchar_t *' to 'unsigned short *' ...
```
On Mac OS X or Linux g++: *sizeof(wchar\_t) is 4*
```
wchar_t *foo = 0;
static_cast<unsigned int *>(foo);
```
Results in
```
error: invalid static_cast from type 'wchar_t*' to type 'unsigned int*'
```
Of course, I can always use *reinterpret\_cast*. However, I would like to understand why it is deemed illegal by the compiler to static\_cast to the appropriate integer type. I'm sure there is a good reason... | You cannot cast between unrelated pointer types. The size of the type pointed to is irrelevant. Consider the case where the types have different alignment requirements, allowing a cast like this could generate illegal code on some processesors. It is also possible for pointers to different types to have differrent sizes. This could result in the pointer you obtain being invalid and or pointing at an entirely different location. Reinterpret\_cast is one of the escape hatches you hacve if you know for your program compiler arch and os you can get away with it. | As with `char`, the signedness of `wchar_t` is not defined by the standard. Put this together with the possibility of non-2's complement integers, and for for a `wchar_t` value `c`,
```
*reinterpret_cast<unsigned short *>(&c)
```
may not equal:
```
static_cast<unsigned short>(c)
```
In the second case, on implementations where `wchar_t` is a sign+magnitude or 1's complement type, any negative value of c is converted to unsigned using modulo 2^N, which changes the bits. In the former case the bit pattern is picked up and used as-is (if it works at all).
Now, if the results are different, then there's no realistic way for the implementation to provide a `static_cast` between the pointer types. What could it do, set a flag on the `unsigned short*` pointer, saying "by the way, when you load from this, you have to also do a sign conversion", and then check this flag on all unsigned short loads?
That's why it's not, in general, safe to cast between pointers to distinct integer types, and I believe this unsafety is why there is no conversion via static\_cast between them.
If the type you're casting to happens to be the so-called "underlying type" of wchar\_t, then the resulting code would almost certainly be OK for the implementation, but would not be portable. So the standard doesn't offer a special case allowing you a static\_cast just for that type, presumably because it would conceal errors in portable code. If you know reinterpret\_cast is safe, then you can just use it. Admittedly, it would be nice to have a straightforward way of asserting at compile time that it is safe, but as far as the standard is concerned you should design around it, since the implementation is not required even to dereference a `reinterpret_cast`ed pointer without crashing. | static_cast wchar_t* to int* or short* - why is it illegal? | [
"",
"c++",
"casting",
"wchar-t",
""
] |
update: changed one time to show that the times per shipment may not be in sequential order always.
here is my input
```
create table test
(
shipment_id int,
stop_seq tinyint,
time datetime
)
insert into test values (1,1,'2009-8-10 8:00:00')
insert into test values (1,2,'2009-8-10 9:00:00')
insert into test values (1,3,'2009-8-10 10:00:00')
insert into test values (2,1,'2009-8-10 13:00:00')
insert into test values (2,2,'2009-8-10 14:00:00')
insert into test values (2,3,'2009-8-10 20:00:00')
insert into test values (2,4,'2009-8-10 18:00:00')
```
the output that i want is below
```
shipment_id start end
----------- ----- ---
1 8:00 10:00
2 13:00 18:00
```
i need to take the time from the `min(stop)` row for each shipment and the time from the `max(stop)` row and place in start/end respectively. i know this can be done with multiple queries rather easily but i am looking to see if a single select query can do this.
thanks! | I think the only way you'll be able to do it is with sub-queries.
```
SELECT shipment_id
, (SELECT TOP 1 time
FROM test AS [b]
WHERE b.shipment_id = a.shipment_id
AND b.stop_seq = MIN(a.stop_seq)) AS [start]
, (SELECT TOP 1 time
FROM test AS [b]
WHERE b.shipment_id = a.shipment_id
AND b.stop_seq = MAX(a.stop_seq)) AS [end]
FROM test AS [a]
GROUP BY shipment_id
```
You'll need to use the DATEPART function to chop up the time column to get your exact output. | Use a Common Table Expression (CTE) - this works (at least on my SQL Server 2008 test system):
```
WITH SeqMinMax(SeqID, MinID, MaxID) AS
(
SELECT Shipment_ID, MIN(stop_seq), MAX(stop_seq)
FROM test
GROUP BY Shipment_ID
)
SELECT
SeqID 'Shipment_ID',
(SELECT TIME FROM test
WHERE shipment_id = smm.seqid AND stop_seq = smm.minid) 'Start',
(SELECT TIME FROM test
WHERE shipment_id = smm.seqid AND stop_seq = smm.maxid) 'End'
FROM seqminmax smm
```
The `SeqMinMax` CTE selects the min and max "stop\_seq" values for each "shipment\_id", and the rest of the query then builds on those values to retrieve the associated times from the table "test".
CTE's are supported on SQL Server 2005 (and are a SQL:2003 standard feature - no Microsoft "invention", really).
Marc | sql max/min query and data transformation | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
According to [PEP 257](http://www.python.org/dev/peps/pep-0257/#multi-line-docstrings) the docstring of command line script should be its usage message.
> The docstring of a script (a
> stand-alone program) should be usable
> as its "usage" message, printed when
> the script is invoked with incorrect
> or missing arguments (or perhaps with
> a "-h" option, for "help"). Such a
> docstring should document the script's
> function and command line syntax,
> environment variables, and files.
> Usage messages can be fairly elaborate
> (several screens full) and should be
> sufficient for a new user to use the
> command properly, as well as a
> complete quick reference to all
> options and arguments for the
> sophisticated user.
So my docstring would look something like this:
```
<tool name> <copyright info>
Usage: <prog name> [options] [args]
some text explaining the usage...
Options:
-h, --help show this help message and exit
...
```
Now I want to use the optparse module. optparse generates the "Options" sections and a "usage" explaining the command line syntax:
```
from optparse import OptionParser
if __name__ == "__main__":
parser = OptionParser()
(options, args) = parser.parse_args()
```
So calling the script with the "-h" flag prints:
```
Usage: script.py [options]
Options:
-h, --help show this help message and exit
```
This can be modified as follows:
```
parser = OptionParser(usage="Usage: %prog [options] [args]",
description="some text explaining the usage...")
```
which results in
```
Usage: script.py [options] [args]
some text explaining the usage...
Options:
-h, --help show this help message and exit
```
But how can I use the docstring here? Passing the docstring as the usage message has two problems.
1. optparse appends "Usage: " to the docstring if it does not start with "Usage: "
2. The placeholder '%prog' must be used in the docstring
**Result**
According to the answers it seems that there is no way to reuse the docstring intended by the optparse module. So the remaining option is to parse the docstring manually and construct the OptionParser. (So I'll accept S.Loot's answer)
The "Usage: " part is introduced by the IndentedHelpFormatter which can be replaced with the formatter parameter in OptionParser.\_\_init\_\_(). | Choice 1: Copy and paste. Not DRY, but workable.
Choice 2: Parse your own docstring to strip out the description paragraph. It's always paragraph two, so you can split on '\n\n'.
```
usage, description= __doc__.split('\n\n')[:2]
```
Since `optparse` generates usage, you may not want to supply the usage sentence to it. Your version of the usage my be wrong. If you insist on providing a usage string to `optparse`, I'll leave it as an exercise for the reader to work out how to remove `"Usage: "` from the front of the `usage` string produced above. | I wrote a module `docopt` to do exactly what you want – write usage-message in docstring and stay DRY.
It also allows to avoid writing tedious `OptionParser` code at all, since `docopt` is generating parser
based on the usage-message.
Check it out: <http://github.com/docopt/docopt>
```
"""Naval Fate.
Usage:
naval_fate.py ship new <name>...
naval_fate.py ship [<name>] move <x> <y> [--speed=<kn>]
naval_fate.py ship shoot <x> <y>
naval_fate.py mine (set|remove) <x> <y> [--moored|--drifting]
naval_fate.py -h | --help
naval_fate.py --version
Options:
-h --help Show this screen.
--version Show version.
--speed=<kn> Speed in knots [default: 10].
--moored Moored (anchored) mine.
--drifting Drifting mine.
"""
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__, version='Naval Fate 2.0')
print(arguments)
``` | How to comply to PEP 257 docstrings when using Python's optparse module? | [
"",
"python",
"optparse",
""
] |
I'm interested in writing a short python script which uploads a short binary file (.wav/.raw audio) via a POST request to a remote server.
I've done this with pycurl, which makes it very simple and results in a concise script; unfortunately it also requires that the end
user have pycurl installed, which I can't rely on.
I've also seen some examples in other posts which rely only on basic libraries, urllib, urllib2, etc., however these generally seem to be quite verbose, which is also something I'd like to avoid.
I'm wondering if there are any concise examples which do not require the use of external libraries, and which will be quick and easy for 3rd parties to understand - even if they aren't particularly familiar with python.
What I'm using at present looks like,
```
def upload_wav( wavfile, url=None, **kwargs ):
"""Upload a wav file to the server, return the response."""
class responseCallback:
"""Store the server response."""
def __init__(self):
self.contents=''
def body_callback(self, buf):
self.contents = self.contents + buf
def decode( self ):
self.contents = urllib.unquote(self.contents)
try:
self.contents = simplejson.loads(self.contents)
except:
return self.contents
t = responseCallback()
c = pycurl.Curl()
c.setopt(c.POST,1)
c.setopt(c.WRITEFUNCTION, t.body_callback)
c.setopt(c.URL,url)
postdict = [
('userfile',(c.FORM_FILE,wavfile)), #wav file to post
]
#If there are extra keyword args add them to the postdict
for key in kwargs:
postdict.append( (key,kwargs[key]) )
c.setopt(c.HTTPPOST,postdict)
c.setopt(c.VERBOSE,verbose)
c.perform()
c.close()
t.decode()
return t.contents
```
this isn't exact, but it gives you the general idea. It works great, it's simple for 3rd parties to understand, *but* it requires pycurl. | POSTing a file requires `multipart/form-data` encoding and, as far as I know, there's no easy way (i.e. one-liner or something) to do this with the stdlib. But as you mentioned, there are plenty of recipes out there.
Although they seem verbose, your use case suggests that you can probably just encapsulate it once into a function or class and not worry too much, right? Take a look at the recipe on ActiveState and read the comments for suggestions:
* [Recipe 146306: Http client to POST using multipart/form-data](http://code.activestate.com/recipes/146306/)
or see the `MultiPartForm` class in this PyMOTW, which seems pretty reusable:
* [PyMOTW: urllib2 - Library for opening URLs.](http://pymotw.com/2/urllib2/)
I believe both handle binary files. | I met similar issue today, after tried both and pycurl and multipart/form-data, I decide to read python httplib/urllib2 source code to find out, I did get one comparably good solution:
1. set Content-Length header(of the file) before doing post
2. pass a opened file when doing post
Here is the code:
```
import urllib2, os
image_path = "png\\01.png"
url = 'http://xx.oo.com/webserviceapi/postfile/'
length = os.path.getsize(image_path)
png_data = open(image_path, "rb")
request = urllib2.Request(url, data=png_data)
request.add_header('Cache-Control', 'no-cache')
request.add_header('Content-Length', '%d' % length)
request.add_header('Content-Type', 'image/png')
res = urllib2.urlopen(request).read().strip()
return res
```
see my blog post: <http://www.2maomao.com/blog/python-http-post-a-binary-file-using-urllib2/> | HTTP POST binary files using Python: concise non-pycurl examples? | [
"",
"python",
"http",
"post",
"binary",
""
] |
is there a better way then a try/catch to parse numbers and datetimes without crashing the page?
if they are not valid numbers/datetimes they should be null.
here is what I've got so far:
```
long id = null;
try{
id = Int64.Parse(Request.QueryString["id"]);
}catch(Exception e){}
DateTime time = null;
try{
time = DateTime.Parse(Request.QueryString["time"]);
}catch(Exception e){}
``` | ```
int tempInt = 0;
if(int.TryParse(Request["Id"], out tempInt))
//it's good!!
```
Likewise, for the date it's "DateTime.TryParse"
*edit*
To fully mimic what your code is doing, you'd have this:
```
long? id = null; DateTime? time = null;
long tempLong; DateTime tempDate;
if(long.TryParse(Request["id"], out tempLong))
id = tempLong;
if(DateTime.TryParse(Request["time"], out tempDate))
time = tempDate;
``` | Use TryParse instead of Parse.
TryParse doesn't throw and is good for situations like this, where the input is not necessarily trusted and you do not want an exception thrown. | asp.net c# better way to Parse numbers and datetimes from query string then try/catch | [
"",
"c#",
"asp.net",
""
] |
I have a LINQ query which searches for a string (using a regex) in multiple fields. I want to sort the results based on in which field the text was found.
Currently I have this:
```
var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable()
where r.IsMatch(i.Field<String>("Key").Replace(" ","")) ||
r.IsMatch(i.Field<String>("Username").Replace(" ","")) ||
r.IsMatch(i.Field<String>("Other").Replace(" ",""))
orderby i.Field<String>("Key"),
i.Field<String>("Other"),
i.Field<String>("Username")
select i;
```
I want matches found in Key first, then matches found in Other, and then matches found in Username. If possible, matches which match both Key and Other should go before matches that match only Key.
The code I currently have sorts based on Key first, so if a match is found on Other but Key starts with an A, it will be sorted before a match found on Key where Key starts with a Z.
Thanks in advance, it isn't a hard question I think but I just can't figure out how to do this as I'm new to LINQ. | Using the `let` keyword to capture intermediate values, you can easily sort by whether there was a match before you sort the matched values:
```
var results = from i in passwordData.Tables["PasswordValue"].AsEnumerable()
let fields = new {
Key = i.Field<String>("Key"),
Username = i.Field<String>("Username"),
Other = i.Field<String>("Other") }
let matches = new {
Key = r.IsMatch(fields.Key.Replace(" ","")),
Username = r.IsMatch(fields.Username.Replace(" ","")),
Other = r.IsMatch(fields.Other.Replace(" ","")) }
where matches.Key || matches.Username || matches.Other
orderby matches.Key descending, fields.Key,
matches.Username descending, fields.Username,
matches.Other descending, fields.Other
select i;
``` | Your one soloution is to create 2 methods , one for the Key search and one for the Other search. Then based on which field was hit on the seach you run the order by. While this may be extra coding it is the only way that i see it being done with out creating your own expresion trees which are alot harder. | Sort by search criteria C# LINQ | [
"",
"c#",
"linq",
"sorting",
""
] |
I was going through the diamond problem and thought will work on various scenarios. And this is one among them which I was working on.
```
#include <iostream>
using namespace std;
class MainBase{
public:
int mainbase;
MainBase(int i):mainbase(i){}
void geta()
{
cout<<"mainbase"<<mainbase<<endl;
}
};
class Derived1: public MainBase{
public:
int derived1;
int mainbase;
Derived1(int i):MainBase(i),derived1(i) {mainbase = 1;}
public:
void getderived1()
{
cout<<"derived1"<<derived1<<endl;
}
};
class Derived2: public MainBase{
public:
int derived2;
int mainbase;
Derived2(int i):MainBase(i),derived2(i){mainbase = 2;}
public:
void getderived2()
{
cout<<"derived2"<<derived2<<endl;
}
};
class Diamond: public Derived1, public Derived2{
public:
int diamond;
int mainbase;
Diamond(int i,int j, int x):Derived1(j),Derived2(x),diamond(i){mainbase=3;}
public:
void getdiamond()
{
cout<<"diamond"<<diamond<<endl;
}
};
int main()
{
Diamond d(4,5,6);
// cout<< d.MainBase::mainbase;
cout<<"tested"<<endl;
cout<<d.mainbase;
cout<<d.Derived2::mainbase<<endl;
cout<<d.Derived1::mainbase<<endl;
/*cout<<d.Derived2::MainBase::mainbase<<endl;
cout<<d.Derived1::MainBase::mainbase<<endl;*/
}
```
I am now wondering how to I access MainBase class mainbase variable? Any inputs. | You do what you have done there:
```
cout<<d.Derived2::MainBase::mainbase<<endl;
cout<<d.Derived1::MainBase::mainbase<<endl;
```
But, it might not do what you are trying to achieve. Possibly, you should be using `virtual` inheritance? What you have means there will be two copies of the `MainBase` members in your object, one for each inheritance track.
(From MSDN).
> When a base class is specified as a
> virtual base, it can act as an
> indirect base more than once without
> duplication of its data members. A
> single copy of its data members is
> shared by all the base classes that
> use it as a virtual base.
Probably something like this will suit you better:
```
class Derived1: virtual public MainBase{
``` | Your code won't compile, there is an ambiguity when referring to Mainbase as a base of a Diamond instance. You need to use *virtual* in the derived classes (Derived1, Derived2) to resolve this ambiguity by allowing them to share a single instance of base class, like this:
```
class Derived1: virtual public Mainbase {
/* do your thing here*/
};
``` | Diamond problem | [
"",
"c++",
"multiple-inheritance",
"diamond-problem",
""
] |
I have a program as follows:
```
a=reader.next()
if *some condition holds*:
#Do some processing and continue the iteration
else:
#Append the variable a back to the iterator
#That is nullify the operation *a=reader.next()*
```
How do I add an element to the start of the iterator?
(Or is there an easier way to do this?)
EDIT: OK let me put it this way. I need the next element in an iterator without removing it.
How do I do this>? | Python iterators, as such, have very limited functionality -- no "appending" or anything like that. You'll need to wrap the generic iterator in a wrapper adding that functionality. E.g.:
```
class Wrapper(object):
def __init__(self, it):
self.it = it
self.pushedback = []
def __iter__(self):
return self
def next(self):
if self.pushedback:
return self.pushedback.pop()
else:
return self.it.next()
def pushback(self, val):
self.pushedback.append(val)
```
This is Python 2.5 (should work in 2.6 too) -- slight variants advised for 2.6 and mandatory for 3.any (use `next(self.it)` instead of `self.it.next()` and define `__next__` instead of `next`).
**Edit**: the OP now says what they need is "peek ahead without consuming". Wrapping is still the best option, but an alternative is:
```
import itertools
...
o, peek = itertools.tee(o)
if isneat(peek.next()): ...
```
this doesn't advance `o` (remember to advance it if and when you decide you DO want to;-). | You're looking for [`itertools.chain`](https://docs.python.org/3/library/itertools.html#itertools.chain):
```
import itertools
values = iter([1,2,3]) # the iterator
value = 0 # the value to prepend to the iterator
together = itertools.chain([value], values) # there it is
list(together)
# -> [0, 1, 2, 3]
``` | Need to add an element at the start of an iterator in python | [
"",
"python",
"iterator",
""
] |
I've got a signed java applet (using a self-signed-certificate) which has to access the user's file system. I have to do it, so please no replies ala "you shouldn't do it" :)
The thing is, when I execute the Applet from Firefox 3.0 / Mac, everything works as desired, I get all access just as it should.
When I use Safar 4 / Mac, I don't get access. The line I especially have problems with is System.getProperty() (although when I stub that out, the FS access doesn't work either)
```
String home = System.getProperty("user.home");
```
The Exception I get is the following:
```
java.security.AccessControlException: access denied (java.util.PropertyPermission user.home read)
at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264)
at java.security.AccessController.checkPermission(AccessController.java:427)
at java.lang.SecurityManager.checkPermission(SecurityManager.java:532)
at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1285)
at java.lang.System.getProperty(System.java:628)
at de.samedi.searcher.Searcher.<init>(Searcher.java:49)
at de.samedi.searcher.Applet.getSearcher(Applet.java:193)
at de.samedi.searcher.Applet.getSearcher(Applet.java:187)
at de.samedi.searcher.Applet.addPatient(Applet.java:68)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at sun.plugin.javascript.invoke.JSInvoke.invoke(JSInvoke.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at sun.plugin.javascript.JSClassLoader.invoke(JSClassLoader.java:44)
at sun.plugin.liveconnect.PrivilegedCallMethodAction.run(SecureInvocation.java:658)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin.liveconnect.SecureInvocation$2.run(SecureInvocation.java:214)
at java.security.AccessController.doPrivileged(Native Method)
at sun.plugin.liveconnect.SecureInvocation.CallMethod(SecureInvocation.java:192)
at sun.plugin.liveconnect.SecureInvocation.access$300(SecureInvocation.java:52)
at sun.plugin.liveconnect.SecureInvocation$CallMethodThread.run(SecureInvocation.java:123)
```
As I said, this works perfectly on Firefox. Gotta check Windows Browser today...
Any Ideas? | Once you have your jar compiled and signed you should run the -verify option to ensure its signed properly.
If the verification is ok look at the installed certificates on your browsers.
I haven't done anything in Safari only IE, but I imagine there is a place similar to I.E. where you can at least view the installed certificates. I would verify the certificate is installed.
Also make sure your code is running in a privileged block.
```
String home = System.getProperty("user.home");
```
will always throw an error in 1.4 or higher. Unless you have edited the java.policy file for All Permissions
Try using this in combination with your signed jar.
```
String home = (String) AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
return System.getProperty("user.home");
}
});
``` | I remember having a similar problem in an older version of Safari (this was years ago), and the solution I found was adding a delay to the applet. It seemed Safari for some reason was allowing the applet to run before the user was given the "trust this applet" dialogue (other browsers would not start the applet until after the user granted or denied access). At that point the applet was not trusted and a security exception would occur. Even though the user would then allow trust, it was too late as the applet had already run and failed. I had to add a delay for safari, so it would not try doing anything that needed secure access until a period of time had passed, allowing the user to give access before the applet tried doing anything needing security access. | Signed Java applet doesnt get permissions in Safari | [
"",
"java",
"safari",
"applet",
"signed-applet",
""
] |
**What is the current state of Java's transition to an open source license** (which [Wikipedia lists as the GNU General Public License / Java Community Process](http://en.wikipedia.org/wiki/Java_%28programming_language%29))?
Java being inclusive of many things, including:
* The JVM
* The JRE
* The JDK
* The Core Java Libraries
* JavaME
* JavaEE
I've heard/read various things, but never seen it laid out in a straight, definitive, manner. However if you know about only a subsection of Java, don't hesitate to add an answer.
Just to clarify, this question is about the **current** state of the process, not what Sun may or may not do in the future. | As you've quite rightly pointed out, Java encompasses a large number of components; I'm not sure that you'll be able to get a definitive answer that clarifies all the intricacies here.
However, based on various licensing that I've read so far, Java is (supposed to be) fully GPL'd now with the exception of the SNMP implementation which is still encumbered. This includes all of items you've stated, with the possible exception of Java EE. (I don't know much about that)
With regards to the state of the process; there doesn't appear to be much progress on replacing the SNMP implementation. I would therefore take the view that Java 6 will not be fully GPL compliant.
Java 7 looks like it will be fully GPL compliant from the info that Sun have been giving out. But that's not due for release until 2010 - and that's a tentative timescale. | I can't say that I know all that much about the current transition/process, but I can tell you that the [OpenJDK](http://openjdk.java.net/) (see also [OpenJDK on Wikipedia](http://en.wikipedia.org/wiki/OpenJDK)), specifically OpenJDK 6 is good enough to be used in place of the Sun Java JDK 6 release, and it has now been [certified by Canonical for use in Ubuntu Jaunty](http://news.softpedia.com/news/Ubuntu-9-04-Receives-OpenJDK-6-Certification-116630.shtml). | What is the state of Open Source Java? | [
"",
"open-source",
"jvm",
"java",
""
] |
I have to connect to a third party web service that provides no wsdl nor asmx. The url of the service is just <http://server/service.soap>
I have read [this article](http://mikehadlow.blogspot.com/2006/05/making-raw-web-service-calls-with.html) about raw services calls, but I'm not sure if this is what I'm looking for.
Also, I've asked for wsdl files, but being told that there are none (and there won't be).
I'm using C# with .net 2.0, and can't upgrade to 3.5 (so no WCF yet). I think that third party is using java, as that's the example they have supplied.
Thanks in advance!
**UPDATE** Get this response when browsing the url:
```
<SOAP-ENV:Envelope>
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode>SOAP-ENV:Server</faultcode>
<faultstring>
Cannot find a Body tag in the enveloppe
</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
``` | Well, I finally got this to work, so I'll write here the code I'm using. (Remember, .Net 2.0, and no wsdl to get from web service).
First, we create an HttpWebRequest:
```
public static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAP:Action");
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
```
Next, we make a call to the webservice, passing along all values needed. As I'm reading the soap envelope from a xml document, I'll handle the data as a StringDictionary. Should be a better way to do this, but I'll think about this later:
```
public static XmlDocument ServiceCall(string url, int service, StringDictionary data)
{
HttpWebRequest request = CreateWebRequest(url);
XmlDocument soapEnvelopeXml = GetSoapXml(service, data);
using (Stream stream = request.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
IAsyncResult asyncResult = request.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
string soapResult;
using (WebResponse webResponse = request.EndGetResponse(asyncResult))
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
File.WriteAllText(HttpContext.Current.Server.MapPath("/servicios/" + DateTime.Now.Ticks.ToString() + "assor_r" + service.ToString() + ".xml"), soapResult);
XmlDocument resp = new XmlDocument();
resp.LoadXml(soapResult);
return resp;
}
```
So, that's all. If anybody thinks that GetSoapXml must be added to the answer, I'll write it down. | In my opinion, there is no excuse for a SOAP web service to not supply a WSDL. It need not be dynamically generated by the service; it need not be available over the Internet. But there **must** be a WSDL, even if they have to send it to you on a ~~floppy disk~~ thumb drive!
If you have any ability to complain to the providers of this service, then I urge you to do so. If you have the ability to push back, then do so. Ideally, switch service providers, and tell these people it's because they didn't provide a WSDL. At the very least, find out why they don't think it's important. | How to call a web service with no wsdl in .net | [
"",
"c#",
".net",
"web-services",
"soap",
"wsdl",
""
] |
In Smarty, is there a standard function or an easy way to generate json from an array, as `json_encode()` does in php?
I could not see it in Smarty documentation, wanted to ask here. | ***Now deprecated***
This should work. The @ makes smarty run the modifier against the whole array, otherwise it does it for each element.
```
{$myarray|@json_encode}
```
If [$escape\_html](http://www.smarty.net/docs/en/variable.escape.html.tpl) is enabled, you will need to use `nofilter`:
```
{$myarray|@json_encode nofilter}
``` | While `{$myarray|@json_encode}` does in fact emit the array encoded in json, it also escapes special characters, making the array unusable in javascript.
To avoid escaping special characters and also be able to use the array in javascript use the nofilter flag:
```
{$myarray|@json_encode nofilter}
``` | Howto generate json with smarty? | [
"",
"php",
"smarty",
"json",
""
] |
I have a website which has thousands of (ever increasing) resources in it. I implemented the usual **Sql Full text Search** and it was working fine until recently. I noticed some performance issues with it. I am using MySql Database with C#. NET as the back-end code.
I just need few valuable suggestions from you so that I can take those into account while building a new search strategy for my website.
What can I use to improve performance in the search functionality on my site? | You could try out;
<http://incubator.apache.org/lucene.net/> | Take a look at [Lucene.NET](http://incubator.apache.org/lucene.net/). It is a high-performance, full-featured text search engine library which was initially written in Java but ported over to .NET. It is a technology suitable for nearly any application that requires full-text search, especially cross-platform. | Implementing 'Search' functionality on website | [
"",
"c#",
"mysql",
"search",
"full-text-search",
""
] |
I'm extracting emails from a database where they're stored as strings. I need to parse these emails to extract their attachments. I guess there must already be some library to do this easily but I can't find any. | [PEAR::Mail::mimeDecode](http://pear.php.net/package/Mail_mimeDecode) should do what you're looking for | PHP has a MailParse extension that is a lot faster then using the PEAR alternative which is native PHP.
Here is a library that wraps this extension:
<http://code.google.com/p/php-mime-mail-parser/>
Example:
```
// require mime parser library
require_once('MimeMailParser.class.php');
// instantiate the mime parser
$Parser = new MimeMailParser();
// set the email text for parsing
$Parser->setText($text);
// get attachments
$attachments = $Parser->getAttachments();
``` | How to extract mail atachment with PHP? | [
"",
"php",
"parsing",
"email",
""
] |
Ok this might sound like a dumb question but bear with me. I am trying to make it so that when people go to example.php?id=1, example.php?id=2, example.php?id=3 etc they see different data called from an included file filling in the blanks.
I have a variable called $offername and I want to display $offer1name, $offer2name, $offer3name in that space, depending on what $\_GET['id'] says. Ideally, when someone goes to example.php?id=2, $offername will equal $offer2name.
I want to do something like this:
$offername = $offer.$\_GET['id'].name
But of course that doesn't work. What should I do? | This should work:
```
$var = 'offer' . $_GET['id'] . 'name';
$offername = $$var;
```
See the page on [variable variables](https://www.php.net/manual/en/language.variables.variable.php) for more. | A much cleaner solution is to just use multidimensional arrays.
e.g., instead of
```
$offername = ${offer.$_GET['id'].name};
```
use
```
$offername = $offer[$_GET['id']]['name'];
```
and define $offer like so:
```
$offer = array(
1 => array(
'name' => 'firstoffer',
),
2 => array(
'name' => 'secondoffer',
),
3 => array(
'name' => 'thirdoffer',
),
);
```
I find variable variables difficult to read, and most of the time when I see them used, an array would be much better. | variables inside variables | [
"",
"php",
"syntax",
"variables",
""
] |
I've always read and been told that when dealing with binary files that one should use read() and write() as opposed to the << and >> operators as they are meant for use with formatted data. I've also read that it is possible to use them, but it is an advanced topic, which I can't find where anyone dives into and discusses.
I recently saw some code which did the following:
```
std::ifstream file1("x", ios_base::in | ios_base::binary);
std::ofstream file2("y", ios_base::app | ios_base::binary);
file1 << file2.rdbuf();
```
When I pointed out the use of the << operator with the binary file, I was told that the rdbuf() call returns a streambuf \* and that << overloads the streambuf\* and does a direct copy with no formatting and is thus safe.
Is this true and also safe? How about efficiency? Any gotchas? Details would be much appreciated.
Thanks! | Yes (see 27.6.2.5.3/6 where the overload of << for streambuf is described). | It's entirely safe and a reasonable way to copy streams.
Note that it also allows stuff like:
```
std::ifstream file_in1("x1", ios_base::in | ios_base::binary);
std::ifstream file_in2("x2", ios_base::in | ios_base::binary);
std::ofstream file_out("y", ios_base::app | ios_base::binary);
file_out << file_in1.rdbuf() << "\nand\n" << file_in2.rdbuf();
``` | C++ fstream << and >> operators with binary data | [
"",
"c++",
"iostream",
"standard-library",
""
] |
I am designing a system for a customer. We are thinking about using Wordpress as a main platform (instead of writing our custom software), and customize it using addons or hiring developers to write some custom modules.
We need to have an ability to have some static pages, few php pages, and lot of user generated content.
What limits do Wordpress have? I have searched website, but did not found any info about for example max number of users. I am interested in experience-based opinions.
So, how Wordpress performs on multi-user websites? Or - do you think it is better to leave Wordpress, and swithch to some other open-source CMS?
**Edit**
The core functionality about the system will be to allow user to put text content and photos on categorized pages. Some users need an ability to have classic blog on the site, while others will only occasionally publish some content. Some data will be polled by RSS from users’ blogs on the other platform (with a respect to copyrights and legal stuff).
So as far as now I have identified a lot of blog-like functionality. | I have had some pretty good success using Drupal. If you aren't trying to build a blog there are much better things out there for dynamic CMS. Wordpress is a great piece of blogging software. Try to make it do something else? It becomes a big pain to do. Having developed "applications" in both. If a blog is not the primary component (which a news site would also follow suit) then use a true CMS and not a blogging platform. | WordPress places no maximum on users, posts, etc. beyond that of the underlying technologies (your database, mainly). WordPress.com runs on the WordPress MultiUser platform and it has [six million blogs, a billion monthly pageviews, and 200k new posts a day](http://en.wordpress.com/stats/).
Your limitations will be more structural - WordPress is designed first and foremost as a blogging platform. If its interface and methodology fit your project well, go for it, but if you're going to be hacking the shit out of it, a more generalist system like Drupal may suit you better. | Wordpress limits - system design consideration | [
"",
"php",
"performance",
"wordpress",
"design-consideration",
""
] |
Working through Pro ASP.NET MVC book and I got the following code snippet that appears in an aspx (view) page...
```
<%= Html.DropDownList ("WillAttend",new[]
{
new SelectListItem { Text = "Yes, I'll be there",Value=bool.TrueString},
new SelectListItem { Text = "No, I can't come",Value=bool.FalseString}
},"Choose an option"); %>
```
Can someone help me convert this to vb.net equivalent.
Any ideas anyone?
**EDIT**
**MORE DETAILS**
Here is the whole code snippet. Not sure it will help but here it goes.
```
<body>
<h1>RSVP</h1>
<% using(Html.BeginForm()) { %>
<p> Your name: <%= Html.TextBox("Name") %></p>
<p> Your email: <%= Html.TextBox("Email") %></p>
<p> Your phone: <%= Html.TextBox("Phone") %></p>
<p>
Will you attend?
<%= Html.DropDownList ("WillAttend",new[]
{
new SelectListItem { Text = "Yes, I'll be there",Value=bool.TrueString},
new SelectListItem { Text = "No, I can't come",Value=bool.FalseString}
},"Choose an option") %>
</p>
<input type="submit" value="Submit RSVP" />
<% } %>
</body>
```
Any help appreciated. I REALLY can't figure this one out.
Seth | you can do this with some fairly verbose VB.NET code:
```
<%
Dim lst As New List(Of SelectListItem)
Dim item1 As New SelectListItem
item1.Text = "Yes, I'll be there"
item1.Value = Boolean.TrueString
lst.Add(item1)
Dim item2 As New SelectListItem
item2.Text = "No, I can't come"
item2.Value = Boolean.FalseString
lst.Add(item2)
%>
<%=Html.DropDownList("WillAttend", lst, "Choose an option")%>
```
The trick is to read the function arguments and supply the appropriate parameters. Sometimes we get used to the more arcane syntaxes and forget about simple variable declarations and assignments. The DropDownList expects an IEnumerable of SelectListItem's as the second argument so that's what we give it. Each SelectListItem should probably have it's value and text fields supplied. What I don't understand is why the SelectListItem's constructor does not supply those two items (plus perhaps a "selected" boolean.) | Try this:
```
<% Dim listItems As SelectListItem() = { _
New SelectListItem() With {.Text = "Yes, I'll be there", .Value = Boolean.TrueString}, _
New SelectListItem() With {.Text = "No, I can't come", .Value = Boolean.FalseString} _
}
Response.Write(Html.DropDownList("WillAttend", listItems, "Choose an option"))
%>
```
My VB is pretty weak. I'm sure someone has a better answer. | How to render the following asp.net mvc c# code snippet as vb.net code | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"vb.net",
""
] |
Goal: When everybody else does SELECT \* FROM mytable they see one version of the table. But when a specific user does SELECT \* FROM mytable they see another version of the table.
I think I'm like halfway there with creating a new role and putting the single user in it. Then creating a copy of the default table with SELECT \* INTO newrole.mytable FROM dbo.mytable. But when the user does SELECT \* FROM mytable they still see the dbo.mytable. How do I get them to default to the newrole.mytable? I still need them to see all the other dbo tables just not this one. | Create a new schema, and a duplicate table (or view onto dbo.table if that's what you want) in it - eg., otheruser.table. Then, set the user's login to default to that schema:
```
USE atest
GO
CREATE ROLE [arole]
GO
CREATE SCHEMA [aschema] AUTHORIZATION [arole]
GO
CREATE USER [auser] FOR LOGIN [modify_user] WITH DEFAULT_SCHEMA = aschema
GO
EXEC sp_addrolemember 'arole', 'auser'
GO
CREATE TABLE dbo.atable ( col1 int )
GO
CREATE TABLE aschema.atable (col2 varchar(10))
GO
INSERT INTO dbo.atable( col1 ) VALUES( 1 )
GO
INSERT INTO aschema.atable( col2 ) VALUES( 'One' )
GO
PRINT 'dbo'
SELECT * FROM atable
GO
EXECUTE AS USER = 'auser'
GO
PRINT 'aschema'
SELECT * FROM atable
GO
REVERT
GO
``` | I use Postgres primarily, so YMMV, but in postgres you need to
1) Create the new schema, preferably owned by the new role, and put the table in it
2) Set the search\_path variable to include that schema BEFORE the other one.
Hope it helps. | How do I make one user see a different table with same name | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
I am trying to access `connectionStrings` from the config file. The code is ASP.NET + C#. I have added `System.Configuration` to reference and also mentioned with using. But still it wouldn't accept the assembly.
I am using VSTS 2008. Any idea what could be the reason?
Another weird thing is the assembly name shown as "System.configuration", a lower case c which is not how names are displayed for other System assemblies.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
namespace Utility
{
public class CommonVariables
{
public static String ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["EmployeeEntities"].ConnectionString; }
}
}
}
```
Config:
```
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="qbankEntities" connectionString="metadata=res://*/qbankModel.csdl|res://*/qbankModel.ssdl|res://*/qbankModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=localhost;Initial Catalog=qbank;Persist Security Info=True;User ID=**;Password=****;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
``` | Ok.. it worked after restarting the VSTS. The [link](http://social.msdn.microsoft.com/Forums/en-US/winformsapplications/thread/82fcd001-243f-4604-bec4-02de92c4f568) suggested the solution for the same problem. Wish i could have seen it before. :) | It's not only necessary to use the **namespace** `System.Configuration`. You have also to add the reference to the **assembly** `System.Configuration.dll` , by
1. Right-click on the *References / Dependencies*
2. Choose *Add Reference*
3. Find and add `System.Configuration`.
This will work for sure.
Also for the `NameValueCollection` you have to write:
```
using System.Collections.Specialized;
``` | The name 'ConfigurationManager' does not exist in the current context | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
""
] |
I know (Windows Activation Service) WAS is advertised as part of Windows 2008/Vista/7 but since it appears under .NET 3.5 framework components in Control Panel Windows Components, I was wondering if anyone knows/has managed to run in under Windows 2003 as well.
I'm trying to host a WCF server in WAS under Windows 2003 (written in .NET C#)
Alternatively, does anyone know of any good open source application servers out there that can be used to host .NET servers? (TomCat for .NET?!) | WAS is a part of IIS7, which is available on Vista and Win Server 2008 and up only.
On Win Server 2003, you can either host your WCF service in IIS - which limits you to just http (basicHttp or wsHttp), or - my preferred way - you can host your WCF service yourself.
Typically, you would host your WCF service in a console app for testing/debugging purposes, and then put it inside a Windows NT Service for production - this runs around the clock, with no one logged in, and it supports **ALL** the WCF bindings (not just http, but also Net.TCP, NetNamedPipe, MSMQ and so on).
Marc | You can always roll your own WCF host. I've used this concept as an example.
<http://www.codeproject.com/KB/WCF/generic_wcf_host.aspx> | Windows Activation Service on Windows 2003 | [
"",
"c#",
".net",
"wcf",
"windows-services",
""
] |
Let's say for example you have 5 different companies using the same platform (Windows based) all wrote their own web services, what technique using C# and .Net 3.5 would you recommend using to monitor all their different web services?
My intention is to build an application that provides visual feedback on service statuses to site administrators and of course e-mail/sms alerts as needed. Is there a best practice or methodology to follow in your opinion?
In addition, are there any windows based tools available to perform this that I'm unaware off? Preferrably open-source?
\*Edit: Think of the end result, an application that just shows a red or green light next to the services running across the different companies.
```
Company 1
> Web Service 1 - Green
> Web Service 2 - Green
Company 2
> Web Service 1 - Red
> Web Service 2 - Green
``` | You should try PolyMon, a .NET based, open-source monitoring tool on CodePlex:
<http://polymon.codeplex.com/>
At least for our case, it hit the sweet-spot of functionality and a lean and easy setup.
You can choose from some out-of-the-box tasks like Ping or URL monitoring, but you can also easily implement your own more complex tasks. Works quite well for us.
The tool itself is not distributed, but you can easily set up two instances of the service (e. g. on servers in different locations) and monitor the same services, or use one instance to monitor the other.
We experienced just one issue that was very annoying and a little freaky, when a server that was running both PolyMon and the SQL Server instance used by PolyMon repeatedly crashed on reboots (endless loop of reboot). Seems to be some kind of race condition. Therefore I strongly recommend to host the PolyMon service and the SQL Server service on different (virtual) machines, or set the start-up type of the PolyMon service to "Manual" instead of "Automatic", and start PolyMon manually after everything else booted, to avoid this problem. | The most commonly used open source monitoring tool is Nagios. Built in it has support for many different services, and you can always write a script or app to test any service not already supported.
* [Nagios Home Page](http://www.nagios.org/)
* [Windows Monitoring Service](http://www.monitoringexchange.org/cgi-bin/page.cgi?g=Detailed/2153.html;d=1)
* [Instruction for setting up Windows service](http://www.bladewatch.com/2007/02/27/installing-nagios-in-windows/) | Distributed Monitoring Service using C# .NET 3.5 | [
"",
"c#",
".net-3.5",
"monitoring",
""
] |
How can I implement a `FileSystemWatcher` for an FTP location (in C#). The idea is whenever anything gets added in the FTP location I wish to copy it to my local machine. Any ideas will be helpful.
This is a follow up of my previous question [Selective FTP download using .NET](https://stackoverflow.com/questions/1276554/selective-ftp-download-using-net). | You're going to have to implement a polling solution, where you keep asking for the directory content periodically. Compare this to a cached list from the previous call and determine what happened that way.
There's nothing in the FTP protocol that will help you with this unfortunately. | You cannot use the [`FileSystemWatcher`](https://learn.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher) or any other way, because the FTP protocol does not have any API to notify a client about changes in the remote directory.
All you can do is to periodically iterate the remote tree and find changes.
It's actually rather easy to implement, if you use an FTP client library that supports recursive listing of a remote tree. Unfortunately, the built-in .NET FTP client, the [`FtpWebRequest`](https://learn.microsoft.com/en-us/dotnet/api/system.net.ftpwebrequest) does not. But for example with [WinSCP .NET assembly](https://winscp.net/eng/docs/library), you can use the [`Session.EnumerateRemoteFiles` method](https://winscp.net/eng/docs/library_session_enumerateremotefiles).
See the article [Watching for changes in SFTP/FTP server](https://winscp.net/eng/docs/library_example_watch_for_changes):
```
// Setup session options
SessionOptions sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "example.com",
UserName = "user",
Password = "password",
};
using (Session session = new Session())
{
// Connect
session.Open(sessionOptions);
List<string> prevFiles = null;
while (true)
{
// Collect file list
List<string> files =
session.EnumerateRemoteFiles(
"/remote/path", "*.*", EnumerationOptions.AllDirectories)
.Select(fileInfo => fileInfo.FullName)
.ToList();
if (prevFiles == null)
{
// In the first round, just print number of files found
Console.WriteLine("Found {0} files", files.Count);
}
else
{
// Then look for differences against the previous list
IEnumerable<string> added = files.Except(prevFiles);
if (added.Any())
{
Console.WriteLine("Added files:");
foreach (string path in added)
{
Console.WriteLine(path);
}
}
IEnumerable<string> removed = prevFiles.Except(files);
if (removed.Any())
{
Console.WriteLine("Removed files:");
foreach (string path in removed)
{
Console.WriteLine(path);
}
}
}
prevFiles = files;
Console.WriteLine("Sleeping 10s...");
Thread.Sleep(10000);
}
}
```
*(I'm the author of WinSCP)*
---
Though, if you actually want to just download the changes, it's a way easier. Just use the [`Session.SynchronizeDirectories`](https://winscp.net/eng/docs/library_session_synchronizedirectories) in the loop.
```
session.SynchronizeDirectories(
SynchronizationMode.Local, "/remote/path", @"C:\local\path", true).Check();
```
See the article [Keep local directory up to date (download changed files from remote SFTP/FTP server)](https://winscp.net/eng/docs/library_example_keep_local_directory_up_to_date).
---
If you do not want to use a 3rd party library, you have to do with limitations of the `FtpWebRequest`. For an example how to recursively list a remote directory tree with the `FtpWebRequest`, see my answer to [C# Download all files and subdirectories through FTP](https://stackoverflow.com/q/37038676/850848). | FileSystemWatcher for FTP | [
"",
"c#",
".net",
"ftp",
"filesystemwatcher",
""
] |
I want to create a simple auditing system for my small CodeIgniter application. Such that it would take a snapshot of a table entry before the entry has been edited. One way I could think of would be to create a `news_audit` table, which would replicate all the columns in the news table. It would also create a new record for each change with the added column of date added. What are your views, and opinions of building such functionality into a PHP web application? | There are a few things to take into account before you decide which solution to use:
If your table is large (or could become large) your audit trail needs to be in a seperate table as you describe or performance will suffer.
If you need an audit that can't (potentially) be modified except to add new entries it needs to have INSERT permissions only for the application (and to be cast iron needs to be on a dedicated logging server...)
I would avoid creating audit records in the same table as it might be confusing to another developer (who might no realize they need to filter out the old ones without dates) and will clutter the table with audit rows, which will force the db to cache more disk blocks than it needs to (== performance cost). Also to index this properly might be a problem if your db does not index NULLS. Querying for the most recent version will involve a sub-query if you choose to time stamp them all.
The cleanest way to solve this, if your database supports it, is to create an UPDATE TRIGGER on your news table that copies the old values to a seperate audit table which needs only INSERT permissions). This way the logic is built into the database, and so your applications need not be concerned with it, they just UPDATE the data and the db takes care of keeping the change log. The body of the trigger will just be an INSERT statement, so if you haven't written one before it should not take long to do.
If I knew which db you are using I might be able to post an example... | What we do (and you would want to set up archiving beforehand depending on size and use), but we created an audit table that stores user information, time, and then the changes in XML with the table name.
If you are in SQL2005+ you can then easily search the XML for changes if needed.
We then added triggers to our table to catch what we wanted to audit (inserts, deletes, updates...)
Then with simple serialization we are able to restore and replicate changes. | What Would be a Suitable Way to Log Changes Within a Database Using CodeIgniter | [
"",
"php",
"mysql",
"codeigniter",
""
] |
I'm using Drupal 6.x and I'm writing a php class that will grab an RSS feed and insert it as nodes.
The problem I'm having is that the RSS feed comes with images, and I cannot figure out how to insert them properly.
[This page](http://drupal.org/node/201594) has some information but it doesn't work.
I create and save the image to the server, and then I add it to the node object, but when the node object is saved it has no image object.
This creates the image object:
```
$image = array();
if($first['image'] != '' || $first['image'] != null){
$imgName = urlencode('a' . crypt($first['image'])) . ".jpg";
$fullName = dirname(__FILE__) . '/../../sites/default/files/rssImg/a' . $imgName;
$uri = 'sites/default/files/rssImg/' . $imgName;
save_image($first['image'], $fullName);
$imageNode = array(
"fid" => 'upload',
"uid" => 1,
"filename" => $imgName,
"filepath" => $uri,
"filemime" => "image/jpeg",
"status" => 1,
'filesize' => filesize($fullName),
'timestamp' => time(),
'view' => '<img class="imagefield imagefield-field_images" alt="' . $first['title'] . '" src="/' . $uri . '" /> ',
);
$image = $imageNode;
}
```
and this adds the image to the node:
```
$node->field_images[] = $image;
```
I save the node using
```
module_load_include('inc', 'node', 'node.pages');
// Finally, save the node
node_save(&$node);
```
but when I dump the node object, it no longer as the image. I've checked the database, and an image does show up in the table, but it has no fid. How can I do this? | Why not get the Feedapi, along with feedapi mapper, and map the image from the RSS field into an image CCK field you create for whatever kind of node you're using?
It's very easy, and you can even do it with a user interface.
Just enable feedapi, feedapi node (not sure on the exact name of that module), feedapi mapper, and create a feed.
Once you've created the feed, go to map (which you can do for the feed content type in general as well) on the feed node, and select which feed items will go to which node fields.
You'll want to delete your feed items at this point if they've already been created, and then refresh the feed. That should be all you need to do.
Do you need to create a separate module, or would an existing one work for you?
Are you using hook\_nodeapi to add the image object to the node object when $op = 'prepare'? | If you are just grabbing content wich has images in, why not just in the body of your nodes change the path of the images to absolute rather than local, then you won't have to worry about CCK at all. | How can I programatically add images to a drupal node? | [
"",
"php",
"drupal",
"rss",
""
] |
### Summary
We have to understand which part of our (or third party, probably CLR itself) code leads to boxing of integers.
### Problem description
We have a rather big application where we observe high allocation rate of `System.Int32` instances. With the help of Memory Profiler we see a small number of long existing `Int32` instances (18, to be exact) and 20-25 thousands of `Int32` allocations per second. All those objects are GC collected as Gen0 objects, system has no memory leaks and can be run for long time. When memory snapshot is created, GC is executed before snapshot, so snapshot does not contains any traces of those “temporary” objects.
All our code was specifically written to eliminate boxing whenever possible, and “by design” we are supposed to not see boxings at all. So we suspect it is some non-eliminated forgotten boxing in our code, or boxing caused by third-party component and/or CLR type itself.
System is compiled using VS2008, and uses .Net 3.5 (measurements were done in both debug and release builds, with the same behavior).
### Question
How can we (using windbg, VS2008, Memory Profiler, AQTime or any other commercially available product) detect why boxing happens ? | One of my favorite applications is CLR Profiler this will give you what you are looking for it will map your entire application showing the different generations. It's a free download from Microsoft and it's extremely powerful and simple to use. I have also included a link for how to use it.
[(CLR Profiler Download)](http://www.microsoft.com/downloads/details.aspx?FamilyId=A362781C-3870-43BE-8926-862B40AA0CD0&displaylang=en)
[(How to Use CLR Profiler)](http://msdn.microsoft.com/en-us/library/ms979205.aspx) | Rather surprisingly, methods of DateTime class ToLocalTime/ToUniversalTime cause boxing.
Our application (application server) was recently modified to work "inside" in UTC only (to cope with daylight time changes etc). Our client codebase stayed 99% local time based.
Application server converts (if needed) local times to UTC times before processing, effectively causing boxing overhead on every time-related operation.
We will consider re-implementing those operations "in house", without boxing. | How to detect cause of boxing in .Net? | [
"",
"c#",
".net",
"clr",
""
] |
I am always annoyed by this fact:
```
$ cat foo.py
def foo(flag):
if flag:
return (1,2)
else:
return None
first, second = foo(True)
first, second = foo(False)
$ python foo.py
Traceback (most recent call last):
File "foo.py", line 8, in <module>
first, second = foo(False)
TypeError: 'NoneType' object is not iterable
```
The fact is that in order to correctly unpack without troubles I have either to catch the TypeError or to have something like
```
values = foo(False)
if values is not None:
first, second = values
```
Which is kind of annoying. Is there a trick to improve this situation (e.g. to so set both first and second to None without having foo returning (None, None)) or a suggestion about the best design strategy for cases like the one I present ? \*variables maybe ? | Well, you could do...
```
first,second = foo(True) or (None,None)
first,second = foo(False) or (None,None)
```
but as far as I know there's no simpler way to expand None to fill in the entirety of a tuple. | I don't see what is wrong with returning (None,None). It is much cleaner than the solutions suggested here which involve far more changes in your code.
It also doesn't make sense that you want None to automagically be split into 2 variables. | Returning None or a tuple and unpacking | [
"",
"python",
"return-value",
""
] |
I have a structure of html like this:
```
<div id="triger1">some elements inside</div>
<div id="triger2">some elements inside</div>
<div id="triger3">some elements inside</div>
<div id="triger4">some elements inside</div>
```
How do I get array of all the div's in JQuery with the triger ID in them (as you can see, they all have triger but different numbering eg. triger1, triger2 etc...) | You can use the following:
```
$("div[id^='triger']")
```
This will return all `<div>` with `id` starting (`^=`) with `triger`.
You can get more information about the various jQuery selectors in the jQuery docs:
> [API/Selectors](http://docs.jquery.com/Selectors) | you can actually use a regular expression in a selector to achieve exactly what you are looking for, as such:
```
$("div:regex(id, yourRegularExpression)");
```
(Note: this does require the [regex-selector](http://james.padolsey.com/javascript/regex-selector-for-jquery/) plugin)
Someone asked a similar question [here](https://stackoverflow.com/questions/190253/jquery-selector-regular-expressions).
You can read all about regular expressions [here](http://www.regular-expressions.info/).
As others have pointed out, you can achieve the same result like this:
```
$("div[id^='partOfID']");
```
by using a simple jQuery selector. For more complex selections, though, you will need to use the [regex plugin](http://james.padolsey.com/javascript/regex-selector-for-jquery/) or do it manually, as noted in the [linked question](https://stackoverflow.com/questions/190253/jquery-selector-regular-expressions).
good luck! | JQuery, how to find list of div's with similar ID | [
"",
"javascript",
"jquery",
"html",
"css",
""
] |
I'm using a simple unzip function (as seen below) for my files so I don't have to unzip files manually before they are processed further.
```
function uncompress($srcName, $dstName) {
$string = implode("", gzfile($srcName));
$fp = fopen($dstName, "w");
fwrite($fp, $string, strlen($string));
fclose($fp);
}
```
The problem is that if the gzip file is large (e.g. 50mb) the unzipping takes a large amount of ram to process.
The question: can I parse a gzipped file in chunks and still get the correct result? Or is there a better other way to handle the issue of extracting large gzip files (even if it takes a few seconds more)? | gzfile() is a convenience method that calls gzopen, gzread, and gzclose.
So, yes, you can manually do the gzopen and gzread the file in chunks.
This will uncompress the file in 4kB chunks:
```
function uncompress($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while (!gzeof($sfp)) {
$string = gzread($sfp, 4096);
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
``` | try with
```
function uncompress($srcName, $dstName) {
$fp = fopen($dstName, "w");
fwrite($fp, implode("", gzfile($srcName)));
fclose($fp);
}
```
$length parameter is optional. | Unpack large files with gzip in PHP | [
"",
"php",
"gzip",
""
] |
I have an SSRS report that uses an Oracle datasource. I have a query;
```
select * from myTable t where
t.date between Date '2009-08-01' and Date '2009-08-04' + 1
```
This query works, both in Oracle and from SSRS. It gets all rows from myTable when the t.date column is between 08/01/2009 and 08/04/2009. The t.date column is of type Date()
Now, I want the dates to be parameters. So I changed the query to:
```
select * from myTable t where
t.date between Date :myDate and Date :myDate + 1
```
When I run this query in SSRS, it prompts me to enter a value for :myDate.
I tried 2009-08-01, '2009-08-01' both results in an oracle sql processing error: " Missing expression".
Any ideas? | If you insist on having one parameter (:myDate), using a with clause can make the process a bit cleaner. I'm not familar with the syntax you have in your example (i.e. the 'Date' like casting in the query), below is a SQL only implementation.
```
with
select TRUNC(TO_DATE(:mydate, 'yyyy-mm-dd')) p_date from dual as parameters
select t.*
from
myTable t,
parameters
where
trunc(t.date) between parameters.p_date and parameters.p_date + 1
``` | Just because you have used :myDate twice doesn't mean that they are the same. They are placeholders, and since you have two placeholders you need two values. | Passing date parameters to Oracle Query in SSRS | [
"",
"sql",
"oracle",
"reporting-services",
""
] |
Just wanted to know if ASP.NET supports other browsers as well as it supports Internet explorer?
Also, does Spring/Java framework for a web platform would them in any better way…?
Thanks. | With ASP.NET, the code is all server side, so browsers never even know the difference.
The only things that would affect browser compatibility really would be the generated HTML from the built-in controls and the associated javascript that goes along with them. Personally, I've never seen any problems with those.
The closest thing to a problem that I've run into is with the generated "ID" elements for server controls. Makes it pretty hard to write CSS and Javascript that uses element ID's, so you usually need to use classes instead. But that's not a browser issue as much as just a general PITA. Note that if you use ASP.NET MVC, the "ID" issue is no longer a concern. | It depends more on slicing than on ASP.NET itself. CSS and javascript incompatibilities are not server side related.
If talking about ASP.NET MVC than there is not difference at all between an asp.net mvc generated page and an PHP one. | Browser compatibility | [
"",
"java",
"asp.net",
"cross-browser",
""
] |
I have a class that uses a struct, and I want to overload the << operator for that struct, but only within the class:
```
typedef struct my_struct_t {
int a;
char c;
} my_struct;
class My_Class
{
public:
My_Class();
friend ostream& operator<< (ostream& os, my_struct m);
}
```
I can only compile when I declare the operator<< overload w/ the friend keyword, but then the operator is overloaded everywhere in my code, not just in the class. How do I overload the << operator for my\_struct ONLY within the class?
Edit: I will want to use the overloaded operator to print a my\_struct which IS a member of My\_Class | > How do I overload the << operator for my\_struct ONLY within the class?
Define it as
```
static std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
```
or
```
namespace {
std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //...
}
```
in the `.cpp` file in which you implement `MyClass`.
**EDIT:** If you really, really need to scope on the class and nothing else, then define it as a private static function in said class. It will only be in scope in that class and it's subclasses. It will hide all other custom `operator<<`'s defined for unrelated classes, though (again, only inside the class, and it's subclasses), unless they can be found with ADL, or are members of `std::ostream` already. | Don't use operator <<. Use a named member function, and make it private.
```
class My_Class
{
public:
My_Class();
private:
void Print( ostream & os, const my_struct & m );
};
```
Note you should pass the structure as a const reference, whichever method you use.
**Edit:** There is no need to make the operator << a member of the class just so you can use it to print a member of the class. You can make it a friend of the struct, or a completely free function, which the class then uses. | overload operator<< within a class in c++ | [
"",
"c++",
"operator-overloading",
""
] |
I'm using subversion and nant (and visual studio IDE)
I've been following the suggested project structure at <http://blog.jpboodhoo.com/NAntStarterSeries.aspx> which advocates self contained subversion directories where a developer can do a checkout and immediately build a project in a single step.
My repo structure is like:
```
/Repo
/MainProject
/trunk
/doc <-- documentation
/lib <-- binary-only DLLs
/src <-- source code for MainProject
/tools <-- holds tools like nant, nunit, etc
...
/ClassLibrary1
/trunk
/doc
/lib
/src
/tools
...
/ClassLibrary2
/trunk
/doc
/lib
/src
/tools
```
What's not clear is how to structure a project that has class libraries which in turn reference third party library dll's themselves.
Currently, I have a main project with a working directory like
Example:
```
/MainProject
/build
/lib
/src
/MainProject
/ClassLibrary1 <-- svn external to svn://server/repo/ClassLibrary1/trunk/src
/ClassLibrary2 <-- svn external to svn://server/repo/ClassLibrary2/trunk/src
/tools
...
```
When building MainProject, I compile the class libraries and output the dll's to the build folder. However, the class libraries themselves have 3rd party binary-only DLL's that they reference.
My questions is in order to build the MainProject I have to somehow get the 3rd party DLL's from the class libraries into the build output. How do I do that?
Thoughts:
1. Should I store copies of these 3rd party dlls in the MainProject's lib folder?
2. Or should my svn:external reference be to the trunk of the class library project rather than the src so that I can access the class library's lib folder?
3. Should I use the subversion 1.6 feature of svn:externals to individual files? | Personally I bring in the trunk of the referenced libraries.
(Actually, I bring in the root of a tag, but that's beside the point).
If you keep a separate copy of the required dll's, then you're not really allowing the referenced library to determine what it needs for itself because all that logic is duplicated in the project. The same thing happens if you use multiple externals references or file externals to bring in the code and the dll's.
My principle here is that - the library knows what it needs, a single external reference to the library can get that library and everything it needs.
That way if you change the library's references, you can be confident that any and all projects will just pick that up. (if the IDE doesn't support this, that's the IDE's problem, not subverion's). You can also be confident as a project that if you change the version of the library you're pointing to, you'll automatically get the right references as well, and don't need to go debugging build failures to work out what's gone wrong. | 1. **Should I store copies of these 3rd party dlls in the MainProject's lib folder?** I prefer to store any external libraries in a binaries directory under trunk but next to source...or call it references, dependencies, etc. This then allows any developer to get latest and all that is needed will come down. It doesn't need to be part of the project per se. It just needs to be accessible when the build is performed.
2. **Or should my svn:external reference be to the trunk of the class library project rather than the src so that I can access the class library's lib folder?** I don't prefer this approach as it makes the process of getting a new developer up and running more convoluted. I think an assembly can go into its own repository when it has a level of importance on to itself. But I would never reference its output. It should have a build process wrapped around it that promotes a mechanism to "deploy" the output to the above references or dependencies directory. However automating the deployment like that might be fraught with issues. It would be better if the assembly had its own process around it. And when a new version of the assembly were released it would be manually embraced by a developer on the project that needed it. They could then test it, accept it, and place it into their build process. Obviously if that assembly changes on a daily basis some automation may be required.
3. **Should I use the subversion 1.6 feature of svn:externals to individual files?** No. I prefer to keep a project/solution as a self contained entity. Having tenticals spread out all of the place makes dependencies more painful. Keep silos as hard as possible...bring new things in as manual as possible...or as manual as the frequency that things change will allow. | Nant: How to structure svn:externals for building class libraries that reference 3rd party dll's | [
"",
"c#",
"svn",
"nant",
"class-library",
""
] |
**Env:** Tomcat 5.x on Java 1.5.x on Windows using OracleJDBC driver on Oracle 9i
**The problem:**
I have a thread which is in RUNNABLE state.
It doesn't seem to complete -ever.
How do I investigate this further ?
This is reproducible quite easily.
This thread is basically trying to insert some data
Update: This insert is happening in a synchronized block
This is what I got from the **thread dump..**.
```
"http-9080-Processor24" daemon prio=6 tid=0x0b20bc00 nid=0x1274 runnable [0x0d55e000..0x0d55fc94]
java.lang.Thread.State: RUNNABLE
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at oracle.net.ns.Packet.receive(Unknown Source)
at oracle.net.ns.DataPacket.receive(Unknown Source)
at oracle.net.ns.NetInputStream.getNextPacket(Unknown Source)
at oracle.net.ns.NetInputStream.read(Unknown Source)
at oracle.net.ns.NetInputStream.read(Unknown Source)
at oracle.net.ns.NetInputStream.read(Unknown Source)
at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1099)
at oracle.jdbc.driver.T4CMAREngine.unmarshalSB1(T4CMAREngine.java:1070)
at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:478)
at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:955)
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10580)
- locked <0x02c10078> (a oracle.jdbc.driver.T4CPreparedStatement)
- locked <0x03dceb08> (a oracle.jdbc.driver.T4CConnection)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:294)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
``` | Looks like your application is executing `oracle.jdbc.driver.OraclePreparedStatement.executeBatch()`, which seems to be waiting (forever?) for a NetInputStream to actually return something.
So, is it possible the query/statement being run is never returning? Is it possible your database is hanging? Or it could be possible you've encountered some sort of bug in the Oracle JDBC driver - are you on the most up-to-date version?
You should probably also check if your JDBC driver allows you to specify configurations for connection/query timeouts, etc, to prevent the driver for waiting forever and ever. | RN:
If you have a java core dump file, did you try to use [HPROF tools](http://java.sun.com/developer/technicalArticles/Programming/HPROF.html) from Java SE 5 ?
I usually used this tool as a simple way to find out where a problem was in the source codes. If it does not help, I will probably use [a profiler tool](http://www.eclipse.org/articles/Article-TPTP-Profiling-Tool/tptpProfilingArticle.html). Please correct me if it is wrong for your question.
I hope it helps.
Tiger. | Unresponsive thread in Tomcat | [
"",
"java",
"tomcat",
"multithreading",
""
] |
I am trying to download mp3 file to users machine without his/her consent while they are listening the song.So, next time they visit that web page they would not have to download same mp3, but palypack from the local file. this will save some bandwidth for me and for them. it something pandora used to do but I really don't know how to.
any ideas? | You can't forcefully download files to a user without his consent. If that was possible you can only imagine what severe security flaw that would be.
You can do one of two things:
* count on the browser to cache the media file
* serve the media via some 3rd party plugin (Flash, for example) | Don't do this.
Most files are cached anyway.
But if you really want to add this (because users asked for it), make it optional (default off). | downloading files to users machine? | [
"",
"python",
"django",
"web-applications",
""
] |
Since generics are only checked during compile time with Java 5, can they avoid ClassCastExceptions in all
situations? | First of all, you should make sure that your code compiles without unckeched warnings. That is a good indicator. To understand why, I suggest you take a look at the [sample chapter for generics from Effective Java](http://java.sun.com/docs/books/effective/).
Second of all, generics can't guard you from code such as:
```
public void methodOne(Integer argument) {
methodTwo(argument);
}
public void methodTwo(Object argument) {
System.out.println(((Date) argument).getTime());
}
```
Third of all, if you're in some way or another messing with Class Loaders, you might get strange `ClassCastExceptions`, such as in [this discussion thread](http://www.techienuggets.com/Comments?tx=5498). It is mind-numbing to see
> java.lang.ClassCastException: javax.mail.Session cannot be cast to
> javax.mail.Session
So the answer is *no, you can't get rid of `ClassCastException`s just by properly using generics*. | The "cast-iron" guarantee that Java 5 generics provides is that you will never see a ClassCastException from the casts inserted by the compiler *provided* that compilation produced no "unchecked" warnings.
In real life, you often can't avoid unchecked warnings if your code uses legacy (non-generified) libraries. Then the compiler-generated casts *can* throw ClassCastException, and it's your job to prevent this by ensuring that the values returned by library code are well-typed for your declarations.
Otherwise the situation is unchanged. Outside of generics, if you cast to an incompatible type you'll get a ClassCastException the same way as you always did.
(A good reference for this and other generics questions is [Java Generics and Collections](http://oreilly.com/catalog/9780596527754/).) | Do generics in Java avoid all ClassCastExceptins? | [
"",
"java",
"generics",
"java-6",
"classcastexception",
""
] |
I realise this is a newbie question, but as I'm trying to learn C++ I'm stumpling upon this expression "callback" frequently. I've googled it and checked wikipedia, but without finding a good explination. I am familiar with some Java and C#, but how unlikely it sounds, I have never really understood what a callback means.
If someone know how to explain this term to a simple layman, I would be really thankfull. | > I am familiar with some Java and C#
A callback is an event or delegate in those languages - a way to get *your* code run by somebody else's code in it's context. Hence, the term "callback":
1. You call some other piece of code
2. It runs, perhaps calculating an intermediate value
3. It calls back into your code, perhaps giving you that intermediate value
4. It continues running, eventually passing control back to you by completing
A canonical example is a sort routine with a user defined comparison function (the callback). Given a sort routine such as:
```
void Sort(void* values, int length, int valueSize,
int (*compare)(const void*, const void*)
{
for (int i = 0; i < length; i = i + 2) {
// call the callback to determine order
int isHigher = compare(values[i], values[i + 1]);
/* Sort */
}
}
```
(The specifics of *how* the sort is performed isn't important - just focus on the fact that any sorting algorithm needs to compare 2 values and determine which is higher.)
So, now we can define some comparison functions:
```
int CompareInts(const void* o, const void* p) {
int* a = (int*) o;
int* b = (int*) p;
if (a == b) return 0;
return (a < b) ? -1 : 1;
}
int ComparePersons(const void* o, const void* p) {
Person* a = (Person*) o;
Person* b = (Person*) p;
if (a == b) return 0;
return (a->Value() < b=>Value()) ? -1 : 1;
}
```
And reuse the same sort function with them:
```
int intValues[10];
Person personValues[10];
Sort(intValues, 10, sizeof(intVaues[0]), CompareInts);
Sort(personValues, 10, sizeof(personVaues[0]), ComparePersons);
```
Things get a bit more complicated if you're using member functions, as you have to manage the `this` pointer - but the concept is the same. As with most things, it's easier to explain them in C first. ;) | When you send something a callback, you send it a way of *addressing* a function (for example, a function pointer in C++) so that the code you're sending it to can call that function later, when it's completed some process.
The difference between
```
start_some_process(some_value, some_function()) # not using a callback
```
and
```
start_some_process(some_value, some_function) # using a callback
```
is that in the first instance you're sending the *result* of the function, while in the second instance you're sending *the function itself*. | What is a callback? What is it for and how is it implemented in for example C++ | [
"",
"c++",
"callback",
"managed-c++",
""
] |
I'm running XAMPP on my local machine and on a server in the office. Both are Windows machines.
I'm writing some code that uses `mail()` to send email from a form. By default, it uses `sendmail.exe` (which comes with XAMPP) to send the email. In all cases, the mail is actually sent via a third machine, which is the Exchange server.
From my local machine, PHP can send mail just fine. On the server, upon form submission I get this error:
> Warning: mail() [function.mail]:
> Failed to connect to mailserver at
> "localhost" port 25, verify your
> "SMTP" and "smtp\_\_\_port" setting in
> php.ini or use ini\_set() in
... followed by my filename.
**I don't understand why it's referencing "localhost."** Nowhere in php.ini or sendmail.ini does is "localhost" used - I use the name of the mail server. The SMTP information used on both machines is the same.
As far as I can tell, the two environments have everything important in common:
* The php.ini files are identical
* The sendmail.ini files are identical
* Both machines have the same version of XAMPP installed
* The same batch script will run on both machines and successfully send email via `sendmail.exe`
I have stopped and started Apache several times to make sure it's using the updated config files.
When I get the error above, I notice that no log file is produced by sendmail.exe, which makes me think it's never run.
What am I missing?
# Solved
My problem was that I thought it was using `c:\xampp\php\php.ini`, but it was actually using `c:\xampp\apache\bin\php.ini`. This should have been obvious, and I had previously edited the correct file on my local machine, but somehow I got confused when making the changes on the server.
Using `php_info()` showed me which config file was loaded, and I edited the correct one. It's working now! Thanks everyone for your help. | You should add a call to `phpinfo()` in your page, and check that:
* Your PHP script is using the correct `php.ini`
* Check that the `SMTP` ini settings (as displayed in the phpinfo tables) are correct. | Try to use this in the code on server:
```
ini_set("SMTP","smtp.example.com" );
ini_set('sendmail_from', 'user@example.com');
``` | Why does this PHP error reference localhost? | [
"",
"php",
"email",
"sendmail.exe",
""
] |
I have a string of this form
```
s='arbit'
string='%s hello world %s hello world %s' %(s,s,s)
```
All the %s in string have the same value (i.e. s).
Is there a better way of writing this? (Rather than listing out s three times) | You can use [advanced string formatting](http://www.python.org/dev/peps/pep-3101/), available in Python 2.6 and Python 3.x:
```
incoming = 'arbit'
result = '{0} hello world {0} hello world {0}'.format(incoming)
``` | ```
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
```
You may like to have a read of this to get an understanding: [String Formatting Operations](http://docs.python.org/library/stdtypes.html#string-formatting). | Inserting the same value multiple times when formatting a string | [
"",
"python",
"string",
"format",
""
] |
I have a string that kind of looks like this:
```
"stuff . // : /// more-stuff .. .. ...$%$% stuff -> DD"
```
and I want to strip off all punctuation, make everything uppercase and collapse all whitespace so that it looks like this:
```
"STUFF MORE STUFF STUFF DD"
```
Is this possible with one regex or do I need to combine more than two? This is what I have so far:
```
def normalize(string):
import re
string = string.upper()
rex = re.compile(r'\W')
rex_s = re.compile(r'\s{2,}')
result = rex.sub(' ', string) # this produces a string with tons of whitespace padding
result = rex.sub('', result) # this reduces all those spaces
return result
```
The only thing that doesn't work is the whitespace collapsing. Any ideas? | Here's a single-step approach (but the uppercasing actually uses a string method -- much simpler!):
```
rex = re.compile(r'\W+')
result = rex.sub(' ', strarg).upper()
```
where `strarg` is the string argument (*don't* use names that shadow builtins or standard library modules, *please*). | ```
s = "$$$aa1bb2 cc-dd ee_ff ggg."
re.sub(r'\W+', ' ', s).upper()
# ' AA1BB2 CC DD EE_FF GGG '
```
Is \_ punctuation?
```
re.sub(r'[_\W]+', ' ', s).upper()
# ' AA1BB2 CC DD EE FF GGG '
```
Don't want the leading and trailing space?
```
re.sub(r'[_\W]+', ' ', s).strip().upper()
# 'AA1BB2 CC DD EE FF GGG'
``` | collapsing whitespace in a string | [
"",
"python",
"regex",
""
] |
I would like to get the name of the method that is being delegated as a Func.
```
Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
```
How can I achieve this?
-- For bragging rights --
Make `ExtractMethodName` also work with a property invocation, having it return the property name in that instance.
eg.
```
Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
``` | Look Ma! No expression trees!
Here's a quick, dirty and implementation-specific version that grabs the metadata token from the IL stream of the underlying lambda and resolves it.
```
private static string ExtractMethodName(Func<MyObject, object> func)
{
var il = func.Method.GetMethodBody().GetILAsByteArray();
// first byte is ldarg.0
// second byte is callvirt
// next four bytes are the MethodDef token
var mdToken = (il[5] << 24) | (il[4] << 16) | (il[3] << 8) | il[2];
var innerMethod = func.Method.Module.ResolveMethod(mdToken);
// Check to see if this is a property getter and grab property if it is...
if (innerMethod.IsSpecialName && innerMethod.Name.StartsWith("get_"))
{
var prop = (from p in innerMethod.DeclaringType.GetProperties()
where p.GetGetMethod() == innerMethod
select p).FirstOrDefault();
if (prop != null)
return prop.Name;
}
return innerMethod.Name;
}
``` | I don't think this is possible in the general case. What if you had:
```
Func<MyObject, object> func = x => x.DoSomeMethod(x.DoSomeOtherMethod());
```
What would you expect?
That being said, you could use reflection to open up the Func object and see what it does inside, but you'll only be able to solve it for certain cases. | Retrieving the name of the invoked method executed in a Func | [
"",
"c#",
"delegates",
"lambda",
"methodinfo",
""
] |
When I read a text file to a wide character string (std::wstring) using an wifstream, does the stream implementation support different encodings - i.e. can it be used to read e.g. ASCII, UTF-8, and UTF-16 files?
If not, what would I have to do?
(I need to read the entire file, if that makes a difference) | C++ supports character encodings by means of `std::locale` and the facet `std::codecvt`. The general idea is that a `locale` object describes the aspects of the system that might vary from culture to culture, (human) language to language. These aspects are broken down into `facet`s, which are template arguments that define how localization-dependent objects (include I/O streams) are constructed. When you read from an `istream` or write to a `ostream`, the actual writing of each character is filtered through the locale's facets. The facets cover not only encoding of Unicode types but such varied features as how large numbers are written (e.g. with commas or periods), currency, time, capitalization, and a slew of other details.
However just because the facilities exist to do encodings doesn't mean the standard library actually handles all encodings, nor does it make such code simple to do right. Even such basic things as the size of character you should be reading into (let alone the encoding part) is difficult, as `wchar_t` can be too small (mangling your data), or too large (wasting space), and the most common compilers (e.g. Visual C++ and Gnu C++) *do* differ on how big their implementation is. So you generally need to find external libraries to do the actual encoding.
* [iconv](http://www.gnu.org/software/libiconv/) is generally acknowledge to be correct, but examples of how to bind it to the C++ mechanism are hard to find.
* [jla3ep mentions](https://stackoverflow.com/questions/1274910/does-wifstream-support-different-encodings/1274989#1274989) [libICU](http://site.icu-project.org), which is very thorough but the [C++ API](http://icu-project.org/apiref/icu4c/) does not try to play nicely with the standard (As far as I can tell: you can scan the [examples](http://bugs.icu-project.org/trac/browser/icu/trunk/source/samples) to see if you can do better.)
The most straightforward example I can find that covers all the bases, is from Boost's [UTF-8 codecvt facet](http://www.boost.org/doc/libs/1_39_0/libs/serialization/doc/codecvt.html), with an example that specifically tries to encode UTF-8 (UCS4) for use by IO streams. It looks like this, though I don't suggest just copying it verbatim. It takes a little more digging in [the source](https://svn.boost.org/trac/boost/browser/trunk/boost/detail/utf8_codecvt_facet.hpp) to understand it (and I don't claim to):
```
typedef wchar_t ucs4_t;
std::locale old_locale;
std::locale utf8_locale(old_locale,new utf8_codecvt_facet<ucs4_t>);
...
std::wifstream input_file("data.utf8");
input_file.imbue(utf8_locale);
ucs4_t item = 0;
while (ifs >> item) { ... }
```
To understand more about locales, and how they use facets (including `codecvt`), take a look at the following:
* Nathan Myers has a [thorough explanation of locales and facets](http://www.cantrip.org/locale.html). Myers was one of the designers of the locale concept. He has [more formal documentation](http://www.cantrip.org/lib-locales.html) if you want to wade through it.
* Apache's Standard Library implementation (formerly RogueWave's) has a [full list of facets](http://stdcxx.apache.org/doc/stdlibug/24-2.html).
* Nicolai Josuttis' [The C++ Standard Library](http://www.josuttis.com/libbook/) Chapter 14 is devoted to the subject.
* Angelika Langer and Klaus Kreft's [Standard C++ IOStreams and Locales](https://rads.stackoverflow.com/amzn/click/com/0201183951) devotes a whole book. | `ifstream` does not care about encoding of file. It just reads chars(bytes) from file. `wifstream` reads wide bytes(`wchar_t`), but it still doesn't know anything about file encoding. `wifstream` is good enough for UCS-2 — fixed-length character encoding for Unicode (each character represented with two bytes).
You could use IBM [ICU](http://site.icu-project.org/home) library to deal with Unicode files.
> The International Component for Unicode (ICU) is a mature, portable set of C/C++ and Java libraries for Unicode support, software internationalization (I18N) and globalization (G11N), giving applications the same results on all platforms.
>
> ICU is released under a nonrestrictive open source license that is suitable for use with both commercial software and with other open source or free software. | does (w)ifstream support different encodings | [
"",
"c++",
"unicode",
"stl",
"character-encoding",
"wifstream",
""
] |
I'm trying to connect to Gmail through IMAP with PHP running in Apache. This is on an Ubuntu 9.04 system. I've got some sort of PHP configuration issue that is keeping this from working. First, here's what I did to setup IMAP for PHP:
```
sudo apt-get install libc-client2007b libc-client2007b-dev
sudo apt-get install php5-imap
sudo /etc/init.d/apache2 start
```
When I run phpinfo(), I get the following imap values:
```
IMAP c-Client Version: 2004
SSL Support: enabled
Kerberos Support: enabled
```
Here's my sample code:
```
<?php
$connect_to = '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX';
$user = 'my gmail address';
$password = 'my gmail password';
$connection = imap_open($connect_to, $user, $password)
or die("Can't connect to '$connect_to': " . imap_last_error());
imap_close($connection);
?>
```
When I execute this code, I get the following output:
```
Warning: imap_open() [function.imap-open]: Couldn't open stream {imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX in /var/www/clint/gmail/gmail.php on line 10
Can't connect to '{imap.gmail.com:993/imap/ssl/novalidate-cert}INBOX': TLS/SSL failure for imap.gmail.com: SSL context failed
```
Note that I can telnet to imap.gmail.com:993 from this computer. I can also hookup Evolution (mail reader) to Gmail through IMAP and fetch mail without problems. So, I don't think this is a firewall issue. I'm pretty sure I've got something in PHP not setup correctly.
Any ideas? | One more additional thing you need enabled in PHP, is the [OpenSSL extension](http://php.net/manual/en/book.openssl.php). It appears that the IMAP Client library (with SSL) depends on this.
It doesn't matter if Apache has the OpenSSL module enabled as this is processed/handled before the request is handed off to PHP.
The following discussion thread may help shed some light:
<http://groups.google.com/group/comp.lang.php/browse_thread/thread/241e619bc70a8bf4/bd3ae0c6a82409bc?lnk=raot&pli=1> | This has worked for me after a long effort:
```
$ServerName = "{imap.gmail.com:993/imap/ssl/novalidate-cert/norsh}Inbox";
``` | Connecting to Gmail through IMAP with PHP - SSL context failed | [
"",
"php",
"ssl",
"ubuntu",
"gmail",
"imap",
""
] |
I have a base class:
```
class RedBlackTreeNode
{
// Interface is the same as the implementation
public:
RedBlackTreeNode* left;
RedBlackTreeNode* right;
RedBlackTreeNode* parent;
Color color;
TreeNodeData* data;
RedBlackTreeNode():
left(0),
right(0),
parent(0),
color(Black),
data(0)
{
}
// This method is to allow dynamic_cast
virtual void foo()
{
}
};
```
and a derived from it one:
```
class IndIntRBNode : public RedBlackTreeNode
{
public:
IndIntRBNode* left;
IndIntRBNode* right;
IndIntRBNode* parent;
IndexedInteger* data;
IndIntRBNode():
RedBlackTreeNode(),
left(0),
right(0),
parent(0),
color(Black),
data(0)
{
}
};
```
root() and rootHolder are defined in RedBlackTree class:
```
class RedBlackTree
{
public:
RedBlackTreeNode rootHolder;
RedBlackTreeNode* root()
{
return rootHolder.left;
}
...
}
```
Then I'm trying to typecast:
```
IndIntRBNode *x, *y, *z;
z = dynamic_cast<IndIntRBNode*>(root());
```
And "z" just becomes a zero-pointer, which means that typecast failed.
So what's wrong with it, how can I fix it to be able to reference "z" as pointer to the IndIntRBNode?
Added: the initialization of the rootHolder.left was some kind of that:
```
int n = atoi(line + i);
tree.clear();
int j = 0;
if (n > 100)
{
n = 100; // Maximum 100 nodes
}
while (j < n)
{
IndexedInteger num(j,j + 10);
RedBlackTreeNode* node;
int c = tree.search(&num, tree.root(), &node);
if (c != 0)
{ // if value is not in the tree
IndexedInteger* v = new IndexedInteger(num);
tree.insert(node, v, c);
++j;
}
}
```
In the other words, it was initialized on the first iteration of "while" by the "insert" method in such way:
```
void RedBlackTree::insert(
RedBlackTreeNode* parentNode,
TreeNodeData* v,
// If it's negative, then add as the left son, else as the right
int compare
)
{
assert(parentNode != 0 && compare != 0);
RedBlackTreeNode* x = new RedBlackTreeNode;
x->data = v;
x->parent = parentNode;
// If it's root
if (parentNode == &rootHolder)
{
// Then it must be black
x->color = Black;
}
else
{
// Leaf must be red
x->color = Red;
}
if (compare < 0)
{
// Insert the node as the left son
assert(parentNode->left == NULL);
parentNode->left = x;
}
else
{
// Insert the node as the right son
assert(parentNode != &rootHolder && parentNode->right == NULL);
parentNode->right = x;
}
++numNodes;
if (x != root())
{
rebalanceAfterInsert(x);
}
}
```
It actually was the problem: "insert" created the RedBlackTreeNode dinamically, so it couldn't be IndIntRBNode.
I really have initialized it wrong, but then how can I derive the base class and not write the whole implementation of it from a scratch just to change the types?
Do I really have to override all the "type-relative" methods in the derived class? It seems to be very stupid, I think there should be the other way - something with class deriving and typecasting, isn't it? | Are you sure that RedBlackTree::rootHolder.left has been initialized?
I think you somewhere initialized IndIntRBNode::left, but when you are accessing RedBlackTree::rootHolder.left you are accessing RedBlackTreeNode::left, which is not the same field. | If I'm reading your code correctly, you are not setting `rootHolder.left` to a `IndIntRBNode` pointer at all, but a vanilla `RedBlackTreeNode`.
Also, you don't need to make up a useless virtual function for polymorphism; just declare the destructor to be `virtual` and provide an empty implementation. Your use of polymorphism also isn't that great, as the `IndIntRBNode` members will hide the `RedBlackTreeNode` members, so they may well point to different things depending on whether you access them through an `IndIntRBNode` pointer/reference or a `RedBlackTreeNode` pointer/reference. | Base-to-derived class typecast | [
"",
"c++",
"class",
"dynamic",
"casting",
""
] |
I have a function which returns a variable number of elements, should I return an array or a List? The "collection's" size does not change once returned, ie for all purposes the collection is immutable. I would think to just return an array, but some people have said to not return variable sized arrays from a function as it is "poor form". Not sure why?
Does it matter that this needs to be .NET 2.0 compliant? | It's bad form to return arrays if not needed, and especially to return `List<T>`.
Usually, you'll want to return `IEnumerable<T>` or `IList<T>`.
If your user is going to just need to run through each element, `IEnumerable<T>` will provide this capability. It also allows you to potentially implement the routine (now or later) using deferred execution.
If your user needs to access elements by index, return `IList<T>`. This provides all of the benefits of arrays, but gives you more flexibility in your implementation. You can implement it as an array, a list, or some other collection that implements `IList<T>`, and you don't have to convert/copy to an array. | One opinion I see pretty often a suggestion to return either `IList<T>` or `ReadOnlyCollection<T>`. It's OK to return these if you have one of these available - both can be assigned directly to an `IEnumerable<T>` (they work directly with any LINQ methods). One thing to note is `ReadOnlyCollection<T>` is a very lightweight type that can wrap any `IList<T>`. | Is it bad form to return Arrays in C#? Should I return List<T>? | [
"",
"c#",
""
] |
I have a string:
```
$string = "12,15,22";
```
Each of these values represents a usrID and I'd like to use these to select the rows associated with the $string.
Something like this:
```
SELECT usrFirst, usrLast FROM tblusers WHERE usrID = 12 OR 15 OR 22.
```
Now, the $string changes all the time, and sometimes can be a different number of ID's. Eg., sometimes 3, sometimes 4.
Thanks! | use IN, although it is very slow if you have lots of numbers:
```
SELECT usrFirst, usrLast FROM tblusers WHERE usrID IN ($string)
```
[W3Schools](http://www.w3schools.com/sql/sql_in.asp) has more info on IN.
If you have lots of numbers, have a look [here](https://stackoverflow.com/questions/1220142/how-to-optimize-this-mysql-slow-very-slow-query) for info on how to speed this up. | you can do something like:
SELECT usrFirst, usrLast FROM tblusers WHERE usrID in (12, 15, 22); | PHP/MySQL / Use String to SELECT from Database | [
"",
"php",
"mysql",
"select",
""
] |
What is the best way in php to take the following string mm[some char]dd[some char]yyyy and translate it to yyyymmdd?
I will probably want in the future, according to local do the same with dd[some char]mm[some char]yyyy.
If there is a way that already uses the Zend Framework API, the better | ```
<?php
$str = '08-24-1989'; // can be in any recognizable date format.
$new_str = date('Ymd', strtotime($str)); // produces "20090824".
?>
```
You can replace `Ymd` in the second statement above with any date format characters found [here](https://www.php.net/manual/en/function.date.php).
If you're looking to use Zend's Zend\_Date framework, check out some examples and documentation [here](http://framework.zend.com/manual/en/zend.date.html). Quite frankly though, the PHP functions are a lot simpler and easier to use in your case. | `date('Ymd', strtotime($time));`
[Strtotime](https://www.php.net/manual/en/function.strtotime.php) is absolutely the best tool to translate almost any time format into a standard one that you can then use [Date](https://www.php.net/manual/en/function.date.php) to put into the format you want.
Because you question title says MySQL Dates, this is the string format that mysql uses.
`date('Y-m-d h:i:s', strtotime($time));` | what is the best method to translate strings to mysql dates? | [
"",
"php",
"mysql",
"zend-framework",
"date",
""
] |
I have created a class library using c#.And i have registered the class library using
regasm..
```
RegAsm.exe Discovery.dll /tlb: Discovery.dll /codebase
```
Now i want to know whether the assembly is registered or not using c++. I need because I have to check the registry for this dll if it is not registered I have to registered it
programatically if it is registered then i simply skip it.
so How can i know whether the assembly registered or not using c++... | Why do you need to bother at all? There is no harm to registering it again if it IS already there. | Use LoadRegTypeLib to load it, and check the return value for errors. For example:
```
HRESULT hr;
ITypeLib *libraryIntf;
hr = LoadRegTypeLib(IID_GuidOfTypeLibrary, LibraryVersionMajor,
LibraryVersionMinor, 0, &libraryIntf);
if(SUCCEEDED(hr))
{
libraryIntf->Release();
libraryIntf = NULL;
// Type library is registered and can be loaded.
}
else
{
// Type library is not registered.
}
``` | How to check whether the tlb file is registered in registry using C++? | [
"",
"c++",
"visual-c++",
"registry",
""
] |
Is it possible to change this code, with a return value and an exception:
```
public Foo Bar(Bar b)
{
if(b.Success)
{
return b;
}
else
{
throw n.Exception;
}
}
```
to this, which throws separate exceptions for success and failure
```
public Foo Bar(Bar b)
{
throw b.Success ? new BarException(b) : new FooException();
}
try
{
Bar(b)
}
catch(BarException bex)
{
return ex.Bar;
}
catch(FooException fex)
{
Console.WriteLine(fex.Message);
}
``` | Throwing an exception is definitely more expensive than returning a value. But in terms of raw cost it's hard to say how much more expensive an exception is.
When deciding on a return value vs. an exception you should always consider the following rule.
> Only use exceptions for exceptional circumstances
They shouldn't ever be used for general control flow. | Using the code below, testing revealed that the the call+return with no exceptions took about 1.6 microseconds per iteration, whereas exceptions (throw plus catch) added about *4000* microseconds each.(!)
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DateTime start = DateTime.Now;
bool PreCheck = chkPrecheck.Checked;
bool NoThrow = chkNoThrow.Checked;
int divisor = (chkZero.Checked ? 0 : 1);
int Iterations = Convert.ToInt32(txtIterations.Text);
int i = 0;
ExceptionTest x = new ExceptionTest();
int r = -2;
int stat = 0;
for(i=0; i < Iterations; i++)
{
try
{
r = x.TryDivide(divisor, PreCheck, NoThrow);
}
catch
{
stat = -3;
}
}
DateTime stop = DateTime.Now;
TimeSpan elapsed = stop - start;
txtTime.Text = elapsed.TotalMilliseconds.ToString();
txtReturn.Text = r.ToString();
txtStatus.Text = stat.ToString();
}
}
class ExceptionTest
{
public int TryDivide(int quotient, bool precheck, bool nothrow)
{
if (precheck)
{
if (quotient == 0)
{
if (nothrow)
{
return -9;
}
else
{
throw new DivideByZeroException();
}
}
}
else
{
try
{
int a;
a = 1 / quotient;
return a;
}
catch
{
if (nothrow)
{
return -9;
}
else
{
throw;
}
}
}
return -1;
}
}
```
So yes, Exceptions are *VERY* expensive.
And before someone says it, YES, I tested this in *Release* mode and not just *Debug* mode. Try the code yourself and see if you get significantly different results. | How much more expensive is an Exception than a return value? | [
"",
"c#",
".net",
"exception",
"return-value",
""
] |
Which Java class should you use for time performance measurements?
(One could use any date/time class, but the reason I'm asking is in .Net there's a designated [Stopwatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class for this purpose) | The Spring Framework has an excellent [`StopWatch` class](http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/util/StopWatch.html):
```
StopWatch stopWatch = new StopWatch("My Stop Watch");
stopWatch.start("initializing");
Thread.sleep(2000); // simulated work
stopWatch.stop();
stopWatch.start("processing");
Thread.sleep(5000); // simulated work
stopWatch.stop();
stopWatch.start("finalizing");
Thread.sleep(3000); // simulated work
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
```
This produces:
```
StopWatch 'My Stop Watch': running time (millis) = 10000
-----------------------------------------
ms % Task name
-----------------------------------------
02000 020% initializing
05000 050% processing
03000 030% finalizing
``` | This is an example how to use StopWatch to set multiple measurements by annotating dedicated methods. Very useful and very simple to use to measure e.g. Service call over multiple embedded call / operation and so on.
StopWatchHierarchy
```
package ch.vii.spring.aop;
import java.util.Arrays;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
@Component
public class ProfilingMethodInterceptor implements MethodInterceptor {
private static final Logger log = LoggerFactory.getLogger(ProfilingMethodInterceptor.class);
public Object invoke(MethodInvocation invocation) throws Throwable {
if (log.isInfoEnabled()) {
String stopWatchName = invocation.getMethod().toGenericString();
StopWatchHierarchy stopWatch = StopWatchHierarchy.getStopWatchHierarchy(stopWatchName);
String taskName = invocation.getMethod().getName();
stopWatch.start(taskName);
try {
return invocation.proceed();
} finally {
stopWatch.stop();
}
} else {
return invocation.proceed();
}
}
static class StopWatchHierarchy {
private static final ThreadLocal<StopWatchHierarchy> stopwatchLocal = new ThreadLocal<StopWatchHierarchy>();
private static final IndentStack indentStack = new IndentStack();
static StopWatchHierarchy getStopWatchHierarchy(String id) {
StopWatchHierarchy stopWatch = stopwatchLocal.get();
if (stopWatch == null) {
stopWatch = new StopWatchHierarchy(id);
stopwatchLocal.set(stopWatch);
}
return stopWatch;
}
static void reset() {
stopwatchLocal.set(null);
}
final StopWatch stopWatch;
final Stack stack;
StopWatchHierarchy(String id) {
stopWatch = new StopWatch(id);
stack = new Stack();
}
void start(String taskName) {
if (stopWatch.isRunning()) {
stopWatch.stop();
}
taskName = indentStack.get(stack.size) + taskName;
stack.push(taskName);
stopWatch.start(taskName);
}
void stop() {
stopWatch.stop();
stack.pop();
if (stack.isEmpty()) {
log.info(stopWatch.prettyPrint());
StopWatchHierarchy.reset();
} else {
stopWatch.start(stack.get());
}
}
}
static class Stack {
private int size = 0;
String elements[];
public Stack() {
elements = new String[10];
}
public void push(String e) {
if (size == elements.length) {
ensureCapa();
}
elements[size++] = e;
}
public String pop() {
String e = elements[--size];
elements[size] = null;
return e;
}
public String get() {
return elements[size - 1];
}
public boolean isEmpty() {
return size == 0;
}
private void ensureCapa() {
int newSize = elements.length * 2;
elements = Arrays.copyOf(elements, newSize);
}
}
static class IndentStack {
String elements[] = new String[0];
public String get(int index) {
if (index >= elements.length) {
ensureCapa(index + 10);
}
return elements[index];
}
private void ensureCapa(int newSize) {
int oldSize = elements.length;
elements = Arrays.copyOf(elements, newSize);
for (int i = oldSize; i < elements.length; i++) {
elements[i] = new String(new char[i]).replace("\0", "| ");
}
}
}
}
```
Advisor
```
package ch.vii.spring.aop;
import java.lang.reflect.Method;
import org.aopalliance.aop.Advice;
import org.springframework.aop.Pointcut;
import org.springframework.aop.support.AbstractPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ProfilingAdvisor extends AbstractPointcutAdvisor {
private static final long serialVersionUID = 1L;
private final StaticMethodMatcherPointcut pointcut = new StaticMethodMatcherPointcut() {
public boolean matches(Method method, Class<?> targetClass) {
return method.isAnnotationPresent(ProfileExecution.class);
}
};
@Autowired
private ProfilingMethodInterceptor interceptor;
public Pointcut getPointcut() {
return this.pointcut;
}
public Advice getAdvice() {
return this.interceptor;
}
}
```
ProfileExecution Annotation
```
package ch.vii.spring.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface ProfileExecution {
}
```
Annotate your code
```
package ch.vii.spring;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ch.vii.spring.aop.ProfileExecution;
@Component
public class Bean {
@Autowired
InnerBean innerBean;
@ProfileExecution
public void foo() {
innerBean.innerFoo();
innerBean.innerFoo2();
innerBean.innerFoo();
}
}
public class InnerBean {
@Autowired
InnerInnerBean innerInnerBean;
@ProfileExecution
public void innerFoo() {
}
@ProfileExecution
public void innerFoo2() {
innerInnerBean.innerInnerFoo();
innerInnerBean.innerInnerFoo();
innerInnerBean.innerInnerFoo();
}
}
```
Output
```
09:58:39.627 [main] INFO c.v.s.aop.ProfilingMethodInterceptor - StopWatch 'public void ch.vii.spring.Bean.foo()': running time (millis) = 215
-----------------------------------------
ms % Task name
-----------------------------------------
00018 008 % foo
00026 012 % | innerFoo
00001 000 % foo
00016 007 % | innerFoo2
00038 018 % | | innerInnerFoo
00000 000 % | innerFoo2
00024 011 % | | innerInnerFoo
00028 013 % | innerFoo2
00024 011 % | | innerInnerFoo
00029 013 % | innerFoo2
00000 000 % foo
00011 005 % | innerFoo
00000 000 % foo
``` | Stopwatch class for Java | [
"",
"java",
"performance",
"measurement",
""
] |
What does bind and unbind mean in jquery in idiot slow learner terms? | Binding: coupling an **handler** to an **element**(s), that will run when an **event** occurs on said element(s). Depending on what kind of event you want to handle you'd use different functions like `click(function)` (alt: `bind('click', function)` or `focus(function)` (alt: `bind('focus', function)`.
Unbinding: de-coupling of an **handler** from an **element(s)**, so that when an **event** occurs the handler function will no longer run. Unbinding is always the same; `unbind('click', function)` to unbind a certain handler, `unbind('click')` to unbind ALL click handlers, and `unbind()` to unbind ALL handlers. You can substitute `click` for other types of events of course. | In simple terms: for [binding](http://docs.jquery.com/Events/bind) and [unbinding](http://docs.jquery.com/Events/unbind) event handlers to elements.
```
$("#divElement").bind('click', functionName);
```
binds a click event handler to the element with id divElement
```
$("#divElement").unbind('click', functionName);
```
unbinds a click event handler to the element with id divElement
Edit:
**Bind also allows you to bind a handler to one or more events.**
```
$("#divElement").bind("click dblclick mouseout", function(){ // your code });
```
Update:
As of jQuery 1.7, the [.on()](http://api.jquery.com/on/) and [.off()](http://api.jquery.com/off/) methods are preferred to attach and remove event handlers on elements. | What does bind and unbind mean in jquery? | [
"",
"javascript",
"jquery",
"binding",
""
] |
One of the major reasons for using webforms is the ease of being able to maintain viewstate. I would like to build an asp.net mvc application so what options do I have for maintaining viewstate?
Kind regards | ASP.NET MVC does not use ViewState in the traditional sense (that of storing the values of controls in the web page). Rather, the values of the controls are posted to a controller method. Once the controller method has been called, what you do with those values is up to you.
ASP.NET MVC will persist the values of the controls long enough for you to validate them and (if needed) to round-trip them back to your page for editing or correction. If the controls validate, you can persist them to a database or other data store, where they will be available for subsequent GET requests. | You can imitate view state by serializing model in view using [MVC3Futures project](http://nuget.org/packages/Mvc3Futures/)
All you have to do is to serialize model and encrypt it in view.
```
@Html.Serialize("Transfer", Model, SerializationMode.EncryptedAndSigned)
```
And in controller add deserialized attribute.
```
public ActionResult Transfer(string id,[Deserialize(SerializationMode.EncryptedAndSigned)]Transfer transfer)
``` | Maintaining viewstate in Asp.net mvc? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"viewstate",
""
] |
When joining to a subset of a table, any reason to prefer one of these formats over the other?
Subquery version:
```
SELECT ...
FROM Customers AS c
INNER JOIN (SELECT * FROM Classification WHERE CustomerType = 'Standard') AS cf
ON c.TypeCode = cf.Code
INNER JOIN SalesReps s ON cf.SalesRepID = s.SalesRepID
```
vs the WHERE clause at the end:
```
SELECT ...
FROM Customers AS c
INNER JOIN Classification AS cf ON c.TypeCode = cf.Code
INNER JOIN SalesReps AS s ON cf.SalesRepID = s.SalesRepID
WHERE cf.CustomerType = 'Standard'
```
The WHERE clause at the end feels more "traditional", but the first is arguably more clear, especially as the joins get increasingly complex.
Only other reason I can think of to prefer the second is that the "SELECT \*" on the first might be returning columns that aren't used later (In this case, I'd probably only need to return cf.Code and Cf.SalesRepID) | What about a third option?
```
SELECT ...
FROM Customers AS c
INNER JOIN Classification AS cf
ON cf.CustomerType = 'Standard'
AND c.TypeCode = cf.Code
INNER JOIN SalesReps AS s
ON cf.SalesRepID = s.SalesRepID
```
Personally, I prefer to use `JOIN` syntax to indicate the statements on which the overall set is defined, the foreign keys or other conditions that indicate two rows should be joined to make a row in the result set.
The `WHERE` clause contains the criteria which filter my result set. Arguably, this can become quite bloaty and complicated when you are performing a number of joins, however when you think in sets it follows a kind of logic:
* `SELECT` what columns I want.
* `JOIN` tables to define the set I want to get rows from.
* Filter out rows `WHERE` my criteria are not met.
By this logic, I'd always choose your second syntax for consistent readability. | The second clause is definitely more clear, and I suspect the optimizer will like it better too. And ideally you should specify the columns you need. | Subquery vs Traditional join with WHERE clause? | [
"",
"sql",
"sql-server",
""
] |
Is there any way to tell whether a **string** represents an integer (e.g., `'3'`, `'-17'` but not `'3.14'` or `'asfasfas'`) Without using a try/except mechanism?
```
is_int('3.14') == False
is_int('-7') == True
``` | If you're really just annoyed at using `try/except`s all over the place, please just write a helper function:
```
def represents_int(s):
try:
int(s)
except ValueError:
return False
else:
return True
```
```
>>> print(represents_int("+123"))
True
>>> print(represents_int("10.0"))
False
```
It's going to be WAY more code to exactly cover all the strings that Python considers integers. I say just be pythonic on this one. | with positive integers you could use [`.isdigit`](http://docs.python.org/library/stdtypes.html#str.isdigit):
```
>>> '16'.isdigit()
True
```
it doesn't work with negative integers though. suppose you could try the following:
```
>>> s = '-17'
>>> s.startswith('-') and s[1:].isdigit()
True
```
it won't work with `'16.0'` format, which is similar to `int` casting in this sense.
**edit**:
```
def check_int(s):
if s[0] in ('-', '+'):
return s[1:].isdigit()
return s.isdigit()
``` | How can I check if a string represents an int, without using try/except? | [
"",
"python",
"string",
"integer",
""
] |
Are there **any good reasons** (except "macros are evil", maybe) **NOT to use the following macros ?**
```
#define DELETE( ptr ) \
if (ptr != NULL) \
{ \
delete ptr; \
ptr = NULL; \
}
#define DELETE_TABLE( ptr ) \
if (ptr != NULL) \
{ \
delete[] ptr; \
ptr = NULL; \
}
``` | Personally I prefer the following
```
template< class T > void SafeDelete( T*& pVal )
{
delete pVal;
pVal = NULL;
}
template< class T > void SafeDeleteArray( T*& pVal )
{
delete[] pVal;
pVal = NULL;
}
```
They compile down to EXACTLY the same code in the end.
There may be some odd way you can break the #define system but, personally (And this is probably going to get me groaned ;) I don't think its much of a problem. | Because it doesn't actually solve many problems.
In practice, most dangling pointer access problems come from the fact that another pointer to the same object exists elsewhere in the program and is later used to access the object that has been deleted.
Zeroing out one of an unknown number of pointer copies might help a bit, but usually this is a pointer that is either about to go out of scope, or set to point to a new object in any case.
From a design point of view, manually calling `delete` or `delete[]` should be relatively rare. Using objects by value instead of dynamically allocated objects where appropriatem using `std::vector` instead of dynamically allocated arrays and wrapping the ownership of objects that have to be dynamically allocated in an appropriate smart pointer (e.g. `auto_ptr`, `scoped_ptr` or `shared_ptr`) to manage their lifetime are all design approaches that make replacing `delete` and `delete[]` with a "safer" macro a comparatively low benefit approach. | Reason why not to have a DELETE macro for C++ | [
"",
"c++",
"pointers",
"memory-management",
"macros",
""
] |
I'm trying to get a list of related articles. Example
```
$title = $fetch_content[article_name]; // example out put "Hello World, Ask A Question"
$rel_title = "Select * from tbl_content WHERE status='t' and article_name like '%$title' order by id desc limit 5";
```
How to separate the "Hello World, Ask A Question" into single keywords. | You can use the [split](https://www.php.net/manual/en/function.split.php) function in PHP to break that title up into each word:
```
$title_words = split($title);
$rel_title = 'select * from tbl_content where status = \'t\' and (1=0';
foreach($title as $word)
{
$word = str_replace(',', '', $word);
$word = mysql_real_escape_string($word);
$rel_title .= ' or article_title like \'%' . $word . '%\'';
}
$rel_title .= ')';
echo $rel_title;
```
I also used [`str_replace`](https://www.php.net/manual/en/function.str-replace.php) to remove the comma in the question. Obviously, you can apply this to other characters if you have them. | It should be noted that..
```
like '%$title'
```
...will only match items like which end in 'title', so you might want to do...
```
LIKE '%$title%'
```
...if you simply want items that contain 'title'. I also presume that the $title variable has already been escaped. If not, do...
```
LIKE '%" . mysql_real_escape_string($title) . "%'
``` | Finding Related Article with the MySQL LIKE Statement | [
"",
"php",
"mysql",
""
] |
I understand that there is no multithreading support in javascript. And i wanted some expert advice on the below scenario..
My requirement is to perform a AJAX call and upon successful completetion, i want to trigger set of events (to update the different parts of UI parallely)
* I am planned to use Subscribe/Publish pattern, is it possible to subscribe multiple listners to the AJAX completion event.
* If possible, i wanted to know how these listners notified on publish.. (parallely in muthithreaded way or one by one).
And suggest me the best way to achive this one.. I really appreciate your thoughts.
**EDIT::**
I know there are popular frameworks like JQuery supports this pattern. But am in a situation to develop this functionality from a scratch (we have our own framework). | I've a Request Pooler that might give you a good head-start here. [Since this answer was accepted I've retired the pooler in favor of a more complete "AJAX Helper" - the link has been updated.]
I'm not sure that'll do everything you want (although it sounds like it may be close). It's old, but it works:
[Depressed Press DP\_AJAX](http://depressedpress.com/javascript-extensions/dp_ajax/)
It supports multiple simultaneous requests with timeout/retry, per-request handlers, has a very small footprint and can be combined with other code easily.
You create a pool (telling it how many simultaneous requests are allowed) and then toss requests at it. When they're done they call whatever handler you specified.
A small, complete example of it's use:
```
// The handler function
function AddUp(Num1, Num2, Num3) {
alert(Num1 + Num2 + Num3);
};
// Instantiate the Pool
myRequestPool = new DP_RequestPool(4);
// Start the Interval
myRequestPool.startInterval(100);
// Create the Request
myRequest = new DP_Request(
"GET",
"http://www.mysite.com/Add.htm",
{"FirstNum" : 5, "SecondNum" : 10},
AddUp,
[7,13]);
// Add the request to the queue
myRequestPool.addRequest(myRequest);
```
It's open source - feel free to chop/fold/spindle or mutilate it to your hearts content.
Jim Davis | [This article](http://madskristensen.net/post/Simple-JavaScript-event-model.aspx) describes what you're trying to accomplish pretty closely. Essentially you just have a JavaScript file that holds an array of handlers/subscribers. Each subscriber registers itself with the publisher (i.e. gets added to the handlers array). Then in the onClose handler of your Ajax call, you'd call a function that iterates over the subscribers and notifies them each by name:
```
this.handlers = [];
...
for(var i = 0; i < this.handlers.length; i++)
{
this.handlers[i].eventHandler.call(this, eventArgs);
}
...
``` | multithreading And Subscribe/Publish approach in javascript | [
"",
"javascript",
"ajax",
"multithreading",
"publish-subscribe",
""
] |
I have created several SQL database change scripts, and placed them in a folder. Is there an easy way of combining a few of them into one file or executable so that it's easier for my partner to execute them on his database?
Thanks for any help! | Found Simple File Joiner - <http://www.peretek.com/sfj.php> - does the job well and it's free! =]
Also, it seems to work on any extension, not just text files... which is ubber cool! | You can do this with the **COPY** command, by using the /a switch (for ASCII).
```
copy *.sql /a one_big_script.sql
```
I typically place this command in a batch file ("make.bat") and then simply double-click it to run it and create one script out of several smaller files. | Combining ASP.net SQL 2005 Change Scripts | [
"",
"asp.net",
"sql",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.