text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: WCF - How to accept long strings as parameters I have a simple web service, it takes 2 parameters one is a simple xml security token, the other is usually a long xml string. It works with short strings but longer strings give a 400 error message. maxMessageLength did nothing to allow for longer strings.
A: After the answer on quotas I just did all that in the web.config
<bindings>
<wsHttpBinding>
<binding name="WSHttpBinding_IPayroll" maxReceivedMessageSize="6553600">
<security mode="None"/>
<readerQuotas maxDepth="32"
maxStringContentLength="6553600"
maxArrayLength="16384"
maxBytesPerRead="4096"
maxNameTableCharCount="16384" />
</binding>
</wsHttpBinding>
</bindings>
A: You should remove the quotas limitations as well.
Here is how you can do it in code with Tcp binding.
I have added some code that shows removal of timeout problems because usually sending very big arguments causes timeout issues. So use the code wisely...
Of course, you can set these parameters in the config file as well.
NetTcpBinding binding = new NetTcpBinding(SecurityMode.None, true);
// Allow big arguments on messages. Allow ~500 MB message.
binding.MaxReceivedMessageSize = 500 * 1024 * 1024;
// Allow unlimited time to send/receive a message.
// It also prevents closing idle sessions.
// From MSDN: To prevent the service from aborting idle sessions prematurely increase the Receive timeout on the service endpoint's binding.’
binding.ReceiveTimeout = TimeSpan.MaxValue;
binding.SendTimeout = TimeSpan.MaxValue;
XmlDictionaryReaderQuotas quotas = new XmlDictionaryReaderQuotas();
// Remove quotas limitations
quotas.MaxArrayLength = int.MaxValue;
quotas.MaxBytesPerRead = int.MaxValue;
quotas.MaxDepth = int.MaxValue;
quotas.MaxNameTableCharCount = int.MaxValue;
quotas.MaxStringContentLength = int.MaxValue;
binding.ReaderQuotas = quotas;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to keep from duplicating path variable in csh It is typical to have something like this in your cshrc file for setting the path:
set path = ( . $otherpath $path )
but, the path gets duplicated when you source your cshrc file multiple times, how do you prevent the duplication?
EDIT: This is one unclean way of doing it:
set localpaths = ( . $otherpaths )
echo ${path} | egrep -i "$localpaths" >& /dev/null
if ($status != 0) then
set path = ( . $otherpaths $path )
endif
A: ok, not in csh, but this is how I append $HOME/bin to my path in bash...
case $PATH in
*:$HOME/bin | *:$HOME/bin:* ) ;;
*) export PATH=$PATH:$HOME/bin
esac
season to taste...
A: you can use the following Perl script to prune paths of duplicates.
#!/usr/bin/perl
#
# ^^ ensure this is pointing to the correct location.
#
# Title: SLimPath
# Author: David "Shoe Lace" Pyke <eselle@users.sourceforge.net >
# : Tim Nelson
# Purpose: To create a slim version of my envirnoment path so as to eliminate
# duplicate entries and ensure that the "." path was last.
# Date Created: April 1st 1999
# Revision History:
# 01/04/99: initial tests.. didn't wok verywell at all
# : retreived path throught '$ENV' call
# 07/04/99: After an email from Tim Nelson <wayland@ne.com.au> got it to
# work.
# : used 'push' to add to array
# : used 'join' to create a delimited string from a list/array.
# 16/02/00: fixed cmd-line options to look/work better
# 25/02/00: made verbosity level-oriented
#
#
use Getopt::Std;
sub printlevel;
$initial_str = "";
$debug_mode = "";
$delim_chr = ":";
$opt_v = 1;
getopts("v:hd:l:e:s:");
OPTS: {
$opt_h && do {
print "\n$0 [-v level] [-d level] [-l delim] ( -e varname | -s strname | -h )";
print "\nWhere:";
print "\n -h This help";
print "\n -d Debug level";
print "\n -l Delimiter (between path vars)";
print "\n -e Specify environment variable (NB: don't include \$ sign)";
print "\n -s String (ie. $0 -s \$PATH:/looser/bin/)";
print "\n -v Verbosity (0 = quiet, 1 = normal, 2 = verbose)";
print "\n";
exit;
};
$opt_d && do {
printlevel 1, "You selected debug level $opt_d\n";
$debug_mode = $opt_d;
};
$opt_l && do {
printlevel 1, "You are going to delimit the string with \"$opt_l\"\n";
$delim_chr = $opt_l;
};
$opt_e && do {
if($opt_s) { die "Cannot specify BOTH env var and string\n"; }
printlevel 1, "Using Environment variable \"$opt_e\"\n";
$initial_str = $ENV{$opt_e};
};
$opt_s && do {
printlevel 1, "Using String \"$opt_s\"\n";
$initial_str = $opt_s;
};
}
if( ($#ARGV != 1) and !$opt_e and !$opt_s){
die "Nothing to work with -- try $0 -h\n";
}
$what = shift @ARGV;
# Split path using the delimiter
@dirs = split(/$delim_chr/, $initial_str);
$dest;
@newpath = ();
LOOP: foreach (@dirs){
# Ensure the directory exists and is a directory
if(! -e ) { printlevel 1, "$_ does not exist\n"; next; }
# If the directory is ., set $dot and go around again
if($_ eq '.') { $dot = 1; next; }
# if ($_ ne `realpath $_`){
# printlevel 2, "$_ becomes ".`realpath $_`."\n";
# }
undef $dest;
#$_=Stdlib::realpath($_,$dest);
# Check for duplicates and dot path
foreach $adir (@newpath) { if($_ eq $adir) {
printlevel 2, "Duplicate: $_\n";
next LOOP;
}}
push @newpath, $_;
}
# Join creates a string from a list/array delimited by the first expression
print join($delim_chr, @newpath) . ($dot ? $delim_chr.".\n" : "\n");
printlevel 1, "Thank you for using $0\n";
exit;
sub printlevel {
my($level, $string) = @_;
if($opt_v >= $level) {
print STDERR $string;
}
}
i hope thats useful.
A: I've been using the following (Bourne/Korn/POSIX/Bash) script for most of a decade:
: "@(#)$Id: clnpath.sh,v 1.6 1999/06/08 23:34:07 jleffler Exp $"
#
# Print minimal version of $PATH, possibly removing some items
case $# in
0) chop=""; path=${PATH:?};;
1) chop=""; path=$1;;
2) chop=$2; path=$1;;
*) echo "Usage: `basename $0 .sh` [$PATH [remove:list]]" >&2
exit 1;;
esac
# Beware of the quotes in the assignment to chop!
echo "$path" |
${AWK:-awk} -F: '#
BEGIN { # Sort out which path components to omit
chop="'"$chop"'";
if (chop != "") nr = split(chop, remove); else nr = 0;
for (i = 1; i <= nr; i++)
omit[remove[i]] = 1;
}
{
for (i = 1; i <= NF; i++)
{
x=$i;
if (x == "") x = ".";
if (omit[x] == 0 && path[x]++ == 0)
{
output = output pad x;
pad = ":";
}
}
print output;
}'
In Korn shell, I use:
export PATH=$(clnpath /new/bin:/other/bin:$PATH /old/bin:/extra/bin)
This leaves me with PATH containing the new and other bin directories at the front, plus one copy of each directory name in the main path value, except that the old and extra bin directories have bin removed.
You would have to adapt this to C shell (sorry - but I'm a great believer in the truths enunciated at C Shell Programming Considered Harmful). Primarily, you won't have to fiddle with the colon separator, so life is actually easier.
A: Well, if you don't care what order your paths are in, you could do something like:
set path=(`echo $path | tr ' ' '\n' | sort | uniq | tr '\n' ' '`)
That will sort your paths and remove any extra paths that are the same. If you have . in your path, you may want to remove it with a grep -v and re-add it at the end.
A: Here is a long one-liner without sorting:
set path = ( echo $path | tr ' ' '\n' | perl -e 'while (<>) { print $_ unless $s{$_}++; }' | tr '\n' ' ')
A: dr_peper,
I usually prefer to stick to scripting capabilities of the shell I am living in. Makes it more portable. So, I liked your solution using csh scripting. I just extended it to work on per dir in the localdirs to make it work for myself.
foreach dir ( $localdirs )
echo ${path} | egrep -i "$dir" >& /dev/null
if ($status != 0) then
set path = ( $dir $path )
endif
end
A: Using sed(1) to remove duplicates.
$ PATH=$(echo $PATH | sed -e 's/$/:/;s/^/:/;s/:/::/g;:a;s#\(:[^:]\{1,\}:\)\(.*\)\1#\1\2#g;ta;s/::*/:/g;s/^://;s/:$//;')
This will remove the duplicates after the first instance, which may or may not be what you want, e.g.:
$ NEWPATH=/bin:/usr/bin:/bin:/usr/local/bin:/usr/local/bin:/bin
$ echo $NEWPATH | sed -e 's/$/:/; s/^/:/; s/:/::/g; :a; s#\(:[^:]\{1,\}:\)\(.*\)\1#\1\2#g; t a; s/::*/:/g; s/^://; s/:$//;'
/bin:/usr/bin:/usr/local/bin
$
Enjoy!
A: Im surprised no one used the tr ":" "\n" | grep -x techique to search if a given folder already exists in $PATH. Any reason not to?
In 1 line:
if ! $(echo "$PATH" | tr ":" "\n" | grep -qx "$dir") ; then PATH=$PATH:$dir ; fi
Here is a function ive made myself to add several folders at once to $PATH (use "aaa:bbb:ccc" notation as argument), checking each one for duplicates before adding:
append_path()
{
local SAVED_IFS="$IFS"
local dir
IFS=:
for dir in $1 ; do
if ! $( echo "$PATH" | tr ":" "\n" | grep -qx "$dir" ) ; then
PATH=$PATH:$dir
fi
done
IFS="$SAVED_IFS"
}
It can be called in a script like this:
append_path "/test:$HOME/bin:/example/my dir/space is not an issue"
It has the following advantages:
*
*No bashisms or any shell-specific syntax. It run perfectly with !#/bin/sh (ive tested with dash)
*Multiple folders can be added at once
*No sorting, preserves folder order
*Deals perfectly with spaces in folder names
*A single test works no matter if $folder is at begginning, end, middle, or is the only folder in $PATH (thus avoiding testing x:*, *:x, :x:, x, as many of the solutions here implicitly do)
*Works (and preserve) if $PATH begins or ends with ":", or has "::" in it (meaning current folder)
*No awk or sed needed.
*EPA friendly ;) Original IFS value is preserved, and all other variables are local to the function scope.
Hope that helps!
A: Here's what I use - perhaps someone else will find it useful:
#!/bin/csh
# ABSTRACT
# /bin/csh function-like aliases for manipulating environment
# variables containing paths.
#
# BUGS
# - These *MUST* be single line aliases to avoid parsing problems apparently related
# to if-then-else
# - Aliases currently perform tests in inefficient in order to avoid parsing problems
# - Extremely fragile - use bash instead!!
#
# AUTHOR
# J. P. Abelanet - 11/11/10
# Function-like alias to add a path to the front of an environment variable
# containing colon (':') delimited paths, without path duplication
#
# Usage: prepend_path ENVVARIABLE /path/to/prepend
alias prepend_path \
'set arg2="\!:2"; if ($?\!:1 == 0) setenv \!:1 "$arg2"; if ($?\!:1 && $\!:1 !~ {,*:}"$arg2"{:*,}) setenv \!:1 "$arg2":"$\!:1";'
# Function-like alias to add a path to the back of any environment variable
# containing colon (':') delimited paths, without path duplication
#
# Usage: append_path ENVVARIABLE /path/to/append
alias append_path \
'set arg2="\!:2"; if ($?\!:1 == 0) setenv \!:1 "$arg2"; if ($?\!:1 && $\!:1 !~ {,*:}"$arg2"{:*,}) setenv \!:1 "$\!:1":"$arg2";'
A: When setting path (lowercase, the csh variable) rather than PATH (the environment variable) in csh, you can use set -f and set -l, which will only keep one occurrence of each list element (preferring to keep either the first or last, respectively).
https://nature.berkeley.edu/~casterln/tcsh/Builtin_commands.html#set
So something like this
cat foo.csh # or .tcshrc or whatever:
set -f path = (/bin /usr/bin . ) # initial value
set -f path = ($path /mycode /hercode /usr/bin ) # add things, both new and duplicates
Will not keep extending PATH with duplicates every time you source it:
% source foo.csh
% echo $PATH
% /bin:/usr/bin:.:/mycode:/hercode
% source foo.csh
% echo $PATH
% /bin:/usr/bin:.:/mycode:/hercode
set -f there ensures that only the first occurrence of each PATH element is kept.
A: I always set my path from scratch in .cshrc.
That is I start off with a basic path, something like:
set path = (. ~/bin /bin /usr/bin /usr/ucb /usr/bin/X11)
(depending on the system).
And then do:
set path = ($otherPath $path)
to add more stuff
A: I have the same need as the original question.
Building on your previous answers, I have used in Korn/POSIX/Bash:
export PATH=$(perl -e 'print join ":", grep {!$h{$_}++} split ":", "'$otherpath:$PATH\")
I had difficulties to translate it directly in csh (csh escape rules are insane). I have used (as suggested by dr_pepper):
set path = ( `echo $otherpath $path | tr ' ' '\n' | perl -ne 'print $_ unless $h{$_}++' | tr '\n' ' '`)
Do you have ideas to simplify it more (reduce the number of pipes) ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: How can I find the version of an installed Perl module? How do you find the version of an installed Perl module?
This is in an answer down at the bottom, but I figure it important enough to live up here. With these suggestions, I create a function in my .bashrc
function perlmodver {
perl -M$1 -e 'print "Version " . $ARGV[0]->VERSION . " of " . $ARGV[0] . \
" is installed.\n"' $1
}
A: If you are lucky, the module will have a package variable named $VERSION:
$ perl -MCPAN -e 'print "$CPAN::VERSION\n"'
1.9205
This is needed for modules to be distributed on CPAN, but internally developed modules might follow a different convention or none at all.
A: Most modules (especially ones from The CPAN) have a $VERSION variable:
perl -MSome::Module -le 'print $Some::Module::VERSION'
A: Why are you trying to get the version of the module? Do you need this from within a program, do you just need the number to pass to another operation, or are you just trying to find out what you have?
I have this built into the cpan (which comes with perl) with the -D switch so you can see the version that you have installed and the current version on CPAN:
$ cpan -D Text::CSV_XS
Text::CSV_XS
-------------------------------------------------------------------------
Fast 8bit clean version of Text::CSV
H/HM/HMBRAND/Text-CSV_XS-0.54.tgz
/usr/local/lib/perl5/site_perl/5.8.8/darwin-2level/Text/CSV_XS.pm
Installed: 0.32
CPAN: 0.54 Not up to date
H.Merijn Brand (HMBRAND)
h.m.brand@xs4all.nl
If you want to see all of the out-of-date modules, use the -O (capital O) switch:
$ cpan -O
Module Name Local CPAN
-------------------------------------------------------------------------
Apache::DB 0.1300 0.1400
Apache::SOAP 0.0000 0.7100
Apache::Session 1.8300 1.8700
Apache::SizeLimit 0.0300 0.9100
Apache::XMLRPC::Lite 0.0000 0.7100
... and so on
If you want to see this for all modules you have installed, try the -a switch to create an autobundle.
A: Thanks for the answers! I've created a function in my .bashrc to easily find the version of a Perl module:
function perlmodver {
perl -M$1 -e 'print $ARGV[0]->VERSION . "\n"' $1
}
A: Easiest to remember and most robust version for me:
perl -e 'use Search::Elasticsearch; print $Search::Elasticsearch::VERSION;'
A: Check out the pmtools scripts on CPAN. If you're using a Debian(-based) distro, there's also a handy pmtools package. This includes a script "pmvers" that tells you a module's version. It's quite handy.
It does something similar to the various one-liners folks posted, but it's a bit smarter about error handling, and can give you the version of more than one module at once.
A: VERSION is a UNIVERSAL method of all Perl classes. You can use it to get the module version (if it has been set which it usually has).
Here is a one liner where you only have to add the module name once:
perl -le 'eval "require $ARGV[0]" and print $ARGV[0]->VERSION' Some::Module
A: There is a less-typing trick, that works provided your module doesn't have something insane like a Unix timestamp as a version number.
perl -MFoo::Bar\ 9999
This works because what it translates to is
use Foo::Bar 9999;
i.e. a version of Foo::Bar that's at least version 9999 or newer.
And what you get is
Foo::Bar version 9999 required--this is only version 1.1.
BEGIN failed--compilation aborted.
(Neat trick I learned from Matt Trout.)
A: I wrote a small script to report that: perlver.
This is a simple little tool that
tells you what version of a module you
have installed, and where the .pm file
is located. It also ensures the module
can be loaded successfully. It
automatically converts ‘-’, ‘/’, or
‘\’ to ‘::’, so you can use a pathname
or distribution name instead of the
canonical module name.
It assumes that the module defines a $VERSION. If the module doesn't define a $VERSION, it will still tell you where the .pm file is, so you can examine it manually. You can also check several modules at once:
$ perlver CPAN DBD-Pg Getopt::Long
CPAN 1.7602 is
/usr/lib/perl5/5.8.8/CPAN.pm
DBD::Pg 1.49 is
/usr/lib/perl5/vendor_perl/5.8.8/i686-linux/DBD/Pg.pm
Getopt::Long 2.36 is
/usr/lib/perl5/vendor_perl/5.8.8/Getopt/Long.pm
A: In addition, for modules that use Exporter.pm, you can get this information with this trick:
perl -MSome::Module=99999 -ex
Some::Module version 99999 required--this is only version 1.9205 at ...
For modules that don't use Exporter.pm, a slightly longer trick reports the same information:
perl -e'use Some::Module 99999'
Some::Module version 99999 required--this is only version 1.9205 at ...
A: We have the system perl (/usr/bin/perl) in Solaris 10, and above solutions are useless. Some of them report "module.pm is not installed", some of them have no output.
Here is the code which is helpful, which can list all modules and their version.
#!/usr/bin/perl
use strict;
use ExtUtils::Installed;
my @modules;
my $installed = ExtUtils::Installed->new();
if (scalar(@ARGV) > 0) {
@modules = @ARGV;
} else {
@modules = $installed->modules();
}
print "Module\tVersion\n";
foreach (@modules) {
print $_ . "\t" . $installed->version($_) . "\n";
}
A: You can also take a look at App::module::version
$ module-version
The version of App::module::version in /home/yourself/perl5/lib/perl5 is 1.004
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "64"
}
|
Q: Why Can't I Inherit IO.Directory? Why can't I create a class in VB.NET that inherits System.IO.Directory? According to Lutz Roeder, it is not declared as NotInheritable!
I want to create a utility class that adds functionality to the Directory class. For instance, I want to add a Directory.Move function.
Please advise and I will send you a six pack. OK nevermind I'm not sending you anything but if you come to the bar tonight I will hook you up and then beat you in pool.
A: Are you using C# 3.0 VB.NET 2008 -- then you could add an Extension Method
A: From the Meta Data of .NET
namespace System.IO
{
// Summary:
// Exposes static methods for creating, moving, and enumerating through directories
// and subdirectories. This class cannot be inherited.
[ComVisible(true)]
public static class Directory
You cannot inherit from a Static Class.
A: If you use the DirectoryInfo class, you will have access to a MoveTo function.
EDIT: I'll correct myself... The static Directory class already has a Move method.
A: I'd guess that Reflector isn't picking up the sealed attribute correctly for VB (or perhaps just not displaying it properly). If you look at the IL, it is sealed:
class public abstract auto ansi sealed beforefieldinit Directory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Silverlight 2 and the MVP Pattern Any ideas on how i get MVP working with Silverlight? How Do I get around the fact there is no load event raised?
This the view I have:
public partial class Person: IPersonView
{
public event RoutedEventHandler Loaded;
public Person()
{
new PersonPresenter(this);
InitializeComponent();
}
public Person Person
{
set { Person.ItemsSource = value; }
}
}
And my presenter:
public class PersonPresenter
{
private readonly IPersonView _view;
private readonly ServiceContractClient _client;
public PersonPresenter(IPersonView view)
{
_client = new ServiceContractClient();
_view = view;
WireUpEvents();
}
private void WireUpEvents()
{
_view.Loaded += Load;
}
private void Load(object sender, EventArgs e)
{
_client.GetPersonCompleted += Client_GetPerson;
_client.GetPersonAsync();
}
private void Client_GetPerson(object sender, GetPersonCompletedEventArgs e)
{
_view.Person= e.Result;
}
}
Nothing happened for me as the Loaded event dont seem to get called, how do i get around this?
A: Tim Ross has a good introduction to Silverlight MVP implementation, with source code.
A: I believe the loaded event gets called when the control has been initialized, loaded, rendered and ready for use. This means that as long as you don't place it inside a visible container (so that it is rendered), the loaded event won't be risen.
A: You may consider using MVC# - a Model View Presenter framework with Silverlight 2.0 support.
Oleg Zhukov
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: A StringToken Parser which gives Google Search style "Did you mean:" Suggestions Seeking a method to:
Take whitespace separated tokens in a String; return a suggested Word
ie:
Google Search can take "fonetic wrd nterpreterr",
and atop of the result page it shows "Did you mean: phonetic word interpreter"
A solution in any of the C* languages or Java would be preferred.
Are there any existing Open Libraries which perform such functionality?
Or is there a way to Utilise a Google API to request a suggested word?
A: You can use the yahoo web service here:
http://developer.yahoo.com/search/web/V1/spellingSuggestion.html
However it's only a web service... (i.e. there are no APIs for other language etc..) but it outputs JSON or XML, so... pretty easy to adapt to any language...
A: You can also use the Google API's to spell check. There is an ASP implementation here (I'm not to credit for this, though).
A: First off:
*
*Java
*C++
*C#
Use the one of your choice. I suspect it runs the query against a spell-checking engine with a word limit of exactly one, it then does nothing if the entire query is valid, otherwise it replaces each word with that word's best match. In other words, the following algorithm (an empty return string means that the query had no problems):
startup()
{
set the spelling engines word suggestion limit to 1
}
option 1()
{
int currentPosition = engine.NextWord(start the search at word 0, querystring);
if(currentPosition == -1)
return empty string; // Query is a-ok.
while(currentPosition != -1)
{
queryString = engine.ReplaceWord(engine.CurrentWord, queryString, the suggestion with index 0);
currentPosition = engine.NextWord(currentPosition, querystring);
}
return queryString;
}
A: Since no one has yet mentioned it, I'll give one more phrase to search for: "edit distance" (for example, link text).
That can be used to find closest matches, assuming it's typos where letters are transposed, missing or added.
But usually this is also coupled with some sort of relevancy information; either by simple popularity (to assume most commonly used close-enough match is most likely correct word), or by contextual likelihood (words that follow preceding correct word, or come before one). This gets into information retrieval; one way to start is to look at bigram and trigrams (sequences of words seen together). Google has very extensive freely available data sets for these.
For simple initial solution though a dictionary couple with Levenshtein-based matchers works surprisingly well.
A: You could plug Lucene, which has a dictionary facility implementing the Levenshtein distance method.
Here's an example from the Wiki, where 2 is the distance.
String[] l=spellChecker.suggestSimilar("sevanty", 2);
//l[0] = "seventy"
*
*http://wiki.apache.org/lucene-java/SpellChecker
*An older link http://today.java.net/pub/a/today/2005/08/09/didyoumean.html
A: In his article How to Write a Spelling Corrector, Peter Norvig discusses how a Google-like spellchecker could be implemented. The article contains a 20-line implementation in Python, as well as links to several reimplementations in C, C++, C# and Java. Here is an excerpt:
The full details of an
industrial-strength spell corrector
like Google's would be more confusing
than enlightening, but I figured that
on the plane flight home, in less than
a page of code, I could write a toy
spelling corrector that achieves 80 or
90% accuracy at a processing speed of
at least 10 words per second.
Using Norvig's code and this text as training set, i get the following results:
>>> import spellch
>>> [spellch.correct(w) for w in 'fonetic wrd nterpreterr'.split()]
['phonetic', 'word', 'interpreters']
A: If you have a dictionary stored as a trie, there is a fairly straightforward way to find best-matching entries, where characters can be inserted, deleted, or replaced.
void match(trie t, char* w, string s, int budget){
if (budget < 0) return;
if (*w=='\0') print s;
foreach (char c, subtrie t1 in t){
/* try matching or replacing c */
match(t1, w+1, s+c, (*w==c ? budget : budget-1));
/* try deleting c */
match(t1, w, s, budget-1);
}
/* try inserting *w */
match(t, w+1, s + *w, budget-1);
}
The idea is that first you call it with a budget of zero, and see if it prints anything out. Then try a budget of 1, and so on, until it prints out some matches. The bigger the budget the longer it takes. You might want to only go up to a budget of 2.
Added: It's not too hard to extend this to handle common prefixes and suffixes. For example, English prefixes like "un", "anti" and "dis" can be in the dictionary, and can then link back to the top of the dictionary. For suffixes like "ism", "'s", and "ed" there can be a separate trie containing just the suffixes, and most words can link to that suffix trie. Then it can handle strange words like "antinationalizationalization".
A: The Google SOAP Search APIs do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Generic logging of function parameters in exception handling A lot of my C# code follows this pattern:
void foo(string param1, string param2, string param3)
{
try
{
// do something...
}
catch(Exception ex)
{
LogError(String.Format("Error in foo(param1={0}, param2={1}, param3={2}), exception={3}", param1, param2, param3, ex.Message));
}
}
Is there a way in .NET to get a Key/Value list of the parameters to a function so that I can call another function to construct my error logging string?
OR
Do you have a more generic / better way of doing this?
A: You could use aspect oriented programming with PostSharp (have a look at http://www.postsharp.org, and the tutorial at http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx). Basically you could do something like this:
public class LogExceptionAttribute : OnExceptionAspect
{
public override void OnException(MethodExecutionEventArgs eventArgs)
{
log.error("Exception occurred in method {0}", eventArgs);
}
}
[LoggingOnExceptionAspect]
public foo(int number, string word, Person customer)
{
// ... something here throws an exception
}
Perhaps not quite what you want, but I'm sure it can be adapted to suit your needs.
A: No there isn't a way to do this.
The normal practice is to not catch exceptions unless you can handle them.
I.e. you would normally only catch exceptions and log them in a top-level exception handler. You will then get a stack trace, but won't of course get details of all the parameters of all method calls in the stack.
Obviously when debugging you want as much detail as possible. Other ways to achieve this are:
*
*Use Debug.Assert statements liberally to test assumptions you are making.
*Instrument your application with logging that can be activate selectively. I use Log4Net, but there are also other alternatives, including using the System.Diagnostics.Trace class.
In any case, if you do catch exceptions only to log them (I'd do this at a tier boundary in an n-tier application, so that exceptions are logged on the server), then you should always rethrow them:
try
{
...
}
catch(Exception ex)
{
log(ex);
throw;
}
A: You could use Reflection and the convention that you must pass the parameters to the LogError with the right order:
private static void MyMethod(string s, int x, int y)
{
try
{
throw new NotImplementedException();
}
catch (Exception ex)
{
LogError(MethodBase.GetCurrentMethod(), ex, s, x, y);
}
}
private static void LogError(MethodBase method, Exception ex, params object[] values)
{
ParameterInfo[] parms = method.GetParameters();
object[] namevalues = new object[2 * parms.Length];
string msg = "Error in " + method.Name + "(";
for (int i = 0, j = 0; i < parms.Length; i++, j += 2)
{
msg += "{" + j + "}={" + (j + 1) + "}, ";
namevalues[j] = parms[i].Name;
if (i < values.Length) namevalues[j + 1] = values[i];
}
msg += "exception=" + ex.Message + ")";
Console.WriteLine(string.Format(msg, namevalues));
}
A: When I have done this I just created a generic dictionary for the logging.
I have this LogArgs class. And logging in a base class that I call when I have an exception.
public class LogArgs
{
public string MethodName { get; set; }
public string ClassName { get; set; }
public Dictionary<string, object> Paramters { get; set; }
public LogArgs()
{
this.Paramters = new Dictionary<string, object>();
}
}
Then at the start of every method I do
LogArgs args = new LogArgs { ClassName = "ClassName", MethodName = "MethodName" };
args.Paramters.Add("Param1", param1);
args.Paramters.Add("Param2", param2);
args.Paramters.Add("Param3", param3);
base.Logger.MethodStartLog(args);
When I have an error I log it this way.
base.Logger.LogError(args, ex);
A: You could use a similar style of constructing the message, but add the params keyword in your LogError method to handle the arguments. For example:
public void LogError(string message, params object[] parameters)
{
if (parameters.Length > 0)
LogError(string.Format(message, parameters));
else
LogError(message);
}
A: This is little dated post but just in case someone comes across this like I did - I solved this issue by using PostSharp.
It's not practically free though. The Express license (downloadable via NuGet in VS) allows you to decorate your method with [Log] attribute and then choose your already configured mechanism for logging, like log4net nLog etc. Now you will start seeing Debug level entries in your log giving parameter details.
With express license I could only decorate a maximum of 50 methods in my project. If it fits your needs you're good to go!
A: Late to the party but I did something along these lines a year or so ago:
Github Repo
The idea of this setup is much like what your after, but with the ability to hook it up globally, there is more code than I would like there but it works and once plugged in, works for what your after.
If you take a quick look at the ProxyLogger.cs, consider this a wrapper, it will encapsulate any method it is given and execute it while handling the logging of the error as set here. This can then be setup with dependency injection for anything and everything you wish to log, e.g.:
public void ConfigureServices(HostBuilderContext hostBuilder, IServiceCollection services)
{
services.AddOptions();
services.AddSingleton<IHostedService, HostedService>();
services.AddSingleton<IMyClass, MyClass>();
// Logging added for both the hosted service and the example class
services.Decorate<IMyClass, ProxyLogger<IMyClass>>();
services.Decorate<IHostedService, ProxyLogger<IHostedService>>();
}
You register your services as normal, but on top of that, you can decorate them with the proxy logger to handle the execution and log the details before, after, on failure etc, with FULL params.
I was obsessed with this for a while and this is as best as I could get it, but it works really well.
A: There are scenarios of a few parameters or Large number of parameters...
*
*Few parameters, without much ado, better write them as part of the logging/exception message.
*In large parameters, a multi-layer application would be using ENTITIES ( like customer, CustomerOrder...) to transfer data between layers. These entities should implement
override ToString() methods of class Object, there by,
Logmessage(" method started " + paramObj.ToString()) would give the list of data in the object..
Any opinions? :)
thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: TDD. When you can move on? When doing TDD, how to tell "that's enough tests for this class / feature"?
I.e. when could you tell that you completed testing all edge cases?
A: Kent Beck's advice is to write tests until fear turns into boredom. That is, until you're no longer afraid that anything will break, assuming you start with an appropriate level of fear.
A: On some level, it's a gut feeling of
"Am I confident that the tests will catch all the problems I can think of
now?"
On another level, you've already got a set of user or system requirements that must be met, so you could stop there.
While I do use code coverage to tell me if I didn't follow my TDD process and to find code that can be removed, I would not count code coverage as a useful way to know when to stop. Your code coverage could be 100%, but if you forgot to include a requirement, well, then you're not really done, are you.
Perhaps a misconception about TDD is that you have to know everything up front to test. This is misguided because the tests that result from the TDD process are like a breadcrumb trail. You know what has been tested in the past, and can guide you to an extent, but it won't tell you what to do next.
I think TDD could be thought of as an evolutionary process. That is, you start with your initial design and it's set of tests. As your code gets battered in production, you add more tests, and code that makes those tests pass. Each time you add a test here, and a test there, you're also doing TDD, and it doesn't cost all that much. You didn't know those cases existed when you wrote your first set of tests, but you gained the knowledge now, and can check for those problems at the touch of a button. This is the great power of TDD, and one reason why I advocate for it so much.
A: Well, when you can't think of any more failure cases that doesn't work as intended.
Part of TDD is to keep a list of things you want to implement, and problems with your current implementation... so when that list runs out, you are essentially done....
And remember, you can always go back and add tests when you discover bugs or new issues with the implementation.
A: that common sense, there no perfect answer. TDD goal is to remove fear, if you feel confident you tested it well enough go on...
Just don't forget that if you find a bug later on, write a test first to reproduce the bug, then correct it, so you will prevent future change to break it again!
Some people complain when they don't have X percent of coverage.... some test are useless, and 100% coverage does not mean you test everything that can make your code break, only the fact it wont break for the way you used it!
A: A test is a way of precisely describing something you want. Adding a test expands the scope of what you want, or adds details of what you want.
If you can't think of anything more that you want, or any refinements to what you want, then move on to something else. You can always come back later.
A: Tests in TDD are about covering the specification, in fact they can be a substitute for a specification. In TDD, tests are not about covering the code. They ensure the code covers the specification, because the code will fail a test if it doesn't cover the specification. Any extra code you have doesn't matter.
So you have enough tests when the tests look like they describe all the expectations that you or the stakeholders have.
A: With Test Driven Development, you’ll write a test before you write the code it tests. Once you’re written the code and the test passes, then it’s time to write another test. If you follow TDD correctly, you’ve written enough tests once you’re code does all that is required.
As for edge cases, let's take an example such as validating a parameter in a method. Before you add the parameter to you code, you create tests which verify the code will handle each case correctly. Then you can add the parameter and associated logic, and ensure the tests pass. If you think up more edge cases, then more tests can be added.
By taking it one step at a time, you won't have to worry about edge cases when you've finished writing your code, because you'll have already written the tests for them all. Of course, there's always human error, and you may miss something... When that situation occurs, it's time to add another test and then fix the code.
A: maybe i missed something somewhere in the Agile/XP world, but my understanding of the process was that the developer and the customer specify the tests as part of the Feature. This allows the test cases to substitute for more formal requirements documentation, helps identify the use-cases for the feature, etc. So you're done testing and coding when all of these tests pass...plus any more edge cases that you think of along the way
A: Alberto Savoia says that "if all your tests pass, chances are that your test are not good enough". I think that it is a good way to think about tests: ask if you are doing edge cases, pass some unexpected parameter and so on. A good way to improve the quality of your tests is work with a pair - specially a tester - and get help about more test cases. Pair with testers is good because they have a different point of view.
Of course, you could use some tool to do mutation tests and get more confidence from your tests. I have used Jester and it improve both my tests and the way that I wrote them. Consider to use something like it.
Kind Regards
A: Theoretically you should cover all possible input combinations and test that the output is correct but sometimes it's just not worth it.
A: Many of the other comments have hit the nail on the head. Do you feel confident about the code you have written given your test coverage? As your code evolves do your tests still adequately cover it? Do your tests capture the intended behaviour and functionality for the component under test?
There must be a happy medium. As you add more and more test cases your tests may become brittle as what is considered an edge case continuously changes. Following many of the earlier suggestions it can be very helpful to get everything you can think of up front and then adding new tests as the software grows. This kind of organic grow can help your tests grow without all the effort up front.
I am not going to lie but I often get lazy when going back to write additional tests. I might miss that property that contains 0 code or the default constructor that I do not care about. Sometimes not being completely anal about the process can save you time n areas that are less then critical (the 100% code coverage myth).
You have to remember that the end goal is to get a top notch product out the door and not kill yourself testing. If you have that gut feeling like you are missing something then chances are you are have and that you need to add more tests.
Good luck and happy coding.
A: You could always use a test coverage tool like EMMA (http://emma.sourceforge.net/) or its Eclipse plugin EclEmma (http://www.eclemma.org/) or the like. Some developers believe that 100% test coverage is a worthy goal; others disagree.
A: Just try to come up with every way within reason that you could cause something to fail. Null values, values out of range, etc. Once you can't easily come up with anything, just continue on to something else.
If down the road you ever find a new bug or come up with a way, add the test.
It is not about code coverage. That is a dangerous metric, because code is "covered" long before it is "tested well".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Determining the port a Visual Studio Web App runs on I've been using the macro from this blog entry for attaching the Visual Studio debugger to an already running instance of the Web Application I'm currently working on. However, if I have more than one instance of the Visual Studio web server running it's pot luck which one it'll attach to.
Is there a way to determine what port is configured in the Web project so I can modify the macro to filter its choice of process to that one?
Further Info
I'm aware that you can set the port number to a static one - I've done just that from the get-go, what I'm trying to determine is how to programatically determine the defined port-number so I can modify the macro (in the linked blog entry) and ensure it connects to the right instance of the Visual Studio web server.
The way I have things running is I have two (or more) instances of Visual Studio running, each of which contains a Solution, which contains a web project and one or more other projects - typically an Installer project), so when I trigger the macro from a given instance of Visual Studio, I want to find the Web Project within that instances loaded solution and determine the port it's running against.
A: This code will get you a list of all ports for the projects in the current solution:
Sub GetWebProjectPorts()
Dim ports As String
For Each prj As Project In DTE.Solution.Projects
For Each p As EnvDTE.Property In prj.Properties
If p.Name.Contains("DevelopmentServerPort") Then
If Not String.IsNullOrEmpty(ports) Then
ports += ","
End If
ports += p.Value.ToString()
End If
Next
Next
MsgBox(ports)
End Sub
A: If that can help you, I have found a link that might actually to the trick.
However, it require DllImport call and a lot of fun.
You can take a look at that article there: http://bytes.com/forum/thread574901.html
Quotes from the actual site:
By calling into iphlpapi.dll using
PInvoke interop. Google around for
GetExtendedTcpTable and iphlpapi.dll,
I'm sure you will find some existing
stuff.
Willy.
And one last:
Here are some API-Methods for my
purposes:
GetTcpTable()
AllocateAndGetTcpExTableFromStack()
GetExtendedTcpTable()
I wrote a small programm that is able
to show me all Processes with the
belonging TCP-Ports (with
AllocateAndGetTcpExTableFromStack())
running under Windows XP.
Now my problem is, that under Windows
2000 I can't use
AllocateAndGetTcpExTableFromStack() or
GetExtendedTcpTable() so I'm only able
to use GetTcpTable() to list all
TCP-Ports but without the belonging
processes.
Did somebody have the same problem or
is there another way (.Net or WMI
etc.) to solve my problem?
Thanks in advance,
Werner
A: If you go to the properties for your web project and look under the "Web" tab, you can specify which port the project will always start up on. Then you can click "Enable Edit and Continue" so you don't have to stop debugging and restart continuously.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is the best way to get a cookie by name in JavaScript? I am using prototype and I can't find any built in extensions to set or retrieve cookies. After googling for a little bit, I see a few different ways to go about it. I was wondering what you think is the best approach for getting a cookie in JavaScript?
A: I use this routine:
function ReadCookie(name)
{
name += '=';
var parts = document.cookie.split(/;\s*/);
for (var i = 0; i < parts.length; i++)
{
var part = parts[i];
if (part.indexOf(name) == 0)
return part.substring(name.length)
}
return null;
}
Works quite well.
A: Anytime I need to access it, I use document.cookie, basically how it's outlined in that article. Caveat, I've never used prototype, so there may be easier methods there that you just haven't run across.
A: In case anyone else needs it, I've fixed up Diodeus's code to address PhiLho's concern about partial matches when trying to fetch a cookie value.
function getCookie(c_name) {
var nameEQ = c_name + '=';
var c_start = 0;
var c_end = 0;
if (document.cookie.substr(0, nameEQ.length) === nameEQ) {
return document.cookie.substring(nameEQ.length, document.cookie.indexOf(';', nameEQ.length));
} else {
c_start = document.cookie.indexOf('; ' + nameEQ);
if(c_start !== -1){
c_start += nameEQ.length + 2;
c_end = document.cookie.indexOf(';', c_start);
if (c_end === -1) {c_end = document.cookie.length;}
return document.cookie.substring(c_start, c_end);
}
}
return null;
}
I've recently also built a much more compact RegExp that should work as well:
function getCookie(c_name){
var ret = window.testCookie.match(new RegExp("(?:^|;)\\s*"+c_name+"=([^;]*)"));
return (ret !== null ? ret[1] : null);
}
I did some speed tests that seem to indicate that out of PhiLo, QuirksMode, and these two implementations the non-RegExp version (using indexOf is very fast, not a huge surprise) above is the fastest. http://jsperf.com/cookie-fetcher
A: I use this. It has been dependable:
function getCookie(c_name) {
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1)
{
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Put a process in a sandbox where it can do least harm I'm looking for the concept to spawn a process such that:
*
*it has only access to certain libraries/APIs
*it cannot acess the file system or only specific parts
*it can do least harm should malicious code run in it
This concept is known as sandbox or jail.
It is required to do this for each major Operating system (Windows, MacOSX and Linux) and the question is conceptual (as in what to do, which APIs to use and and what to observe) rather then language specific.
answer requirements
I really want to accept an answer and give you 20 points for that. I cannot accept my own answer, and I don't have it yet anyway. So if you really want your answer to be accepted, please observe:
*
*The answer has to be specific and complete
*With specific I mean that it is more then a pointer to some resource on the internet. It has to summarize what the resource says about the topic at least.
*It may or may not contain example code, but if it does please write it in C
*I cannot accept an answer that is 2/3 complete even if the 2/3 that are there are perfect.
this question FAQ
*
*Is this homework? No.
*Why do you ask this like a homework question? If you ask a specific question and you want to get a specific answer, and you know how that answer should look like, even though you don't know the answer, that's the style of question you get.
*If you know how it should look like, why do you ask? 1) because I don't know all the answer 2) because on the internet there's no single place that contains all the details to this question in one place. Please also read the stackoverflow FAQ
*Why is the main part of your question how to answer this question? Because nobody reads the FAQ.
A: For Windows there is a sandbox in Google Chrome. You may want to investigate it. It uses liberal BSD-like license.
For Linux there would be good old chroot or more sophisticated http://plash.beasts.org/wiki/.
OS X since Leopard has some SELinux-like protection available.
A: The site codepad.prg has a good "About" page on how they safely allow the execution of any code snippets..
Code execution is handled by a supervisor based on geordi. The strategy is to run everything under ptrace, with many system calls disallowed or ignored. Compilers and final executables are both executed in a chroot jail, with strict resource limits. The supervisor is written in Haskell.
When your app is remote code execution, you have to expect security problems. Rather than rely on just the chroot and ptrace supervisor, I've taken some additional precautions:
*
*The supervisor processes run on virtual machines, which are firewalled such that they are incapable of making outgoing connections.
*The machines that run the virtual machines are also heavily firewalled, and restored from their source images periodically.
A: FreeBSD has specific concepts of jails, and Solaris has containers. Depending on what you're looking for, these may help.
chroot jails can help to limit what an application can do (though any app with root privileges can escape a jail), and they're available on most UNIXen, including OS X.
As for Windows, I'm not sure. If there was an easy way to sandbox a Windows app, most of them would be a lot more secure by now, I'm sure.
A: On windows (2000 and later) you can use Job objects to restrict processes.
A: If you really want a technique that will work with all these platforms, as opposed to a separate solution for each platform, then I think your only answer is to set up a virtual machine for each testing environment. You can restore back to a snapshot at any time.
Another big advantage of using virtualization is that you can have all of the testing environments with their guest operating systems all on the same box.
A: Mac OS X has a sandbox facility code-named Seatbelt. The public API for it is documented in the sandbox(7), sandbox_init(3), and related manual pages. The public API is somewhat limited, but the facility itself is very powerful. While the public API only lets you choose from some pre-defined sandboxes (e.g. “All sockets-based networking is prohibited”), you can also use the more powerful underlying implementation which allows you to specify exactly what operating system resources are available via a Scheme-like language. For example, here is an excerpt of the sandbox used for portmap:
(allow process-exec (regex #"^/usr/sbin/portmap$"))
(allow file-read-data file-read-metadata (regex
#"^/etc"
#"^/usr/lib/.*\.dylib$"
#"^/var"
#"^/private/var/db/dyld/"
#"^/dev/urandom$"))
(allow file-write-data (regex
#"^/dev/dtracehelper$"))
You can see many sandboxes used by the system in /usr/share/sandbox. It is easy to experiment with sandboxes by using the sandbox-exec(1) command.
For Windows, you may want to have a look at David LeBlanc’s “Practical Sandboxing” talk given at Black Hat USA 2007. Windows has no built-in sandboxing technology per se, so the techniques described leverage an incomplete mechanism introduced with Windows 2000 called SAFER. By using restricted tokens, one can create a process that has limited access to operating system resources.
For Linux, you might investigate the complicated SELinux mechanism:
SELinux home,
a HOWTO. It is used by Red Hat, for example, to harden some system services in some of their products.
A: For Linux, there is AppArmor. Unfortunately, the project is somewhat on hiatus.
Another sandboxing-alternative is VServer, which uses virtualization.
A: Generally any virtual private server will do:
Linux VServer
http://linux-vserver.org/Welcome_to_Linux-VServer.org
Parallels Virtuozzo Containers
http://www.parallels.com/products/pvc/
and as was mentioned FreeBSD and Solaris has own implementations.
Oh. actually I've noticed you're asking it to work on ANY OS. Well, that might be complicated a bit as the I think less effort is just to reuse some VM that can support some level of sandboxing like:
*
*Java
*.NET
A: I'm not an expert on the topic, but i think the standard answer for linux is to define a SeLinux policy with the right capabilities for the process.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: DragDrop registration did not succeed
System.InvalidOperationException: DragDrop registration did not
succeed. ---> System.Threading.ThreadStateException:
What does this exception mean? I get it at this line trying to add a panel to a panel at runtime...
splitReport.Panel1.Controls.Add(ChartPanel);
Working in VS2008 C#
A: function abc
{
Thread t = new Thread(new ThreadStart(xyz));
t.SetApartmentState(ApartmentState.STA);
t.Start( );
}
function xyz
{
the code of Windows form..or whatever which is causing the error
}
A: Add the STAThreadAttribute attribute on the Main method. This attribute is required if your program access OLE related functions, like Clipboard class does.
[STAThread]
static void Main(string[] args)
{
}
A: This exception means that the thread that owns the Panel (the Panel being added) has been initialized using the MTA threading model. The drag/drop system requires that the calling thread use the STA thread model (particularly it requires that COM be initialized via OleInitialize). Threading models are an unfortunate vestige of COM, a predecessor of the .NET platform.
If you have the [STAThread] attribute on your Main function, then the main program thread should already be STA. The most likely explanation, then, is that this exception is happening on a different thread. Look at the Threads window in Visual Studio (Debug | Windows | Threads) when the exception occurs and see if you are on a thread other than the main thread. If you are, the solution is probably as simple as setting the thread model for that new thread, which you can do as follows (add this code to the thread where the control is being created):
Thread.CurrentThread.SetApartmentState( ApartmentState.STA )
(Thread and ApartmentState are members of System.Threading)
That code will need to happen before you actually start the new thread. As noted by @Tomer, you can also specify this declaratively using the [STAThread] attribute.
If you find that the exception is happening on the main thread, post back and let us know, and maybe we can help more. A stack trace at the time of the exception may help track down the problem.
A: I'm not sure whether you have solved this problem or not. I just encountered this problem and I fixed it by deleting my bin directory.
A: Yes, I realize this question was asked 2 and a half years ago. I hit this exception and did some reading on it. I corrected it, but didn't see my solution anywhere, so I thought I'd post it somewhere someone else could read.
One possibility for this happening with [STAThread] marked on the Main() is if you're running this on a thread other than the one you started on.
I just ran into this exception when trying to create and show a new form in a BackgroundWorker.DoWork method. To fix it, I wrapped the creation and showing of my new form into a method, and then called Invoke on that method so that it fired on the UI thread. This worked because the UI thread started from the Main() method with [STAThread] marked, as other answers here explained.
A: This error also can happen, if you have async Task signature on your Main()
[STAThread]
static async Task Main()
{
}
if it's feasible change it back to void
[STAThread]
static void Main()
{
}
A: By far the easiest way is:
private void DoSomethingOnGui()
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
Safe_DoSomethingOnGui();
});
}
else
{
Safe_DoSomethingOnGui();
}
}
private void Safe_DoSomethingOnGui()
{
// Do whatever you want with the GUI
}
You can even pass things along no problem:
private void DoSomethingOnGui(object o)
{
if (this.InvokeRequired)
{
this.Invoke((MethodInvoker)delegate
{
Safe_DoSomethingOnGui(o);
});
}
else
{
Safe_DoSomethingOnGui(o);
}
}
private void Safe_DoSomethingOnGui(object o)
{
// Do whatever you want with the GUI and o
}
A: I found this error, and the one that makes the error shown was when we have another thread calling MessageBox.Show(this, ...). However, this is not done initialized.
We need to remove the owner of the message box to remove the error.
A: I solved this error by using below code...I were using Background Worker and trying to access UI while background worker..that is why getting error - DragDrop registration did not succeed.
We cannot access UI from the code running in background worker or in thread.
BeginInvoke((MethodInvoker)delegate
{
//write your code here...
});
Thanks Happy Coding... :
A: "Crypto Obfuscator For .NET" can also trigger this exception, in my case the DragDrop event was subscribed to (from designer), but contained no code as I commented it out much earlier on. It took a while to figure out what is was, and this was after changing every single Obfuscator config option 1 after the next.. it came down to exactly this. If you encounter this with a popular obfuscation tool, keep this in mind.
A: I have encountered this situation recently,[STAThreadAttribute]is in my case,and i solved this problem by using Invoke method,it might be helpful for you guys,so I share with a little code snippet:
this.Invoke(new InvokeHandler(delegate()
{
//Your method here!
}));
And InvokeHandler is a delegate like this:
private delegate void InvokeHandler();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: For tabular data, what renders faster, CSS or ? I am looking for some stats on current browsers for how long it takes to render a table using plain HTML versus a hacked-up CSS puritan method that avoids using actual TABLE, TR, TD etc. tags.
I am not looking for what's proper, only for what's faster, particularly on Firefox 3, although I am also interested in the stats for other browsers. Of course TABLE tags are designed for tables. That's not the question.
A: In general, I would say use <table> for tabular data. However, if the table is very long (say, over 100 rows) and the number of columns is low (~3), using divs to emulate rows would result in a much smaller markup footprint. This is especially relevant if you are using DOM searching javascript (as provided by the many JS libraries), as it would benefit to reduce the DOM tree size.
This is from experience, I had such a table and was looking for optimizations - moving to a div based display cut the HTML generated to a third and was a big improvement in DOM traversal performance.
A: Since some browsers wait until the entire table has been transferred to display it in order to make sure they have adjusted the column widths for content size, using divs will probably render faster if you're looking for an average across every browser.
That being said, if you need a table, use a table.
A: This question looks to be similar to this one:
Why not use tables for layout in HTML? so you might want to check some of the responses there as well.
In general, browsers will not render a table until the entire table has been calculated, which means that from a user perspective a large table is slower than the same content using CSS styling in place of tables. I was working with a web application at one point that was using tables to display a grid of status information, and it was extremely intensive to display and very slow. The same information displayed using CSS was faster and more importantly, started to display line by line as it was loaded, instead of waiting for the entire table, so it felt faster as an end user. I would suggest investigating using CSS to display the data using a sample dataset for testing. This is what I did to confirm that the tables were in fact much slower for the particular use case we had.
A: If you use CSS for layout and you adhere to best practice and keep your CSS in a separate file(s) then your CSS will typically only need to be downloaded once before it is cached, giving you the benefits of caching.
If you use tables for layout then your layout tables will be sent with the HTML for every page, increasing your bandwidth and download times.
To improve the rendering speed of tables though you could try setting the table-layout:fixed; to see if that helps..
A: If you really have tabular data, then use tables. The idea that you should never use tables for anything was a mistaken extension of the correct concept that you should use html tags only for their intended semantic purpose. That means use CSS for layout, but use tables for tabular data. It does not mean never use tables.
A: Different browsers have wildly different javascript/css performance, so it's very hard to generalise here. For example, IE7 has a shockingly slow engine, and Chrome's is mind-bogglingly fast. Firefox is somewhere in between, depennding on if you're using 2 or 3.
A: I would not take rendering speed as the most important aspect here. HTML tables are made for tabular data. Putting that into a lot of DIVs or so would be totally wrong in my understanding.
A: Like most of the above answers, I too would say use Tables if you are displaying tabular data and DIVs if you want to control layout (using CSS3). Contrary to belief, tables are not slower in rendering than DIVs if you set a few properties like colgroup and keep layout as fixed. Check out the details of how to in the following link:
sites.google.com/site/spyderhoodcommunity/xhtml/makingtablesrenderfasterwhenlistingtabulardata
A: For tabular data, use a table. Tables come with all kinds of nice features, like <thead> and <tfoot> tags, legends, titles, captions, etc. Everything you need to make a table a table.
Also, if the CSS doesn't work/isn't loaded/doesn't matter, the table will still look and work the way it should.
A: Personally from what I have read, if you are actually presenting tabular data, a table is more appropriate for the task, I personally hae found that to be pretty true.
As for raw number of what is "faster", as mentioned by @skaffman it depends on the browsers...but to be "correct" it would make sense to use a table for tabular data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Application specific metadata in SOAP header Do you think its a good idea to put our application specific metadata in the SOAP header?
E.g. In our organization, we want to track each message as it passes through various services, I want to track service path (just like TCP) to know which all services processed the message etc. For all this, currently we are defining our own message format (that has header and body) over SOAP message.
I want to get your opinion on whether this is a good idea or should I put my application metadata in the SOAP header itself.
Thanks
Manju
A: Put your application metadata in the SOAP header - otherwise you're supporting both your own private envelope format as well as the SOAP format, for no particular advantage.
Is your metadata large? That might be one reason to leave it out of the soap headers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Python: SWIG vs ctypes In python, under what circumstances is SWIG a better choice than ctypes for calling entry points in shared libraries? Let's assume you don't already have the SWIG interface file(s). What are the performance metrics of the two?
A: I have a rich experience of using swig. SWIG claims that it is a rapid solution for wrapping things. But in real life...
Cons:
SWIG is developed to be general, for everyone and for 20+ languages. Generally, it leads to drawbacks:
- needs configuration (SWIG .i templates), sometimes it is tricky,
- lack of treatment of some special cases (see python properties further),
- lack of performance for some languages.
Python cons:
1) Code style inconsistency. C++ and python have very different code styles (that is obvious, certainly), the possibilities of a swig of making target code more Pythonish is very limited. As an example, it is butt-heart to create properties from getters and setters. See this q&a
2) Lack of broad community. SWIG has some good documentation. But if one caught something that is not in the documentation, there is no information at all. No blogs nor googling helps. So one has to heavily dig SWIG generated code in such cases... That is terrible, I could say...
Pros:
*
*In simple cases, it is really rapid, easy and straight forward
*If you produced swig interface files once, you can wrap this C++ code to ANY of other 20+ languages (!!!).
*One big concern about SWIG is a performance. Since version 2.04 SWIG includes '-builtin' flag which makes SWIG even faster than other automated ways of wrapping. At least some benchmarks shows this.
When to USE SWIG?
So I concluded for myself two cases when the swig is good to use:
2) If one needs to wrap C++ code for several languages. Or if potentially there could be a time when one needs to distribute the code for several languages. Using SWIG is reliable in this case.
1) If one needs to rapidly wrap just several functions from some C++ library for end use.
Live experience
Update :
It is a year and a half passed as we did a conversion of our library by using SWIG.
First, we made a python version. There were several moments when we experienced troubles with SWIG - it is true. But right now we expanded our library to Java and .NET. So we have 3 languages with 1 SWIG. And I could say that SWIG rocks in terms of saving a LOT of time.
Update 2:
It is two years as we use SWIG for this library. SWIG is integrated into our build system. Recently we had major API change of C++ library. SWIG worked perfectly. The only thing we needed to do is to add several %rename to .i files so our CppCamelStyleFunctions() now looks_more_pythonish in python. First I was concerned about some problems that could arise, but nothing went wrong. It was amazing. Just several edits and everything distributed in 3 languages. Now I am confident that it was a good solution to use SWIG in our case.
Update 3:
It is 3+ years we use SWIG for our library. Major change: python part was totally rewritten in pure python. The reason is that Python is used for the majority of applications of our library now. Even if the pure python version works slower than C++ wrapping, it is more convenient for users to work with pure python, not struggling with native libraries.
SWIG is still used for .NET and Java versions.
The Main question here "Would we use SWIG for python if we started the project from the beginning?". We would! SWIG allowed us to rapidly distribute our product to many languages. It worked for a period of time which gave us the opportunity for better understanding our users requirements.
A: You can also use Pyrex, which can act as glue between high-level Python code and low-level C code. lxml is written in Pyrex, for instance.
A: SWIG generates (rather ugly) C or C++ code. It is straightforward to use for simple functions (things that can be translated directly) and reasonably easy to use for more complex functions (such as functions with output parameters that need an extra translation step to represent in Python.) For more powerful interfacing you often need to write bits of C as part of the interface file. For anything but simple use you will need to know about CPython and how it represents objects -- not hard, but something to keep in mind.
ctypes allows you to directly access C functions, structures and other data, and load arbitrary shared libraries. You do not need to write any C for this, but you do need to understand how C works. It is, you could argue, the flip side of SWIG: it doesn't generate code and it doesn't require a compiler at runtime, but for anything but simple use it does require that you understand how things like C datatypes, casting, memory management and alignment work. You also need to manually or automatically translate C structs, unions and arrays into the equivalent ctypes datastructure, including the right memory layout.
It is likely that in pure execution, SWIG is faster than ctypes -- because the management around the actual work is done in C at compiletime rather than in Python at runtime. However, unless you interface a lot of different C functions but each only a few times, it's unlikely the overhead will be really noticeable.
In development time, ctypes has a much lower startup cost: you don't have to learn about interface files, you don't have to generate .c files and compile them, you don't have to check out and silence warnings. You can just jump in and start using a single C function with minimal effort, then expand it to more. And you get to test and try things out directly in the Python interpreter. Wrapping lots of code is somewhat tedious, although there are attempts to make that simpler (like ctypes-configure.)
SWIG, on the other hand, can be used to generate wrappers for multiple languages (barring language-specific details that need filling in, like the custom C code I mentioned above.) When wrapping lots and lots of code that SWIG can handle with little help, the code generation can also be a lot simpler to set up than the ctypes equivalents.
A: ctypes is great, but does not handle C++ classes. I've also found ctypes is about 10% slower than a direct C binding, but that will highly depend on what you are calling.
If you are going to go with ctypes, definitely check out the Pyglet and Pyopengl projects, that have massive examples of ctype bindings.
A: I'm going to be contrarian and suggest that, if you can, you should write your extension library using the standard Python API. It's really well-integrated from both a C and Python perspective... if you have any experience with the Perl API, you will find it a very pleasant surprise.
Ctypes is nice too, but as others have said, it doesn't do C++.
How big is the library you're trying to wrap? How quickly does the codebase change? Any other maintenance issues? These will all probably affect the choice of the best way to write the Python bindings.
A: Just wanted to add a few more considerations that I didn't see mentioned yet.
[EDIT: Ooops, didn't see Mike Steder's answer]
If you want to try using a non Cpython implementation (like PyPy, IronPython or Jython), then ctypes is about the only way to go. PyPy doesn't allow writing C-extensions, so that rules out pyrex/cython and Boost.python. For the same reason, ctypes is the only mechanism that will work for IronPython and (eventually, once they get it all working) jython.
As someone else mentioned, no compilation is required. This means that if a new version of the .dll or .so comes out, you can just drop it in, and load that new version. As long as the none of the interfaces changed, it's a drop in replacement.
A: Something to keep in mind is that SWIG targets only the CPython implementation. Since ctypes is also supported by the PyPy and IronPython implementations it may be worth writing your modules with ctypes for compatibility with the wider Python ecosystem.
A: CTypes is very cool and much easier than SWIG, but it has the drawback that poorly or malevolently-written python code can actually crash the python process. You should also consider boost python. IMHO it's actually easier than swig while giving you more control over the final python interface. If you are using C++ anyway, you also don't add any other languages to your mix.
A: In my experience, ctypes does have a big disadvantage: when something goes wrong (and it invariably will for any complex interfaces), it's a hell to debug.
The problem is that a big part of your stack is obscured by ctypes/ffi magic and there is no easy way to determine how did you get to a particular point and why parameter values are what they are..
A: I have found SWIG to be be a little bloated in its approach (in general, not just Python) and difficult to implement without having to cross the sore point of writing Python code with an explicit mindset to be SWIG friendly, rather than writing clean well-written Python code. It is, IMHO, a much more straightforward process to write C bindings to C++ (if using C++) and then use ctypes to interface to any C layer.
If the library you are interfacing to has a C interface as part of the library, another advantage of ctypes is that you don't have to compile a separate python-binding library to access third-party libraries. This is particularly nice in formulating a pure-python solution that avoids cross-platform compilation issues (for those third-party libs offered on disparate platforms). Having to embed compiled code into a package you wish to deploy on something like PyPi in a cross-platform friendly way is a pain; one of my most irritating points about Python packages using SWIG or underlying explicit C code is their general inavailability cross-platform. So consider this if you are working with cross-platform available third party libraries and developing a python solution around them.
As a real-world example, consider PyGTK. This (I believe) uses SWIG to generate C code to interface to the GTK C calls. I used this for the briefest time only to find it a real pain to set up and use, with quirky odd errors if you didn't do things in the correct order on setup and just in general. It was such a frustrating experience, and when I looked at the interace definitions provided by GTK on the web I realized what a simple excercise it would be to write a translator of those interface to python ctypes interface. A project called PyGGI was born, and in ONE day I was able to rewrite PyGTK to be a much more functiona and useful product that matches cleanly to the GTK C-object-oriented interfaces. And it required no compilation of C-code making it cross-platform friendly. (I was actually after interfacing to webkitgtk, which isn't so cross-platform). I can also easily deploy PyGGI to any platform supporting GTK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
}
|
Q: Limiting the number of records from mysqldump? I am trying to load a small sample of records from a large database into a test database.
How do you tell mysqldump to only give you n records out of 8 million?
Thanks
A: mysqldump can be given a SQL query to execute, from which it will take the data for the dump. You can then use the "limit X" clause in your query to restrict the number of rows.
A: If you want to get n records from a specific table you can do something like this:
mysqldump --opt --where="1 limit 1000000" database table > dump.sql
This will dump the first 1000000 rows from the table named table into the file dump.sql.
A: As skaffman says, use the --where option:
mysqldump --opt --where="1 limit 1000000" database
Of course, that would give you the first million rows from every table.
A: As the default order is ASC which is rarely what you want in this situation, you need to have a proper database design to make DESC work out of the box. If all your tables have ONE primary key column with the same name (natural or surrogate) you can easily dump the n latest records using:
mysqldump --opt --where="1 ORDER BY id DESC limit 1000000" --all-databases > dump.sql
This is a perfect reason to why you should always name your PK's id and avoid composite PK's, even in association tables (use surrogate keys instead).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "159"
}
|
Q: Marking A Class Static in VB.NET As just stated in a recent question and answer, you can't inherit from a static class. How does one enforce the rules that go along with static classes inside VB.NET? Since the framework is compatible between C# and VB it would make sense that there would be a way to mark a class static, but there doesn't seem to be a way.
A: Almost there. You've got to prevent instantiation, too.
NotInheritable Class MyStaticClass
''' <summary>
''' Prevent instantiation.
''' </summary>
Private Sub New()
End Sub
Public Shared Function MyMethod() As String
End Function
End Class
*
*Shared is like method of static class.
*NotInheritable is like sealed.
*Private New is like static class can not be instantiated.
See:
MSDN - Static Classes and Static Class Members
A: If you just want to create a class that you can't inherit, in C# you can use Sealed, and in VB.Net use NotInheritable.
The VB.Net equivalent of static is shared.
A: You can create static class in vb.net. The solution is
Friend NotInheritable Class DB
Public Shared AGE As Integer = 20
End Class
AGE variable is public static, you can use it in other code just like this
Dim myage As Integer = DB.AGE
Friend = public, NotInheritable = static
A: From the CLR point of view, C# static class is just "sealed" and "abstract" class. You can't create an instance, because it is abstract, and you can't inherit from it since it is sealed. The rest is just some compiler magic.
A: Module == static class
If you just want a class that you can't inherit, use a NotInheritable class; but it won't be static/Shared. You could mark all the methods, properties, and members as Shared, but that's not strictly the same thing as a static class in C# since it's not enforced by the compiler.
If you really want the VB.Net equivalent to a C# static class, use a Module. It can't be inherited and all members, properties, and methods are static/shared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "94"
}
|
Q: Are booleans as method arguments unacceptable? A colleague of mine states that booleans as method arguments are not acceptable. They shall be replaced by enumerations. At first I did not see any benefit, but he gave me an example.
What's easier to understand?
file.writeData( data, true );
Or
enum WriteMode {
Append,
Overwrite
};
file.writeData( data, Append );
Now I got it! ;-)
This is definitely an example where an enumeration as second parameter makes the code much more readable.
So, what's your opinion on this topic?
A: Enums are better but I wouldn't call boolean params as "unacceptable". Sometimes it's just easier to throw one little boolean in and move on (think private methods etc.)
A: Booleans may be OK in languages that have named parameters, like Python and Objective-C, since the name can explain what the parameter does:
file.writeData(data, overwrite=true)
or:
[file writeData:data overwrite:YES]
A: Enums also allow for future modifications, where you now want a third choice (or more).
A: Enums have a definite benefit, but you should't just go replacing all your booleans with enums. There are many places where true/false is actually the best way to represent what is going on.
However, using them as method arguments is a bit suspect, simply because you can't see without digging into things what they are supposed to do, as they let you see what the true/false actually means
[Edit for the current state in 2022]
In modern C#, or other languages that support this, the nicest way to do it is with named arguments:
var worker = new BackgroundWorker(workerReportsProgress: true);
If your language doesn't allow for named arguments, then you may find properties to be a reasonable solution as well
[Original Answer from 2008 left for posterity]
Properties (especially with C#3 object initializers) or keyword arguments (a la ruby or python) are a much better way to go where you'd otherwise use a boolean argument.
C# example:
var worker = new BackgroundWorker { WorkerReportsProgress = true };
Ruby example
validates_presence_of :name, :allow_nil => true
Python example
connect_to_database( persistent=true )
The only thing I can think of where a boolean method argument is the right thing to do is in java, where you don't have either properties or keyword arguments. This is one of the reasons I hate java :-(
A: I would not agree that it is a good rule. Obviously, Enum makes for a better explicit or verbose code at some instances, but as a rule it seems way over reaching.
First let me take your example:
The programmers responsibility (and ability) to write good code is not really jeopardized by having a Boolean parameter. In your example the programmer could have written just as verbose code by writing:
dim append as boolean = true
file.writeData( data, append );
or I prefer more general
dim shouldAppend as boolean = true
file.writeData( data, shouldAppend );
Second:
The Enum example you gave is only "better" because you are passing a CONST. Most likely in most application at least some if not most of the time parameters that are passed to functions are VARIABLES. in which case my second example (giving variables with good names) is much better and Enum would have given you little benefits.
A: While it is true that in many cases enums are more readable and more extensible than booleans, an absolute rule that "booleans are not acceptable" is daft. It is inflexible and counter-productive - it does not leave room for human judgement. They're a fundamental built in type in most languages because they're useful - consider applying it to other built-in-types: saying for instance "never use an int as a parameter" would just be crazy.
This rule is just a question of style, not of potential for bugs or runtime performance. A better rule would be "prefer enums to booleans for reasons of readability".
Look at the .Net framework. Booleans are used as parameters on quite a few methods. The .Net API is not perfect, but I don't think that the use of boolean as parameters is a big problem. The tooltip always gives you the name of the parameter, and you can build this kind of guidance too - fill in your XML comments on the method parameters, they will come up in the tooltip.
I should also add that there is a case when you should clearly refactor booleans to an enumeration - when you have two or more booleans on your class, or in your method params, and not all states are valid (e.g. it's not valid to have them both set true).
For instance, if your class has properties like
public bool IsFoo
public bool IsBar
And it's an error to have both of them true at the same time, what you've actually got is three valid states, better expressed as something like:
enum FooBarType { IsFoo, IsBar, IsNeither };
A: Some rules that your colleague might be better adhering to are:
*
*Don't be dogmatic with your design.
*Choose what fits most appropriately for the users of your code.
*Don't try to bash star-shaped pegs into every hole just because you like the shape this month!
A: Use the one that best models your problem. In the example you give, the enum is a better choice. However, there would be other times when a boolean is better. Which makes more sense to you:
lock.setIsLocked(True);
or
enum LockState { Locked, Unlocked };
lock.setLockState(Locked);
In this case, I might choose the boolean option since I think it's quite clear and unambiguous, and I'm pretty sure my lock is not going to have more than two states. Still, the second choice is valid, but unnecessarily complicated, IMHO.
A: A Boolean would only be acceptable if you do not intend to extend the functionality of the framework. The Enum is preferred because you can extend the enum and not break previous implementations of the function call.
The other advantage of the Enum is that is easier to read.
A: If the method asks a question such as:
KeepWritingData (DataAvailable());
where
bool DataAvailable()
{
return true; //data is ALWAYS available!
}
void KeepWritingData (bool keepGoing)
{
if (keepGoing)
{
...
}
}
boolean method arguments seem to make absolutely perfect sense.
A: It depends on the method. If the method does something that is very obviously a true/false thing then it is fine, e.g. below [though not I am not saying this is the best design for this method, it's just an example of where the usage is obvious].
CommentService.SetApprovalStatus(commentId, false);
However in most cases, such as the example you mention, it is better to use an enumeration. There are many examples in the .NET Framework itself where this convention is not followed, but that is because they introduced this design guideline fairly late on in the cycle.
A: It does make things a bit more explicit, but does start to massively extend the complexity of your interfaces - in a sheer boolean choice such as appending/overwriting it seems like overkill. If you need to add a further option (which I can't think of in this case), you can always perform a refactor (depending on the language)
A: Enums can certainly make the code more readable. There are still a few things to watch out for (in .net at least)
Because the underlying storage of an enum is an int, the default value will be zero, so you should make sure that 0 is a sensible default. (E.g. structs have all fields set to zero when created, so there's no way to specify a default other than 0. If you don't have a 0 value, you can't even test the enum without casting to int, which would be bad style.)
If your enum's are private to your code (never exposed publicly) then you can stop reading here.
If your enums are published in any way to external code and/or are saved outside of the program, consider numbering them explicitly. The compiler automatically numbers them from 0, but if you rearrange your enums without giving them values you can end up with defects.
I can legally write
WriteMode illegalButWorks = (WriteMode)1000000;
file.Write( data, illegalButWorks );
To combat this, any code that consumes an enum that you can't be certain of (e.g. public API) needs to check if the enum is valid. You do this via
if (!Enum.IsDefined(typeof(WriteMode), userValue))
throw new ArgumentException("userValue");
The only caveat of Enum.IsDefined is that it uses reflection and is slower. It also suffers a versioning issue. If you need to check the enum value often, you would be better off the following:
public static bool CheckWriteModeEnumValue(WriteMode writeMode)
{
switch( writeMode )
{
case WriteMode.Append:
case WriteMode.OverWrite:
break;
default:
Debug.Assert(false, "The WriteMode '" + writeMode + "' is not valid.");
return false;
}
return true;
}
The versioning issue is that old code may only know how to handle the 2 enums you have. If you add a third value, Enum.IsDefined will be true, but the old code can't necessarily handle it. Whoops.
There's even more fun you can do with [Flags] enums, and the validation code for that is slightly different.
I'll also note that for portability, you should use call ToString() on the enum, and use Enum.Parse() when reading them back in. Both ToString() and Enum.Parse() can handle [Flags] enum's as well, so there's no reason not to use them. Mind you, it's yet another pitfall, because now you can't even change the name of the enum without possibly breaking code.
So, sometimes you need to weigh all of the above in when you ask yourself Can I get away with just an bool?
A: To me, neither using boolean nor enumeration is a good approach. Robert C. Martin captures this very clearly in his Clean Code Tip #12: Eliminate Boolean Arguments:
Boolean arguments loudly declare that the function does more than one thing. They are confusing and should be eliminated.
If a method does more than one thing, you should rather write two different methods, for example in your case: file.append(data) and file.overwrite(data).
Using an enumeration doesn't make things clearer. It doesn't change anything, it's still a flag argument.
A: Remember the question Adlai Stevenson posed to ambassador Zorin at the U.N. during the cuban missile crisis?
"You are in the courtroom of world
opinion right now, and you can answer
yes or no. You have denied that [the missiles]
exist, and I want to know whether I
have understood you correctly.... I am
prepared to wait for my answer until
hell freezes over, if that's your
decision."
If the flag you have in your method is of such a nature that you can pin it down to a binary decision, and that decision will never turn into a three-way or n-way decision, go for boolean. Indications: your flag is called isXXX.
Don't make it boolean in case of something that is a mode switch. There is always one more mode than you thought of when writing the method in the first place.
The one-more-mode dilemma has e.g. haunted Unix, where the possible permission modes a file or directory can have today result in weird double meanings of modes depending on file type, ownership etc.
A: There are two reasons I've run into this being a bad thing:
*
*Because some people will write methods like:
ProcessBatch(true, false, false, true, false, false, true);
This is obviously bad because it's too easy to mix up parameters, and you have no idea by looking at it what you're specifying. Just one bool isn't too bad though.
*Because controlling program flow by a simple yes/no branch might mean you have two entirely different functions that are wrapped up into one in an awkard way. For instance:
public void Write(bool toOptical);
Really, this should be two methods
public void WriteOptical();
public void WriteMagnetic();
because the code in these might be entirely different; they might have to do all sorts of different error handling and validation, or maybe even have to format the outgoing data differently. You can't tell that just by using Write() or even Write(Enum.Optical) (though of course you could have either of those methods just call internal methods WriteOptical/Mag if you want).
I guess it just depends. I wouldn't make too big of a deal about it except for #1.
A: Boolean's represent "yes/no" choices. If you want to represent a "yes/no", then use a boolean, it should be self-explanatory.
But if it's a choice between two options, neither of which is clearly yes or no, then an enum can sometimes be more readable.
A: I think you almost answered this yourself, I think the end aim is to make the code more readable, and in this case the enum did that, IMO its always best to look at the end aim rather than blanket rules, maybe think of it more as a guideline i.e. enums are often more readable in code than generic bools, ints etc but there will always be exceptions to the rule.
A: IMHO it seems like an enum would be the obvious choice for any situation where more than two options are possible. But there definitely ARE situations where a boolean is all you need. In that case I would say that using an enum where a bool would work would be an example of using 7 words when 4 will do.
A: Booleans make sense when you have an obvious toggle which can only be one of two things (i.e. the state of a light bulb, on or off). Other than that, it's good to write it in such a way that it's obvious what you're passing - e.g. disk writes - unbuffered, line-buffered, or synchronous - should be passed as such. Even if you don't want to allow synchronous writes now (and so you're limited to two options), it's worth considering making them more verbose for the purposes of knowing what they do at first glance.
That said, you can also use False and True (boolean 0 and 1) and then if you need more values later, expand the function out to support user-defined values (say, 2 and 3), and your old 0/1 values will port over nicely, so your code ought not to break.
A: Sometimes it's just simpler to model different behaviour with overloads. To continue from your example would be:
file.appendData( data );
file.overwriteData( data );
This approach degrades if you have multiple parameters, each allowing a fixed set of options. For example, a method that opens a file might have several permutations of file mode (open/create), file access (read/write), sharing mode (none/read/write). The total number of configurations is equal to the Cartesian products of the individual options. Naturally in such cases multiple overloads are not appropriate.
Enums can, in some cases make code more readable, although validating the exact enum value in some languages (C# for example) can be difficult.
Often a boolean parameter is appended to the list of parameters as a new overload. One example in .NET is:
Enum.Parse(str);
Enum.Parse(str, true); // ignore case
The latter overload became available in a later version of the .NET framework than the first.
If you know that there will only ever be two choices, a boolean might be fine. Enums are extensible in a way that won't break old code, although old libraries might not support new enum values so versioning cannot be completely disregarded.
EDIT
In newer versions of C# it's possible to use named arguments which, IMO, can make calling code clearer in the same way that enums can. Using the same example as above:
Enum.Parse(str, ignoreCase: true);
A: Where I do agree that Enums are good way to go, in methods where you have 2 options (and just two options you can have readability without enum.)
e.g.
public void writeData(Stream data, boolean is_overwrite)
Love the Enums, but boolean is useful too.
A: This is a late entry on an old post, and it's so far down the page that nobody will ever read it, but since nobody has said it already....
An inline comment goes a long way to solving the unexpected bool problem. The original example is particularly heinous: imagine trying to name the variable in the function declearation! It'd be something like
void writeData( DataObject data, bool use_append_mode );
But, for the sake of example, let's say that's the declaration. Then, for an otherwise unexplained boolean argument, I put the variable name in an inline comment. Compare
file.writeData( data, true );
with
file.writeData( data, true /* use_append_mode */);
A: It really depends on the exact nature of the argument. If it is not a yes/no or true/false then a enum makes it more readable. But with an enum you need to check the argument or have acceptable default behaviour since undefined values of the underlying type can be passed.
A: The use of enums instead of booleans in your example does help make the method call more readable. However, this is a substitute for my favorite wish item in C#, named arguments in method calls. This syntax:
var v = CallMethod(pData = data, pFileMode = WriteMode, pIsDirty = true);
would be perfectly readable, and you could then do what a programmer should do, which is choose the most appropriate type for each parameter in the method without regard to how it looks in the IDE.
C# 3.0 allows named arguments in constructors. I don't know why they can't do this with methods as well.
A: Booleans values true/false only. So it is not clear what it represent. Enum can have meaningful name, e.g OVERWRITE, APPEND, etc. So enums are better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "124"
}
|
Q: How do I serve a script with apache instead of running it? I'm trying to host a python script using an apache web server, but the server tries to run the script instead of just offering it for download.
I do not have direct access to server, and adding the line
AddType text/plain .py
to .htaccess in the root folder does not appear to work, though I could be doing something wrong.
How do I get the server to just send the file as text instead of trying to run it?
-Edit
Changing the name does not work. Script.py.safe still give a 500 Server error when you click it.
I should also mention that the .htaccess file does work, but for some reason that one addType line is not working. Either because it's not overriding something, or the line is wrong.
A: If you can't change the Apache config and you can't override it with an htaccess file, then it seems to me that the easiest solutions would be either to change the file extension, or else to write a script that prints the contents of the target script.
Both are hacks to some extent, but the correct solution is to change the Apache config.
A: In your .htaccess:
RemoveHandler .py
A: One option is to change the extention and make clear that it should be renamed. IE python.py.safe or python.py.dl. The user would then need to remove the extra bit.
You could also Zip it up.
A: I would write something that loads the python script up. This way you could even get energetic and include formatting and styling of the code. You could even write it in python since you will not have precluded that by file extension.
A: <IfModule mime_module>
<Files *.py>
ForceType text/plain
</Files>
</IfModule>
in a .htaccess for the folder should work ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Zooming an element and its contents-- an alternative to CSS3's zoom property? Is there a cross-browser method to emulate CSS3's zoom property? I know how to zoom images and text separately, but cannot seem to keep everything aligned.
One solution might be to read the computed styles of the element and its children, convert all measures to px, multiply them by some factor, and then generate HTML/CSS with these new styles. Another solution might actually make sense. :)
Important: A correct solution assumes nothing about the page it acts on. We don't know that every element is sized in px, styled by an external stylesheet, or anything else.
Thanks!
A: You could try using the Scriptaculous library that provides Effect.Scale functionality.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: where can I find a description of *all* MIPS instructions Does anyone know of a web site where I can find a list of 32-bit MIPS instructions/opcodes, with the following features:
*
*Clearly distinguishes between real opcodes and assembly-language macros (pseudo-instructions)
*Describes the instruction behavior including differences depending on privilege level.
*Indicates in which instruction set revision the instruction was introduced/revised (e.g. MIPS I, MIPS II, MIPS32, etc.)
*Includes privileged instructions such as syscall.
I am aware of numerous web sites which document "part of" the instruction set, mostly for teaching purposes. They tend to leave out or only partially describe floating-point and privileged instructions.
In case you're wondering, I'm looking at Verilog code for a MIPS processor subset, and trying to figure out exactly to what extent it complies with the instruction sets of any real MIPS processors!
A: Okay, I found something!
MIPS offers a set of "MIPS 32 reference manuals" which refer to the latest, standardized instruction set (MIPS32v2): here
These include just about everything, except the information about which version the instructions originated in :-(
WAIT A SEC...
This class website at Cornell includes links to what appears to be the same manual, but is in fact an older version of it, and volume 2 of that older version does in fact include information about when the instructions where first introduced. Woohoo!
Why would MIPS remove this information from the revised documentation? There doesn't seem to be any explanation in the revision history.
A: I can only partially answer the question: I'd recommend See MIPS Run by Dominic Sweetman, if you're not already referring to it. I have the first edition of the book, the second edition is now current.
table 8.2 lists each opcode and expected behavior, differentiating assembler macros and listing the instructions they decompose to. Unfortunately it does not differentiate user vs kernel mode.
table 8.6 lists the ISA level where each instruction was introduced, including obscure variants like the LSI MiniRISC
syscall is present in the table, though lacking much description
The first edition mentions the kernel. supervisor, and user privilege levels but does not discuss what operations are allowed in each. I do not know what changes were made in the second edition.
A: Doesn't include instruction descriptions, but the source of the GNU assembler is probably as detailed as you can get regarding what instructions are available on what specific CPUs.
Get binutils and look at opcodes/mips-*.c
A: The current instruction-set reference manual is free online: MIPS® Architecture for Programmers
Volume II-A: The MIPS32® Instruction
Set Manual. That link is Revision 6.06
December 15, 2016. (i.e. it documents MIPS32 Release 6).
It documents all user and supervisor/kernel mode instructions, and all floating-point, in full detail including their machine-code encoding, and with an Operation section that shows what they do. It still documents all the instructions that were removed in MIPS32 release 6. (MIPS32 Release 6 also moved around a lot of opcodes, and this is well documented).
See https://www.mips.com/products/architectures/mips32/ for the latest version. mips.com has a section for "classic cores", but that still appears to only go back to MIPS32, not historical stuff.
Sample of the "availability and compatibility" section for balc (Branch and Link Compact: no branch-delay slot, and GRP31 is the implicit destination, freeing up 26 bits for an offset<<2):
This instruction is introduced by and required as of Release 6.
Release 6 instruction BALC occupies the same encoding as pre-Release 6
instruction SWC2. The SWC2 instruction has been moved to the COP2
major opcode in MIPS Release 6
Or for LDXC1 fd, index(base) (Load Doubleword Indexed to Floating Point)
This instruction has been removed in Release 6.
Required in all versions of MIPS64 since MIPS64 Release 1. Not available in MIPS32 Release 1. Required in
MIPS32 Release 2 and all subsequent versions of MIPS32. When required, required whenever FPU is present,
whether a 32-bit or 64-bit FPU, whether in 32-bit or 64-bit FP Register Mode (FIRF64=0 or 1, StatusFR=0 or 1).
For historical stuff, I found the MIPS IV Instruction Set
Revision 3.2
September, 1995 on a cmu.edu web page. It lists when instructions were introduced, e.g. MIPS I for div, MIPS III for dmult and other 64-bit instructions, MIPS II for ll / sc.
A good quick-reference with pseudocode for the effect of each instruction is https://inst.eecs.berkeley.edu/~cs61c/resources/MIPS_help.html. It doesn't include encoding details, but does accurately describe the effect of branch and jump instructions on the program counter. (Which is somewhat tricky: they're relative or section-absolute to the branch-delay slot.)
It's not complete even for MIPS I integer instructions, though: it's missing the unaligned-load helper instructions LWL and LWR and corresponding SWL/R stores which were present in MIPS I. It also doesn't include any FP stuff, or later MIPS instructions like mul (only mult). I don't know what else might be missing; I didn't cross reference it against a complete list.
The MIPS-IV manual linked above confirms that lwl/lwr were available in MIPS I (and documents that the load delay slot restriction applies to them).
A: This web site (archive.org) describes most of the MIPS instruction set and their encoding. It's not complete, though: missing at least nor and maybe other things.
A good quick-reference with pseudocode for the effect of each instruction is https://inst.eecs.berkeley.edu/~cs61c/resources/MIPS_help.html. It doesn't include encoding details.
The MIPS web site also has technical documents about the various cores.
For example, I downloaded the manual for the MIPS 4KE core (document #MD00103) "MIPS32® 4KE™ Processor Core Family Software User’s Manual" and chapter 10 contains a detailed description of the Instruction Set.
Note that you have to register to access the documents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: What is the method for converting radians to degrees? I run into this occasionally and always forget how to do it.
One of those things that pop up ever so often.
Also, what's the formula to convert angles expressed in radians to degrees and back again?
A: In javascript you can do it this way
radians = degrees * (Math.PI/180);
degrees = radians * (180/Math.PI);
A: radians = degrees * (pi/180)
degrees = radians * (180/pi)
As for implementation, the main question is how precise you want to be about the value of pi. There is some related discussion here
A: a complete circle in radians is 2*pi. A complete circle in degrees is 360. To go from degrees to radians, it's (d/360) * 2*pi, or d*pi/180.
A: x rads in degrees - > x*180/pi
x degrees in rads -> x*pi/180
I guess if you wanted to make a function for this [in PHP]:
function convert($type, $num) {
if ($type == "rads") {
$result = $num*180/pi();
}
if ($type == "degs") {
$result = $num*pi()/180;
}
return $result;
}
Yes, that could probably be written better.
A: This works well enough for me :)
// deg2rad * degrees = radians
#define deg2rad (3.14159265/180.0)
// rad2deg * radians = degrees
#define rad2deg (180/3.14159265)
A: 180 degrees = PI * radians
A: 360 degrees is 2*PI radians
You can find the conversion formulas at: http://en.wikipedia.org/wiki/Radian#Conversion_between_radians_and_degrees.
A: 360 degrees = 2*pi radians
That means deg2rad(x) = x*pi/180 and rad2deg(x) = 180x/pi;
A: pi Radians = 180 degrees
So 1 degree = pi/180 radians
or 1 radian = 180/pi degrees
A: For double in c# this might be helpful:
public static double Conv_DegreesToRadians(this double degrees)
{
//return degrees * (Math.PI / 180d);
return degrees * 0.017453292519943295d;
}
public static double Conv_RadiansToDegrees(this double radians)
{
//return radians * (180d / Math.PI);
return radians * 57.295779513082323d;
}
A: Here is some code which extends Object with rad(deg), deg(rad) and also two more useful functions: getAngle(point1,point2) and getDistance(point1,point2) where a point needs to have a x and y property.
Object.prototype.rad = (deg) => Math.PI/180 * deg;
Object.prototype.deg = (rad) => 180/Math.PI * rad;
Object.prototype.getAngle = (point1, point2) => Math.atan2(point1.y - point2.y, point1.x - point2.x);
Object.prototype.getDistance = (point1, point2) => Math.sqrt(Math.pow(point1.x-point2.x, 2) + Math.pow(point1.y-point2.y, 2));
A: radians = (degrees/360) * 2 * pi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "174"
}
|
Q: java.net.SocketException: Software caused connection abort: recv failed I haven't been able to find an adequate answer to what exactly the following error means:
java.net.SocketException: Software caused connection abort: recv failed
Notes:
*
*This error is infrequent and unpredictable; although getting this error means that all future requests for URIs will also fail.
*The only solution that works (also, only occasionally) is to reboot Tomcat and/or the actual machine (Windows in this case).
*The URI is definitely available (as confirmed by asking the browser to do the fetch).
Relevant code:
BufferedReader reader;
try {
URL url = new URL(URI);
reader = new BufferedReader(new InputStreamReader(url.openStream())));
} catch( MalformedURLException e ) {
throw new IOException("Expecting a well-formed URL: " + e);
}//end try: Have a stream
String buffer;
StringBuilder result = new StringBuilder();
while( null != (buffer = reader.readLine()) ) {
result.append(buffer);
}//end while: Got the contents.
reader.close();
A: Are you accessing http data? Can you use the HttpClient library instead of the standard library? The library has more options and will provide better error messages.
http://hc.apache.org/httpclient-3.x/
A: The only time I've seen something like this happen is when I have a bad connection, or when somebody is closing the socket that I am using from a different thread context.
A: This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication.
A: This usually means that there was a network error, such as a TCP timeout. I would start by placing a sniffer (wireshark) on the connection to see if you can see any problems. If there is a TCP error, you should be able to see it. Also, you can check your router logs, if this is applicable. If wireless is involved anywhere, that is another source for these kind of errors.
A: Try adding 'autoReconnect=true' to the jdbc connection string
A: This error occurs when a connection is closed abruptly (when a TCP connection is reset while there is still data in the send buffer). The condition is very similar to a much more common 'Connection reset by peer'. It can happen sporadically when connecting over the Internet, but also systematically if the timing is right (e.g. with keep-alive connections on localhost).
An HTTP client should just re-open the connection and retry the request. It is important to understand that when a connection is in this state, there is no way out of it other than to close it. Any attempt to send or receive will produce the same error.
Don't use URL.open(), use Apache-Commons HttpClient which has a retry mechanism, connection pooling, keep-alive and many other features.
Sample usage:
HttpClient httpClient = HttpClients.custom()
.setConnectionTimeToLive(20, TimeUnit.SECONDS)
.setMaxConnTotal(400).setMaxConnPerRoute(400)
.setDefaultRequestConfig(RequestConfig.custom()
.setSocketTimeout(30000).setConnectTimeout(5000).build())
.setRetryHandler(new DefaultHttpRequestRetryHandler(5, true))
.build();
// the httpClient should be re-used because it is pooled and thread-safe.
HttpGet request = new HttpGet(uri);
HttpResponse response = httpClient.execute(request);
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
// handle response ...
A: This will happen from time to time either when a connection times out or when a remote host terminates their connection (closed application, computer shutdown, etc). You can avoid this by managing sockets yourself and handling disconnections in your application via its communications protocol and then calling shutdownInput and shutdownOutput to clear up the session.
A: Look if you have another service or program running on the http port. It happened to me when I tried to use the port and it was taken by another program.
A: If you are using Netbeans to manage Tomcat, try to disable HTTP monitor in Tools - Servers
A: I too had this problem. My solution was:
sc.setSoLinger(true, 10);
COPY FROM A WEBSITE -->By using the setSoLinger() method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.
Maybe it is not the answer to everybody but to some people.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "92"
}
|
Q: Can you have just a comment in a block of your SQL if-statement? I'd like to just put in a comment in the block of my if-statement, but I get an error when I try. I want to be more like Steve McConnell.
declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
--can't drop primary keys
END
The error I get is:
Incorrect syntax near 'END'.
If I add something after the comment, i.e. PRINT @ConstraintName, it works fine.
A: No, you cannot have an empty if block (or one that contains only comments).
You don't say why you would want this. If you are just trying to comment out the contents of the if for debugging, you should comment the entire if.
A: SELECT NULL will generate a result-set and could affect client apps. Seems better to do something that will have no effect, like:
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
DECLARE @Dummy bit -- Do nothing here, but this is required to compile
END
A: I can't say for sure in SQL Server, but in Oracle PL/SQL you would put a NULL statement in a block that you want to do nothing:
BEGIN
-- This is a comment
NULL;
END
A: Good tips here: How to do nothing in SQL Server
BEGIN
DONOTHING:
END
So you're just defining a label.
A: No, I don't think you can. If you want to temporarily comment that out, you'll probably need to just put a /* ... */ around the entire statement.
A: It's not the comment. It's that you have an empty if block. You have to have at least one statement in there. Putting in a print statement might be your best bet.
A: Since you can't have an "empty" blocks (thanks Charles Graham), I'll place a comment above the if-statement for the intention of the conditional (thanks BlackWasp), and then have a comment within the begin..end block that describes a dummy declare (thanks GiLM).
Do you think this is how I should comment the code?
declare @ConstraintName varchar(255)
set @ConstraintName = 'PK_Whatever'
--can't drop primary keys
IF LEFT(@ConstraintName, 2) = 'PK'
BEGIN
--do nothing here
DECLARE @Dummy bit --required to compile
END
A: Would it not be better to design your SQL statement around items you do wish to drop constraints for? So If you wish to remove the ability for this then
If left(@constraintname,2 <> 'PK'
BEGIN
-- Drop your constraint here
ALTER TABLE dbo.mytable DROP constraint ... -- etc
END
A: i know it doesn't answer your original question as to whether you can place just a comment inside a block, but why not inverse your conditional so the block only executes if <> 'PK'?
-- drop only if not primary
IF LEFT (@ConstraintName, 2) <> 'PK'
BEGIN
--do something here
END
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Strategy for storing an string of unspecified length in Sql Server? So a column will hold some text that beforehand I won't know how long the length of this string can be. Realistically 95% of the time, it will probably be between 100-500 chars, but there can be that one case where it will 10000 chars long. I have no control over the size of this string and never does the user. Besides varchar(max), what other strategy have you guys found useful? Also what are some cons of varchar(max)?
A: Varchar(max) in sqlserver 2005 is what I use.
SqlServer handles large string fields weirdly, in that if you specify "text" or a large varchar, but not max, it stores part of the bits in the record and the rest outside.
To my knowledge with varchar(max) it goes ahead and stores the entire contents out of the record, which makes it less efficient than a small text input. But its more efficient than a "text" field since it does not have to look up that information 2 times by getting part inline and the rest from a pointer.
A: One inelegant but effective approach would be to have two columns in your table, one a varchar big enough to cover your majority of cases, and another of a CLOB/TEXT type to store the freakishly large ones. When inserting/updating, you can get the size of your string, and store it in the appropriate column.
Like I say, not pretty, but it would give you the performance of varchar for the majority case, without breaking when you have larger values.
A: Have you considered using the BLOB type?
Also, out of curiosity, is you don't control the size of the string, and neither does the user, who does?
A: nvarchar(max) is definitely your best bet - as i'm sure you know it will only allocate the space required for the data you are actually storing per row, not the actual max of the datatype per row.
The only con i would see would be if you are constantly updating a row and it is switching from less than 8000 bytes to > 8000 bytes often in which case SQL will change the storage to a LOB and store a pointer to the data whenever you go over 8000 bytes. Changing back and forth would be expensive in this case, but you don't really have any other options in this case that I can see - so it's kind of a moot point.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I pInvoke the function SHCameraCapture (camera dialog) from Aygshell.dll from WinMO6 I need to show a camera capture dialog in a compact framework 3.7 application by pinvoking SHCameraCapture from the dll Aygshell.dll. I cannont use the managed object CameraCaptureDialog because of limitations with the technology I'm working with. Instead, I need to access it by Pinvoking it.
See http://msdn.microsoft.com/en-us/library/aa454995.aspx for documentation on the function. The function takes in a struct that defines the parameters of the dialog. e.g. where to save the file, what resolution to use.
I would imaging that I would have to define a copy of the struct in C# and decorate the sturct with the attribute StructLayout. I also imagine that the code would involve [DllImport("aygshell.dll")]. Any sample code of how to call this would be much appreciated.
A: this code works....
#region Enumerations
public enum CAMERACAPTURE_STILLQUALITY
{
CAMERACAPTURE_STILLQUALITY_DEFAULT = 0,
CAMERACAPTURE_STILLQUALITY_LOW = 1,
CAMERACAPTURE_STILLQUALITY_NORMAL = 2,
CAMERACAPTURE_STILLQUALITY_HIGH = 3
}
public enum CAMERACAPTURE_VIDEOTYPES
{
CAMERACAPTURE_VIDEOTYPE_ALL = 0xFFFF,
CAMERACAPTURE_VIDEOTYPE_STANDARD = 1,
CAMERACAPTURE_VIDEOTYPE_MESSAGING = 2
}
public enum CAMERACAPTURE_MODE
{
CAMERACAPTURE_MODE_STILL = 0,
CAMERACAPTURE_MODE_VIDEOONLY = 1,
CAMERACAPTURE_MODE_VIDEOWITHAUDIO = 2
}
#endregion //Enumerations
#region Structures
[StructLayout(LayoutKind.Sequential,CharSet=CharSet.Unicode)]
public struct struSHCAMERACAPTURE
{
public uint cbSize;
public IntPtr hwndOwner;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public String szFile;
[MarshalAs(UnmanagedType.LPTStr)]
public String pszInitialDir; //LPCTSTR
[MarshalAs(UnmanagedType.LPTStr)]
public String pszDefaultFileName; //LPCTSTR
[MarshalAs(UnmanagedType.LPTStr)]
public String pszTitle; //LPCTSTR
public CAMERACAPTURE_STILLQUALITY StillQuality;
public CAMERACAPTURE_VIDEOTYPES VideoTypes;
public uint nResolutionWidth;
public uint nResolutionHeight;
public uint nVideoTimeLimit;
public CAMERACAPTURE_MODE Mode;
}
#endregion //Structures
#region API
[DllImport("Aygshell.dll", SetLastError = true,CharSet=CharSet.Unicode)]
public static extern int SHCameraCapture
(
ref struSHCAMERACAPTURE pshCamCapture
);
private string StartImager(String strImgDir, String strImgFile, uint uintImgHeight,
uint uintImgWidth)
try
{
struSHCAMERACAPTURE shCamCapture = new struSHCAMERACAPTURE();
shCamCapture.cbSize = (uint)Marshal.SizeOf(shCamCapture);
shCamCapture.hwndOwner = IntPtr.Zero;
shCamCapture.szFile = "\\" + strImgFile; //strImgDir + "\\" + strImgFile;
shCamCapture.pszInitialDir = "\\"; // strImgDir;
shCamCapture.pszDefaultFileName = strImgFile;
shCamCapture.pszTitle = "PTT Image Capture";
shCamCapture.StillQuality = 0; // CAMERACAPTURE_STILLQUALITY.CAMERACAPTURE_STILLQUALITY_NORMAL;
shCamCapture.VideoTypes = CAMERACAPTURE_VIDEOTYPES.CAMERACAPTURE_VIDEOTYPE_STANDARD;
shCamCapture.nResolutionHeight = 0; // uintImgHeight;
shCamCapture.nResolutionWidth = 0; // uintImgWidth;
shCamCapture.nVideoTimeLimit = 10;
shCamCapture.Mode = 0; // CAMERACAPTURE_MODE.CAMERACAPTURE_MODE_STILL;
//IntPtr intptrCamCaptr = IntPtr.Zero;
//Marshal.StructureToPtr(shCamCapture, intptrCamCaptr, true);
int intResult = SHCameraCapture(ref shCamCapture);
if (intResult != 0)
{
Win32Exception Win32 = new Win32Exception(intResult);
MessageBox.Show("Error: " + Win32.Message);
}
return strCaptrErr;
}
catch (Exception ex)
{
MessageBox.Show("Error StartImager : " + ex.ToString() + " - " + strCaptrErr
, "Nomad Imager Test");
return "";
}
A: Groky, this is a good start... Thanks for getting this started. I tried wiring this up, but get a NotSupportedException.
I've pasted the text from my test app below. Note that I tried decorating the struct with [StructLayout(LayoutKind.Sequential)]. I've also made all members public to eliminate any issues with object accessability.
public partial class Form1 : Form
{
[DllImport("aygshell.dll")]
static extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);
[StructLayout(LayoutKind.Sequential)]
struct SHCAMERACAPTURE
{
public Int32 cbSize;
public IntPtr hwndOwner;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szFile;
[MarshalAs(UnmanagedType.LPStr)]
public string pszInitialDir;
[MarshalAs(UnmanagedType.LPStr)]
public string pszDefaultFileName;
[MarshalAs(UnmanagedType.LPStr)]
public string pszTitle;
public Int32 StillQuality;
public Int32 VideoTypes;
public Int32 nResolutionWidth;
public Int32 nResolutionHeight;
public Int32 nVideoTimeLimit;
public Int32 Mode;
}
private void ShowCamera()
{
SHCAMERACAPTURE captureData = new SHCAMERACAPTURE
{
cbSize = sizeof (Int64),
hwndOwner = (IntPtr)0,
szFile = "\\My Documents",
pszDefaultFileName = "picture.jpg",
pszTitle = "Camera Demo",
StillQuality = 0,
VideoTypes = 1,
nResolutionWidth = 480,
nResolutionHeight = 640,
nVideoTimeLimit = 0,
Mode = 0
};
SHCameraCapture(ref captureData);
}
private void button1_Click(object sender, EventArgs e)
{
ShowCamera();
}
A: I've not been able to test this, but your struct/function should look something like this:
struct SHCAMERACAPTURE {
public Int32 cbSize;
public IntPtr hwndOwner;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szFile;
[MarshalAs(UnmanagedType.LPStr)]
string pszInitialDir;
[MarshalAs(UnmanagedType.LPStr)]
string pszDefaultFileName;
[MarshalAs(UnmanagedType.LPStr)]
string pszTitle;
Int32 StillQuality;
Int32 VideoTypes;
Int32 nResolutionWidth;
Int32 nResolutionHeight;
Int32 nVideoTimeLimit;
Int32 Mode;
}
[DllImport("aygshell.dll")]
static extern int SHCameraCapture(ref SHCAMERACAPTURE pshcc);
AFAIK, you don't need to explicitly set StructLayout on SHCAMERCAPTURE as there's nothing unusual about its layout.
Once you get this working, you might want to post your findings to pinvoke.net for others to make use of!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flash: Listen to all events of a type with one eventlistener It's not a matter of life or death but I wonder if this could be possible:
I got a couple of events from one type of custom event (FormEvent) now I got a FormListener that listens to all those events and handles them according to the event type. Instead of adding one eventListener at the time I wish to add all events at once.
so now it looks like this:
private function addListeners():void {
addEventListener(FormEvent.SHOW_FORM, formListener);
addEventListener(FormEvent.SEND_FORM, formListener);
addEventListener(FormEvent.CANCEL_FORM, formListener);
}
private function formListener(event:formEvent):void {
switch(event.type){
case "show.form":
// handle show form stuff
break;
case "send.form":
// handle send form stuff
break;
case "cancel.form":
// handle cancel form stuff
break;
}
}
but instead of adding every event one at the time I would rather be doing something like
private function addListeners():void {
addEventListener(FormEvent.*, formListener);
}
I wonder if something like this is possible, i would love it. I work with loads of events :)
A: You only really need one event listener in this case anyhow. That listener will be listening for any change with the form and a parameter equal to what the change was becomes available to the event listener function. I will show you, but please remember that this is a pseudo situation and normally I wouldn't dispatch an event off of something as simple as a method call because the dispatch is implied so there is no real need to listen for it.
First the Custom Event
package com.yourDomain.events
{
import flash.events.Event;
public class FormEvent extends Event
{
//Public Properties
public static const CANCEL_FORM:int = "0";
public static const SHOW_FORM:int = "1";
public static const SEND_FORM:int = "2";
public static const STATE_CHANGED:String = "stateChanged";
//Private Properties
private var formState:int;
public function FormEvent(formState:int):void
{
super(STATE_CHANGED);
formState = formState;
}
}
}
So we have just created our custom event class and we have set it up so that we can catch the state through the listener function as I will demonstrate once done with the pseudo form class that will dispatch the for said custom event.
Remember that this is all hypothetical as I have no idea what your code looks like or how your implementing things. What is important is to notice that when I dispatch the event I need to send a parameter with it that reflects what the new state is.
package com.yourDomain.ui
{
import flash.events.Event;
import flash.events.EventDispatcher;
import com.yourDomain.events.FormEvent;
public class Form extends EventDispatcher
{
public function Form():void
{
//Anything you want form to do upon instantiation goes here.
}
public function cancelForm():void
{
dispatchEvent(new Event(FormEvent.CANCEL_FORM);
}
public function showForm():void
{
dispatchEvent(new Event(FormEvent.SHOW_FORM);
}
public function sendForm():void
{
dispatchEvent(new Event(FormEvent.SEND_FORM);
}
}
}
And finally we create the document class that will listen for it. Please know that I realize it isn't logical to create a listener that fires when you call a method of a class because you obviously know you called the method, but for this example it will due.
package com.yourDomain.ui
{
import com.yourDomain.ui.Form;
import com.yourDomain.events.FormEvent;
//Form is in the same package so we need not import it.
public class MainDocumentClass
{
private var _theForm:Form;
public function MainDocumentClass():void
{
_theForm = new Form();
_theForm.addEventListener(FormEvent.STATE_CHANGED, onFormStateChange, false, 0, true);
/*
The following three method calls each cause the
FormEvent.STATE_CHANGE event to be dispatched.
onFormStateChange is notified and checks what
the last change actually was.
*/
_theForm.cancelForm();
_theForm.showForm();
_theForm.sendForm();
}
private function onFormStateChange(e:FormEvent):void
{
switch(e.formState)
{
case CANCEL_FORM:
trace('The form was canceled');
break;
case SHOW_FORM:
trace('The form was revealed');
break;
case SEND_FORM:
trace('The form was sent');
break;
}
}
}
}
I hope that this was helpful, its late and I may have to revise some things later, but this should help get an understanding of how to make your own events and to customize how things work.
A: I don't know of any routines that let you do that directly, but you could write your own. The syntax here won't be perfect, but here's a first pass:
private function addMultipleEventListeners( evts:Array, callback:function ):void
{
for each( var evt:Event in evts )
{
addEventListener( evt, callback );
}
}
You could then call that routine like so:
var evts:Array = [ FormEvent.SHOW_FORM, FormEvent.SEND_FORM, FormEvent.CANCEL_FORM ];
addMultipleEventListeners( evts, formListener );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Encrypting Source Code I work on relatively sensitive code that we wouldn't want falling into the wrong hands. Up until now, all the code has been keep in house so it hasn't been an issue. I am moving to working from home a day or two a week and we want to secure the code on my laptop.
We have looked at a few alternatives, but Windows EFS and Bitlocker seem to be the most obvious. The laptop doesn't have TPM hardware, and I won't have access to Active Directory from home, so EFS looks to be the option.
Basically, does anyone else have any alternatives, or issues with using EFS to encrypt source code?
A: Truecrypt:
WARNING: Using TrueCrypt is not secure as it may contain unfixed security issues
This page exists only to help migrate existing data encrypted by TrueCrypt.
The development of TrueCrypt was ended in 5/2014 after Microsoft terminated support of Windows XP. Windows 8/7/Vista and later offer integrated support for encrypted disks and virtual disk images. Such integrated support is also available on other platforms (click here for more information). You should migrate any data encrypted by TrueCrypt to encrypted disks or virtual disk images supported on your platform...
A: You should look into TrueCrypt. It's free, open source and supported on a number of platforms.
A: I would also recommend Truecrypt
A: The last time I did this was a few years ago, but we used PGPdisk. It did a good job.
A: You should consider using truecrypt. It would accomplish the same thing, and be a bit less invasive to your system.
A: TrueCrypt, there's no excuse to use anything different. It's secure and it's free...what more could you want.
A: +1 for TrueCrypt. We use it at work, it's great.
Tip: it seems that if you have a big codebase and you work with multiple working copies checked out simultaneously, you get much better performance if each working copy is on its own encrypted partition.
A: You MAY want to encrypt PARTS of the data instead of all of it for speed and simplification issues, however, using a windows encrypted volume would be fairly easy as well. Don't forget that if you must encrypt the entire source, then remember that you're best off encrypting the entire development machine, not just a single volume as temp files or swap files may contain the decrypted information.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Can PHP's SQL Server driver return SQL return codes? Stored procs in SQL Server sometimes finish with a return code, as opposed to a recordset of data. I've seen ASP code that's able to get this return code, but I can't figure out how to get this code with PHP's mssql driver.
mssql_get_last_message() always returns nothing, and I'm thinking it's because it only returns the very last line that came from the server. When we run the proc in another application (outside PHP), there is blank line following the return code.
Has anyone figured out how to get return codes from SQL stored procs using PHP's mssql driver?
A: Are you talking about SQL Server error codes, e.g. RAISERRROR or other failures? If so, last time I checked in PHP you need to ask for @@ERROR (e.g. select @@error) instead.
If it is a return code, you must explicitly catch it, e.g.
DECLARE @return_code INT
EXEC @return_code = your_stored_procedure 1123
SELECT @return_code
A: To get a numeric error code from mssql you can do a select that looks something like
SELECT @@ERROR AS ErrorCode
Which SHOULD return the correct error code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to convert Cardinal numbers into Ordinal ones Is there an easy way to convert the number 1, 2, 3, ... to "1st", "2nd", "3rd", ..., and in such a way that I can give the function a language and have it return me the correct form for the language I'm targeting? Either standard C++ (stl or boost OK), MFC or ATL, win32 api or a small, single-purpose and free library that I can download from somewhere. Thanks.
A: I doubt whether it is possible at all, since in many languages this form will depend on the context, like gender or case of the noun it describes and different languages will require different kind of context information to allow to determine the correct form.
EDIT: E.g. in Polish it is "5-ta klasa" (5th class) vs. "5-ty miesiąc" (5th month) vs. "w 5-tym miesiącu" (in the 5th month).
A: I've spend quite some time researching this, because it's too large a project to get right myself. It looks like the ICU library is the only one that provides this functionality in a somewhat comprehensive way (http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html). I'm not too keen on incorporating a huge library like that, though. I'll keep on looking and I'm still open to suggestions.
A: Did you look up the CLDR repository on the Unicode site? I don't know if they have this kind of thing but since it's probably the most comprehensive locale data repository out there, it's probably worth a look.
http://www.unicode.org/cldr/
A: Since you use C++, I assume you could use GNU gettext (there's a Windows port as well) for all the translations, or at least get the idea how they solved it. Here's the relevant manual page on plural forms that explains the problem (which you already found, but in more detail) and their solution:
http://www.gnu.org/software/automake/manual/gettext/Plural-forms.html
A: Here is the piece of code on CodeProject that does the job. Haven't tried it on my own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Is there a tool to discover if the same class exists in multiple jars in the classpath? If you have two jars in your classpath that contain different versions of the same class, the classpath order becomes critical.
I am looking for a tool that can detect and flag such potential conflicts in a given classpath or set of folders.
Certainly a script that starts:
classes=`mktemp`
for i in `find . -name "*.jar"`
do
echo "File: $i" > $classes
jar tf $i > $classes
...
done
with some clever sort/uniq/diff/grep/awk later on has potential, but I was wondering if anyone knows of any existing solutions.
A: Looks like jarfish will do what you want with its "dupes" command.
A: The Tattletale tool from JBoss is another candidate: "Spot if a class/package is located in multiple JAR files"
A: Classpath Helper is an Eclipse plug-in that helps a little bit.
A: I think it wouldn't be too hard to write a tool for your self.
You can get the classpath entries with System.getProperty("java.class.path");
And then walk through the jars, zips, or directories listed there and collect all the information about the classes and findout those that might cause trouble.
This task would take 1 or 2 days at most. Then you can load this class directly in your application and generate a report.
Probably java.class.path property wont's show all the classes if you run in some infrastructure with complex custom class loading ( for instance I once saw an app that load the classes from the LDAP ) but it would certainly work for most of the cases.
Heres a tool you might find useful, I've never use it my self, but give it a try and let us know the result.
http://www.jgoodies.com/freeware/jpathreport/features.html
If you are going to create your own tool, here is the code I use for the same shell script posted before, but that I use on my Windows machine. It runs faster when there are tons of jar files.
You can use it and modify it so instead of recursively walk a directory, read the class path and compare the .class time attribute.
There is a Command class you can subclass if needed, I was thinking in the -execute option of "find"
This my own code, so it was not intended to be "production ready", just to do the work.
import java.io.*;
import java.util.zip.*;
public class ListZipContent{
public static void main( String [] args ) throws IOException {
System.out.println( "start " + new java.util.Date() );
String pattern = args.length == 1 ? args[0] : "OracleDriver.class";// Guess which class I was looking for :)
File file = new File(".");
FileFilter fileFilter = new FileFilter(){
public boolean accept( File file ){
return file.isDirectory() || file.getName().endsWith( "jar" );
}
};
Command command = new Command( pattern );
executeRecursively( command, file, fileFilter );
System.out.println( "finish " + new java.util.Date() );
}
private static void executeRecursively( Command command, File dir , FileFilter filter ) throws IOException {
if( !dir.isDirectory() ){
System.out.println( "not a directory " + dir );
return;
}
for( File file : dir.listFiles( filter ) ){
if( file.isDirectory()){
executeRecursively( command,file , filter );
}else{
command.executeOn( file );
}
}
}
}
class Command {
private String pattern;
public Command( String pattern ){
this.pattern = pattern;
}
public void executeOn( File file ) throws IOException {
if( pattern == null ) {
System.out.println( "Pattern is null ");
return;
}
String fileName = file.getName();
boolean jarNameAlreadyPrinted = false;
ZipInputStream zis = null;
try{
zis = new ZipInputStream( new FileInputStream( file ) );
ZipEntry ze;
while(( ze = zis.getNextEntry() ) != null ) {
if( ze.getName().endsWith( pattern )){
if( !jarNameAlreadyPrinted ){
System.out.println("Contents of: " + file.getCanonicalPath() );
jarNameAlreadyPrinted = true;
}
System.out.println( " " + ze.getName() );
}
zis.closeEntry();
}
}finally{
if( zis != null ) try {
zis.close();
}catch( Throwable t ){}
}
}
}
I hope this helps.
A: If you dislike downloading and installing stuff you can use this one line command to find jar conflicts with standard gnu tools. It is rudimentary but you can expand it as you will.
ls *.jar | xargs -n1 -iFILE unzip -l FILE | grep class | sed "s,.* ,," | tr "/" "." | sort | uniq -d | xargs -n1 -iCLASS grep -l CLASS *.jar | sort -u
(it is a bit slow to run if you have a lot of jars)
Explanation:
It lists all the files in all the jars, greps for class files, finds dupes, then greps the original jars to see where they appeared. It could be made more efficient with a more complicated script.
A: jarclassfinder is another eclipse plugin option
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Is it possible to define a Ruby singleton method using a block? So, I want to define a singleton method for an object, but I want to do it using a closure.
For example,
def define_say(obj, msg)
def obj.say
puts msg
end
end
o = Object.new
define_say o, "hello world!"
o.say
This doesn't work because defining a singleton method via "def" is not a closure, so I get an exception that "msg" is an undefined variable or method.
What I would like to do is something like using the "define_method" method in the Module class, but as far as I can tell, this can only be used to define a method on a class... but I want a Singleton Method...
So, I would love to write it something like this:
def define_say(obj, msg)
obj.define_singleton_method(:say) {
puts msg
}
end
Does anyone know how I can achieve this without having to create a method to store a Proc and then use the Proc within a singleton method? (basically, I want a clean, non-hacky way of doing this)
A: Here's an answer which does what you're looking for
def define_say(obj, msg)
# Get a handle to the singleton class of obj
metaclass = class << obj; self; end
# add the method using define_method instead of def x.say so we can use a closure
metaclass.send :define_method, :say do
puts msg
end
end
Usage (paste from IRB)
>> s = "my string"
=> "my string"
>> define_say(s, "I am S")
=> #<Proc:0xb6ed55b0@(irb):11>
>> s.say
I am S
=> nil
For more info (and a little library which makes it less messy) read this:
http://viewsourcecode.org/why/hacking/seeingMetaclassesClearly.html
As an aside, If you're a ruby programmer, and you HAVEN'T read that, go do it now~!
A: Object#define_singleton_method was added to ruby-1.9.2 by the way:
def define_say(obj, msg)
obj.define_singleton_method(:say) do
puts msg
end
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/135995",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Comet and jQuery I've done some research into server push with javascript and have found the general consensus to be that what I'm looking for lies in the "Comet" design pattern. Are there any good implementations of this pattern built on top of jQuery? If not, are there any good implementations of this pattern at all? And regardless of the answer to those questions, is there any documentation on this pattern from an implementation stand-point?
A: Check out the Ape Project for a complete client and server side solution that implements the comet pattern.
A: I wrote the plugin mentioned by Till. The plugin is an implementation of the Bayeux protocol and currently supports long-polling (local server via AJAX) and callback-polling (remote server via XSS). There is a Bayeux implementation for Python called cometd-twisted that I have heard my plugin works with, but I have not verified this. I have tested and verified it works with cometd-jetty and erlycomet which has a jQuery Comet example included. There is more info on my blog and the current code with a basic chat example can be found on its google code page. Hope this info is helpful and feel free to contact me if need any further help with the plugin.
A: A description of the pattern: http://ajaxpatterns.org/HTTP_Streaming
A: Comet is a great solution, and there are all kinds of implementations. Which one depends on your needs.
We've implemented a solution for IIS/ASP.NET, WebSync. It includes the javascript client, which plays nicely with jQuery. Technically, since it's the Bayeux protocol, any Bayeux client should work just dandy. The same protocol can also be found in the dojo library.
For more detail, you can see the spec for the Bayeux protocol.
A: I have a very simple example here that can get you started with comet. It covers compiling Nginx with the NHPM module and includes code for simple publisher/subscriber roles in jQuery, PHP, and Bash.
http://blog.jamieisaacs.com/2010/08/27/comet-with-nginx-and-jquery/
A working example (simple chat) can be found here:
http://cheetah.jamieisaacs.com/
A: Look at socket.io. Trust me. This is exactly what the doctor ordered.
http://socket.io
Stream data with Node.js
A: If you're using JQuery, I'd recommend jquery-stream. I'm currently using jquery-stream on a project and so far its been reliable, well-documented and has an active Google code project.
http://code.google.com/p/jquery-stream/
A: Someone built a client for Comet using jQuery. I don't know if it's any good though. I've read about Comet and heard about all the good it can do, but I have never gotten around to using it. Just had no time and no use case on any of my current projects.
I totally forgot to add a link as for implementing comet.
There is Comet Daily and they have a comparison online. The comparison emphasizes on maturity of the different implementation. It's pretty interesting and should get you started.
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "114"
}
|
Q: Quickbooks 2005 Web Integration A customer of ours has Quickbooks 2005 and is looking to have their web data (orders, customers, tax) sent as it is collected from the web in a format that can be imported into Quickbooks 2005 Pro.
Does anyone have any experience with this? If so, what was your experience, and what component/method would you recommend for importing this data into Quickbooks?
A: Have a look at the QuickBooks Web Connector.
There is a similar question:
https://stackoverflow.com/questions/9331/integrating-quickbooks-with-your-e-commerce-site
A: The QuickBooks Web Connector is almost certainly the only way to go for integrating websites with QuickBooks.
Here is a wiki with some additional information:
http://www.consolibyte.com/wiki/doku.php/quickbooks
You'll also want to see the QuickBooks OSR:
http://developer.intuit.com/qbSDK-Current/Common/newOSR/index.html
And the QuickBooks SDK:
http://developer.intuit.com/
PHP specific framework:
http://idnforums.intuit.com/messageview.aspx?catid=56&threadid=9164
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Assembly.Load and Environment.CurrentDirectory I realize there is a somewhat related thread on this here:
Loading assemblies and its dependencies
But I am modifying something and this doesn't exactly apply.
string path = Path.GetDirectoryName( pathOfAssembly );
Environment.CurrentDirectory = path;
Assembly.Load(Path.GetFileNameWithoutExtension(pastOfAssembly));
Is there any really reason you would do it like this? Wouldn't it make more sense to just use:
Assembly.LoadFile(pathOfAssembly);
Any insight would be greatly appreciated.
A: Looks like the "Department of Redundancy Department."
A lot more code than is necessary. Less is more!
Edit: On second thought, it could be that the assembly you are loading has dependencies that live in its own folder that may be required to use the first assembly.
A: This can be necessary when you are developping a windows service. The working dir of a service defaults to %WinDir%, so if you want to load an assembly from the dir that your service exe resides in, this is the way to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I get PHP's (deployment) simplicity but Perl's power? I despise the PHP language, and I'm quite certain that I'm not alone. But the great thing about PHP is the way that mod_php takes and hides the gory details of integrating with the apache runtime, and achieves CGI-like request isolation and decent performance.
What's the shortest-distance approach to getting the same simplicity, speed and isolation as PHP's runtime environment, with Perl semantics? I feel like raw mod_perl gives me too much rope to hang myself with: cross-request globals, messy config, too many template engines to choose from.
FastCGI? HTML::Mason? I'd like to do development largely in Perl, if only I had a framework that let me.
A: I just saw Dancer. Looks like this might be a good option.
A: I'd recommend Catalyst with FastCGI. Also, for templating, Template::Toolkit is my personal favorite, but HTML::Mason is also highly regarded in the community.
A: The closest, well-regarded equivalent to PHP in Perl is probably HTML::Mason.
Like PHP, it embeds Perl into your document and renders it:
% my $noun = 'World';
Hello <% $noun %>!
How are ya?
The O'Reilly book Embedding Perl in HTML with Mason is available online for free.
A: There are a lot of possibilities, depending on what you want to do.
If you want to take advantage of the speed of mod_perl, but the simplicity of vanilla CGI, check out the Modperl::Registry distribution from CPAN. This will allow you to run your plain CGI scripts largely unaltered.
In terms of frameworks, I'm a big fan of CGI::Application. It provides a very simple inheritance-based framework that handles most everything a web application will need to do, giving you the freedom to design your application the way you like. A simple app can be done in a monolithic fashion; a more complex one can use a full-fledged MVC design. Like Perl in general, CGI-App gives you a lot of options and generally stays out of your way.
CGI-App supports the excellent HTML::Template module by default, and has plugins for other templating systems such as the spectacular Template Toolkit. There are also a plethora of plugins for other purposes.
If you want more work done for you, check out Catalyst. This way of doing things may be more familiar if you've used Ruby on Rails.
Other popular web-app frameworks include Jifty and CGI::Prototype, written by Randal Schwartz, which is based on the Class::Prototyped object framework.
A: The aforementioned Catalyst is a fine tool for constructing entire web applications, but it is by no means anywhere near simple. The primary strength of PHP is that you can embed small chunks of it as needed in otherwise static pages, i.e. you can do:
<html>
<body>
<p>The value of 2+2 is: <?php echo 2+2; ?></p>
</body></html>
and see on your web browser:
The value of 2+2 is: 4
If you try to do something like this with Catalyst (as far as I know), you're developing an entire application with multiple files to print a simple value. At least, there's no explanation of how to do simple embedding in the tutorials that I saw.
Fortunately, this level of simplicity can be reached with Mason, which in some ways (thanks to the power of Perl) can be even simpler. The above example reads:
<html><body><p>The value of 2+2 is: <% 2+2 %></p></body></html>
and you get the same result.
There's no reason you can't start by installing and working with Mason and then install Catalyst side by side with it, however, if you plan to move to very complex, purely Perl-driven projects later, though.
A: I wonder what became of mod_perlite, which was going to provide exactly what you are after.
A: Stuff like Catalyst and CGI::Application are more equivalents of Zend Framework rather than PHP itself. In order to replicate the basic functionality for creating web pages that PHP offers "out the box" then you need two CPAN modules that should be available in every base Perl installation:
use CGI;
use DBI;
Is all you really need. Now instead of:
$_POST['param']
$_GET['param']
you have:
my $q = new CGI;
$q->param('param'); # same for post or get
And instead of:
$dbh = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$sth = mysql_query("SELECT 1 FROM table", $dbh);
while($row = mysql_fetch_assoc($sth))
{
// do something with $row
}
You have:
my $dbh = DBI->connect('DBI:mysql:host=localhost;', 'mysql_user', 'mysql_password');
my $sth = $dbh->prepare("SELECT 1 FROM table");
$sth->execute();
while(my $row = $sth->fetchrow_hashref)
{
# do stuff with row
}
The DBI code is slightly more complicated because it offers prepared statments and bound variables so that you don't need to worry about SQL injections. PHP doesn't offer this so you need to use something like PDO or write your own database class.
The only thing left is if you wanted HTML output in a script. But you don't want that do you? You use HTML::Template or Template::Toolkit for that, the same way you should be using Smarty or native templates in PHP.
A: If Mojolicious had existed when I asked this question, I doubt I would have asked it.
Specifically, Mojolicious::Lite
A: Look at Catalyst this MVC (model, view, controller) framework works stand-a-lone or with apache_perl and hides a lot of the messy bits. There is a slightly odd learning curve (quick start, slower middle, then it really clicks for advanced stuff).
Catalyst allows you to use Template Toolkit to separate the design logic from the business logic, Template toolkit really is great, even if you decide not to use Catalyst then you should be using this. HTML::Mason isn't something I personally like, although if you do all the HTML yourself then you might want to review Template::Declare which is another alternative you can also use with Catalyst.
For database stuff look at DBIx::Class, which yet again works with Catalyst or on it's own.
A: I agree with Aristotle. mod_perlite sounds like just what you are looking for, if only it was finished.
A: The closest to PHP in terms of simplicity is HTML::Mason.
Suggesting Catalyst is a bad joke for someone who is looking for simplicity... And I'm happily working with Catalyst every single day now.
A: I've worked with HTML::Mason, first hacking RT and then creating two sites with it. There's a learning curve, but it's not too bad. Worse, I think, is installing the thing, but that has much more to do with Apache and mod_perl than Mason. Once the pieces are in place, it's only as complicated as you make it (like Perl itself).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Pass and return custom array object in ibatis and oracle in java I've looked around for a good example of this, but I haven't run into one yet. I want to pass a custom string array from java to oracle and back, using the IBATIS framework. Does anyone have a good link to an example? I'm calling stored procs from IBATIS.
Thanks
A: You've got to start with a custom instance of TypeHandler. We'd prefer to implement the simpler TypeHandlerCallback, but in this scenario we need access to the underlying Connection.
public class ArrayTypeHandler implements TypeHandler {
public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType)
throws SQLException {
if (param == null) {
ps.setNull(i, Types.ARRAY);
} else {
Connection conn = ps.getConnection();
Array loc = conn.createArrayOf("myArrayType", (Object[]) param);
ps.setArray(i, loc);
}
}
public Object getResult(CallableStatement statement, int i)
throws SQLException {
return statement.getArray(i).getArray();
}
...
}
Then, to wire it up in the iBATIS config:
<?xml version="1.0"?>
<!DOCTYPE sqlMap PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="arrayTest">
<parameterMap id="storedprocParams" class="map">
<parameter property="result" mode="OUT" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
<parameter property="argument" mode="IN" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
</parameterMap>
<procedure id="storedproc" parameterMap="arrayTest.storedprocParams">
{? = call My_Array_Function( ? )}
</procedure>
</sqlMap>
Hope this helps!
A: bsanders gave me a good starting point - here's what I had to do to make it work within the RAD environment (websphere 6.2).
public Object getResult(CallableStatement statement, int i) throws SQLException {
return statement.getArray(i).getArray(); //getting null pointer exception here
}
public void setParameter(PreparedStatement ps, int i, Object param, String jdbcType) throws SQLException {
if (param == null) {
ps.setNull(i, Types.ARRAY);
} else {
String[] a = (String[]) param;
//ARRAY aOracle = ARRAY.toARRAY(a, (OracleConnection)ps.getConnection());
//com.ibm.ws.rsadapter.jdbc.WSJdbcConnection
w = (com.ibm.ws.rsadapter.jdbc.WSJdbcConnection)ps.getConnection());
//com.ibm.ws.rsadapter.jdbc.WSJdbcObject x;
Connection nativeConnection = Connection)WSJdbcUtil.getNativeConnection((WSJdbcConnection)ps.getConnection());
ArrayDescriptor descriptor = ArrayDescriptor.createDescriptor("F2_LIST", nativeConnection);
ARRAY dataArray = new ARRAY(descriptor, nativeConnection, a);
ps.setArray(i, dataArray);
}
}
Notice the nativeConnection I had to get, the descriptor I had to make, and so on. However, while I can pass things into the database as an array of Strings, I haven't been able to figure out why I'm not getting anything back. My OUT parameter (the getResult(CallableStatement statment, int i) is throwing a null pointer exception, even though I'm setting the out parameter in the plsql in the database.
--stored procedure to take a | delimited ids
PROCEDURE array_test (argument IN f2_list, result OUT f2_list)
AS
l_procname_v VARCHAR2 (50) := 'array_test';
l_param_list VARCHAR2 (2000)
:= l_procname_v || ' param_values: p_string: ';
p_status_n NUMBER;
p_message_v VARCHAR2 (2000);
ret_list f2_list := new f2_list();
l_count_v varchar2(200);
BEGIN
l_count_v := argument.COUNT;
for x in 1..argument.count
LOOP
pkg_az_common_util.az_debug (package_nm,
l_procname_v,
pkg_az_data_type_def.debug_num,
argument(x)
);
end loop;
pkg_az_common_util.az_debug (package_nm,
l_procname_v,
pkg_az_data_type_def.debug_num,
l_count_v
);
ret_list.extend();
ret_list(1) := 'W';
ret_list.extend();
ret_list(2) := 'X';
ret_list.extend();
ret_list(3) := 'Y';
ret_list.extend();
ret_list(4) := 'Z';
result := ret_list;
EXCEPTION
WHEN OTHERS
THEN
p_status_n := pkg_az_common_util.get_error_code;
p_message_v :=
TO_CHAR (p_status_n)
|| '|'
|| 'Oracle Internal Exception('
|| l_procname_v
|| ')'
|| '|'
|| TO_CHAR (SQLCODE)
|| '|'
|| SQLERRM
|| l_param_list;
standard_pkg.log_error (package_nm,
l_procname_v,
SQLCODE,
p_message_v
);
IF p_status_n = 1
THEN
RAISE;
END IF;
END array_test;
Here is how I'm accessing it:
Map queryParamsTest = new HashMap();
String[] testArray = {"A", "B", "C"};
queryParamsTest.put("argument", testArray);
DaoUtils.executeQuery(super.getSqlMapClientTemplate(),
"arrayTest", queryParamsTest, queryParamsTest
.toString()); //just executes query
String[] resultArray = (String[])queryParamsTest.get("result");
for(int x = 0; x< resultArray.length; x++)
{
System.out.println("Result: " + resultArray[x]);
}
<parameterMap id="storedprocParams" class="map">
<parameter property="argument" mode="IN" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
<parameter property="result" mode="OUT" jdbcType="ARRAY" typeHandler="ArrayTypeHandler"/>
</parameterMap>
<procedure id="arrayTest" parameterMap="storedprocParams">
{call pkg_az_basic_dev.array_test(?, ? )}
</procedure>
Any ideas?
A: Well, guys in company found out the solution: you need to have implemented getResult method(s) in your typeHandler and provided additional attribute jdbcTypeName=ORACLE_REAL_ARRAY_TYPE in your mapper
A: Try using statement.getObject(i) and then casting to an array.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Catch multiple exceptions at once? It is discouraged to simply catch System.Exception. Instead, only the "known" exceptions should be caught.
Now, this sometimes leads to unnecessary repetitive code, for example:
try
{
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
WebId = Guid.Empty;
}
catch (OverflowException)
{
WebId = Guid.Empty;
}
I wonder: Is there a way to catch both exceptions and only call the WebId = Guid.Empty call once?
The given example is rather simple, as it's only a GUID. But imagine code where you modify an object multiple times, and if one of the manipulations fails expectedly, you want to "reset" the object. However, if there is an unexpected exception, I still want to throw that higher.
A: If you can upgrade your application to C# 6 you are lucky. The new C# version has implemented Exception filters. So you can write this:
catch (Exception ex) when (ex is FormatException || ex is OverflowException) {
WebId = Guid.Empty;
}
Some people think this code is the same as
catch (Exception ex) {
if (ex is FormatException || ex is OverflowException) {
WebId = Guid.Empty;
}
throw;
}
But it´s not. Actually this is the only new feature in C# 6 that is not possible to emulate in prior versions. First, a re-throw means more overhead than skipping the catch. Second, it is not semantically equivalent. The new feature preserves the stack intact when you are debugging your code. Without this feature the crash dump is less useful or even useless.
See a discussion about this on CodePlexNot available anymore. And an example showing the difference.
A: Note that I did find one way to do it, but this looks more like material for The Daily WTF:
catch (Exception ex)
{
switch (ex.GetType().Name)
{
case "System.FormatException":
case "System.OverflowException":
WebId = Guid.Empty;
break;
default:
throw;
}
}
A: EDIT: I do concur with others who are saying that, as of C# 6.0, exception filters are now a perfectly fine way to go: catch (Exception ex) when (ex is ... || ex is ... )
Except that I still kind of hate the one-long-line layout and would personally lay the code out like the following. I think this is as functional as it is aesthetic, since I believe it improves comprehension. Some may disagree:
catch (Exception ex) when (
ex is ...
|| ex is ...
|| ex is ...
)
ORIGINAL:
I know I'm a little late to the party here, but holy smoke...
Cutting straight to the chase, this kind of duplicates an earlier answer, but if you really want to perform a common action for several exception types and keep the whole thing neat and tidy within the scope of the one method, why not just use a lambda/closure/inline function to do something like the following? I mean, chances are pretty good that you'll end up realizing that you just want to make that closure a separate method that you can utilize all over the place. But then it will be super easy to do that without actually changing the rest of the code structurally. Right?
private void TestMethod ()
{
Action<Exception> errorHandler = ( ex ) => {
// write to a log, whatever...
};
try
{
// try some stuff
}
catch ( FormatException ex ) { errorHandler ( ex ); }
catch ( OverflowException ex ) { errorHandler ( ex ); }
catch ( ArgumentNullException ex ) { errorHandler ( ex ); }
}
I can't help but wonder (warning: a little irony/sarcasm ahead) why on earth go to all this effort to basically just replace the following:
try
{
// try some stuff
}
catch( FormatException ex ){}
catch( OverflowException ex ){}
catch( ArgumentNullException ex ){}
...with some crazy variation of this next code smell, I mean example, only to pretend that you're saving a few keystrokes.
// sorta sucks, let's be honest...
try
{
// try some stuff
}
catch( Exception ex )
{
if (ex is FormatException ||
ex is OverflowException ||
ex is ArgumentNullException)
{
// write to a log, whatever...
return;
}
throw;
}
Because it certainly isn't automatically more readable.
Granted, I left the three identical instances of /* write to a log, whatever... */ return; out of the first example.
But that's sort of my point. Y'all have heard of functions/methods, right? Seriously. Write a common ErrorHandler function and, like, call it from each catch block.
If you ask me, the second example (with the if and is keywords) is both significantly less readable, and simultaneously significantly more error-prone during the maintenance phase of your project.
The maintenance phase, for anyone who might be relatively new to programming, is going to compose 98.7% or more of the overall lifetime of your project, and the poor schmuck doing the maintenance is almost certainly going to be someone other than you. And there is a very good chance they will spend 50% of their time on the job cursing your name.
And of course FxCop barks at you and so you have to also add an attribute to your code that has precisely zip to do with the running program, and is only there to tell FxCop to ignore an issue that in 99.9% of cases it is totally correct in flagging. And, sorry, I might be mistaken, but doesn't that "ignore" attribute end up actually compiled into your app?
Would putting the entire if test on one line make it more readable? I don't think so. I mean, I did have another programmer vehemently argue once long ago that putting more code on one line would make it "run faster." But of course he was stark raving nuts. Trying to explain to him (with a straight face--which was challenging) how the interpreter or compiler would break that long line apart into discrete one-instruction-per-line statements--essentially identical to the result if he had gone ahead and just made the code readable instead of trying to out-clever the compiler--had no effect on him whatsoever. But I digress.
How much less readable does this get when you add three more exception types, a month or two from now? (Answer: it gets a lot less readable).
One of the major points, really, is that most of the point of formatting the textual source code that we're all looking at every day is to make it really, really obvious to other human beings what is actually happening when the code runs. Because the compiler turns the source code into something totally different and couldn't care less about your code formatting style. So all-on-one-line totally sucks, too.
Just saying...
// super sucks...
catch( Exception ex )
{
if ( ex is FormatException || ex is OverflowException || ex is ArgumentNullException )
{
// write to a log, whatever...
return;
}
throw;
}
A: Since I felt like these answers just touched the surface, I attempted to dig a bit deeper.
So what we would really want to do is something that doesn't compile, say:
// Won't compile... damn
public static void Main()
{
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException)
catch (IndexOutOfRangeException)
{
// ... handle
}
The reason we want this is because we don't want the exception handler to catch things that we need later on in the process. Sure, we can catch an Exception and check with an 'if' what to do, but let's be honest, we don't really want that. (FxCop, debugger issues, uglyness)
So why won't this code compile - and how can we hack it in such a way that it will?
If we look at the code, what we really would like to do is forward the call. However, according to the MS Partition II, IL exception handler blocks won't work like this, which in this case makes sense because that would imply that the 'exception' object can have different types.
Or to write it in code, we ask the compiler to do something like this (well it's not entirely correct, but it's the closest possible thing I guess):
// Won't compile... damn
try
{
throw new ArgumentOutOfRangeException();
}
catch (ArgumentOutOfRangeException e) {
goto theOtherHandler;
}
catch (IndexOutOfRangeException e) {
theOtherHandler:
Console.WriteLine("Handle!");
}
The reason that this won't compile is quite obvious: what type and value would the '$exception' object have (which are here stored in the variables 'e')? The way we want the compiler to handle this is to note that the common base type of both exceptions is 'Exception', use that for a variable to contain both exceptions, and then handle only the two exceptions that are caught. The way this is implemented in IL is as 'filter', which is available in VB.Net.
To make it work in C#, we need a temporary variable with the correct 'Exception' base type. To control the flow of the code, we can add some branches. Here goes:
Exception ex;
try
{
throw new ArgumentException(); // for demo purposes; won't be caught.
goto noCatch;
}
catch (ArgumentOutOfRangeException e) {
ex = e;
}
catch (IndexOutOfRangeException e) {
ex = e;
}
Console.WriteLine("Handle the exception 'ex' here :-)");
// throw ex ?
noCatch:
Console.WriteLine("We're done with the exception handling.");
The obvious disadvantages for this are that we cannot re-throw properly, and -well let's be honest- that it's quite the ugly solution. The uglyness can be fixed a bit by performing branch elimination, which makes the solution slightly better:
Exception ex = null;
try
{
throw new ArgumentException();
}
catch (ArgumentOutOfRangeException e)
{
ex = e;
}
catch (IndexOutOfRangeException e)
{
ex = e;
}
if (ex != null)
{
Console.WriteLine("Handle the exception here :-)");
}
That leaves just the 're-throw'. For this to work, we need to be able to perform the handling inside the 'catch' block - and the only way to make this work is by an catching 'Exception' object.
At this point, we can add a separate function that handles the different types of Exceptions using overload resolution, or to handle the Exception. Both have disadvantages. To start, here's the way to do it with a helper function:
private static bool Handle(Exception e)
{
Console.WriteLine("Handle the exception here :-)");
return true; // false will re-throw;
}
public static void Main()
{
try
{
throw new OutOfMemoryException();
}
catch (ArgumentException e)
{
if (!Handle(e)) { throw; }
}
catch (IndexOutOfRangeException e)
{
if (!Handle(e)) { throw; }
}
Console.WriteLine("We're done with the exception handling.");
And the other solution is to catch the Exception object and handle it accordingly. The most literal translation for this, based on the context above is this:
try
{
throw new ArgumentException();
}
catch (Exception e)
{
Exception ex = (Exception)(e as ArgumentException) ?? (e as IndexOutOfRangeException);
if (ex != null)
{
Console.WriteLine("Handle the exception here :-)");
// throw ?
}
else
{
throw;
}
}
So to conclude:
*
*If we don't want to re-throw, we might consider catching the right exceptions, and storing them in a temporary.
*If the handler is simple, and we want to re-use code, the best solution is probably to introduce a helper function.
*If we want to re-throw, we have no choice but to put the code in a 'Exception' catch handler, which will break FxCop and your debugger's uncaught exceptions.
A: This is a classic problem every C# developer faces eventually.
Let me break your question into 2 questions. The first,
Can I catch multiple exceptions at once?
In short, no.
Which leads to the next question,
How do I avoid writing duplicate code given that I can't catch multiple exception types in the same catch() block?
Given your specific sample, where the fall-back value is cheap to construct, I like to follow these steps:
*
*Initialize WebId to the fall-back value.
*Construct a new Guid in a temporary variable.
*Set WebId to the fully constructed temporary variable. Make this the final statement of the try{} block.
So the code looks like:
try
{
WebId = Guid.Empty;
Guid newGuid = new Guid(queryString["web"]);
// More initialization code goes here like
// newGuid.x = y;
WebId = newGuid;
}
catch (FormatException) {}
catch (OverflowException) {}
If any exception is thrown, then WebId is never set to the half-constructed value, and remains Guid.Empty.
If constructing the fall-back value is expensive, and resetting a value is much cheaper, then I would move the reset code into its own function:
try
{
WebId = new Guid(queryString["web"]);
// More initialization code goes here.
}
catch (FormatException) {
Reset(WebId);
}
catch (OverflowException) {
Reset(WebId);
}
A: So you´re repeating lots of code within every exception-switch? Sounds like extracting a method would be god idea, doesn´t it?
So your code comes down to this:
MyClass instance;
try { instance = ... }
catch(Exception1 e) { Reset(instance); }
catch(Exception2 e) { Reset(instance); }
catch(Exception) { throw; }
void Reset(MyClass instance) { /* reset the state of the instance */ }
I wonder why no-one noticed that code-duplication.
From C#6 you furthermore have the exception-filters as already mentioned by others. So you can modify the code above to this:
try { ... }
catch(Exception e) when(e is Exception1 || e is Exception2)
{
Reset(instance);
}
A: Update for C# 9
Using the new pattern matching enhancements made in C# 9, you can shorten the expression in the exception filter. Now, catching multiple exceptions is a simple is this:
try
{
WebId = new Guid(queryString["web"]);
}
catch (Exception e) when (e is FormatException or OverflowException)
{
WebId = Guid.Empty;
}
A: With C# 7 the answer from Michael Stum can be improved while keeping the readability of a switch statement:
catch (Exception ex)
{
switch (ex)
{
case FormatException _:
case OverflowException _:
WebId = Guid.Empty;
break;
default:
throw;
}
}
Thanks to Orace comment this can be simplified with C# 8 by omitting the discard variable:
catch (Exception ex)
{
switch (ex)
{
case FormatException:
case OverflowException:
WebId = Guid.Empty;
break;
default:
throw;
}
}
And with C# 8 as switch expression:
catch (Exception ex)
{
WebId = ex switch
{
_ when ex is FormatException || ex is OverflowException => Guid.Empty,
_ => throw ex
};
}
As Nechemia Hoffmann pointed out. The latter example will cause a loss of the stacktrace. This can be prevented by using the extension method described by Jürgen Steinblock to capture the stacktrace before throwing:
catch (Exception ex)
{
WebId = ex switch
{
_ when ex is FormatException || ex is OverflowException => Guid.Empty,
_ => throw ex.Capture()
};
}
public static Exception Capture(this Exception ex)
{
ExceptionDispatchInfo.Capture(ex).Throw();
return ex;
}
Both styles can be simplified with the pattern matching enhancements of C# 9:
catch (Exception ex)
{
switch (ex)
{
case FormatException or OverflowException:
WebId = Guid.Empty;
break;
default:
throw;
}
}
catch (Exception ex)
{
WebId = ex switch
{
_ when ex is FormatException or OverflowException => Guid.Empty,
_ => throw ex.Capture()
};
}
A: Wanted to added my short answer to this already long thread. Something that hasn't been mentioned is the order of precedence of the catch statements, more specifically you need to be aware of the scope of each type of exception you are trying to catch.
For example if you use a "catch-all" exception as Exception it will preceed all other catch statements and you will obviously get compiler errors however if you reverse the order you can chain up your catch statements (bit of an anti-pattern I think) you can put the catch-all Exception type at the bottom and this will be capture any exceptions that didn't cater for higher up in your try..catch block:
try
{
// do some work here
}
catch (WebException ex)
{
// catch a web excpetion
}
catch (ArgumentException ex)
{
// do some stuff
}
catch (Exception ex)
{
// you should really surface your errors but this is for example only
throw new Exception("An error occurred: " + ex.Message);
}
I highly recommend folks review this MSDN document:
Exception Hierarchy
A: As others have pointed out, you can have an if statement inside your catch block to determine what is going on. C#6 supports Exception Filters, so the following will work:
try { … }
catch (Exception e) when (MyFilter(e))
{
…
}
The MyFilter method could then look something like this:
private bool MyFilter(Exception e)
{
return e is ArgumentNullException || e is FormatException;
}
Alternatively, this can be all done inline (the right hand side of the when statement just has to be a boolean expression).
try { … }
catch (Exception e) when (e is ArgumentNullException || e is FormatException)
{
…
}
This is different from using an if statement from within the catch block, using exception filters will not unwind the stack.
You can download Visual Studio 2015 to check this out.
If you want to continue using Visual Studio 2013, you can install the following nuget package:
Install-Package Microsoft.Net.Compilers
At time of writing, this will include support for C# 6.
Referencing this package will cause the project to be built using the
specific version of the C# and Visual Basic compilers contained in the
package, as opposed to any system installed version.
A: If you don't want to use an if statement within the catch scopes, in C# 6.0 you can use Exception Filters syntax which was already supported by the CLR in previews versions but existed only in VB.NET/MSIL:
try
{
WebId = new Guid(queryString["web"]);
}
catch (Exception exception) when (exception is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
}
This code will catch the Exception only when it's a InvalidDataException or ArgumentNullException.
Actually, you can put basically any condition inside that when clause:
static int a = 8;
...
catch (Exception exception) when (exception is InvalidDataException && a == 8)
{
Console.WriteLine("Catch");
}
Note that as opposed to an if statement inside the catch's scope, Exception Filters cannot throw Exceptions, and when they do, or when the condition is not true, the next catch condition will be evaluated instead:
static int a = 7;
static int b = 0;
...
try
{
throw new InvalidDataException();
}
catch (Exception exception) when (exception is InvalidDataException && a / b == 2)
{
Console.WriteLine("Catch");
}
catch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)
{
Console.WriteLine("General catch");
}
Output: General catch.
When there is more then one true Exception Filter - the first one will be accepted:
static int a = 8;
static int b = 4;
...
try
{
throw new InvalidDataException();
}
catch (Exception exception) when (exception is InvalidDataException && a / b == 2)
{
Console.WriteLine("Catch");
}
catch (Exception exception) when (exception is InvalidDataException || exception is ArgumentException)
{
Console.WriteLine("General catch");
}
Output: Catch.
And as you can see in the MSIL the code is not translated to if statements, but to Filters, and Exceptions cannot be throw from within the areas marked with Filter 1 and Filter 2 but the filter throwing the Exception will fail instead, also the last comparison value pushed to the stack before the endfilter command will determine the success/failure of the filter (Catch 1 XOR Catch 2 will execute accordingly):
Also, specifically Guid has the Guid.TryParse method.
A: Maybe try to keep your code simple such as putting the common code in a method, as you would do in any other part of the code that is not inside a catch clause?
E.g.:
try
{
// ...
}
catch (FormatException)
{
DoSomething();
}
catch (OverflowException)
{
DoSomething();
}
// ...
private void DoSomething()
{
// ...
}
Just how I would do it, trying to find the simple is beautiful pattern
A: catch (Exception ex) when (ex is FormatException or OverflowException)
{
WebId = Guid.Empty;
}
or
catch (Exception ex)
{
if (ex is not FormatException and not OverflowException)
throw;
WebId = Guid.Empty;
}
A: Catch System.Exception and switch on the types
catch (Exception ex)
{
if (ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
return;
}
throw;
}
A: The accepted answer seems acceptable, except that CodeAnalysis/FxCop will complain about the fact that it's catching a general exception type.
Also, it seems the "is" operator might degrade performance slightly.
CA1800: Do not cast unnecessarily says to "consider testing the result of the 'as' operator instead", but if you do that, you'll be writing more code than if you catch each exception separately.
Anyhow, here's what I would do:
bool exThrown = false;
try
{
// Something
}
catch (FormatException) {
exThrown = true;
}
catch (OverflowException) {
exThrown = true;
}
if (exThrown)
{
// Something else
}
A: Not in C# unfortunately, as you'd need an exception filter to do it and C# doesn't expose that feature of MSIL. VB.NET does have this capability though, e.g.
Catch ex As Exception When TypeOf ex Is FormatException OrElse TypeOf ex Is OverflowException
What you could do is use an anonymous function to encapsulate your on-error code, and then call it in those specific catch blocks:
Action onError = () => WebId = Guid.Empty;
try
{
// something
}
catch (FormatException)
{
onError();
}
catch (OverflowException)
{
onError();
}
A: in C# 6 the recommended approach is to use Exception Filters, here is an example:
try
{
throw new OverflowException();
}
catch(Exception e ) when ((e is DivideByZeroException) || (e is OverflowException))
{
// this will execute iff e is DividedByZeroEx or OverflowEx
Console.WriteLine("E");
}
A: This is a variant of Matt's answer (I feel that this is a bit cleaner)...use a method:
public void TryCatch(...)
{
try
{
// something
return;
}
catch (FormatException) {}
catch (OverflowException) {}
WebId = Guid.Empty;
}
Any other exceptions will be thrown and the code WebId = Guid.Empty; won't be hit. If you don't want other exceptions to crash your program, just add this AFTER the other two catches:
...
catch (Exception)
{
// something, if anything
return; // only need this if you follow the example I gave and put it all in a method
}
A: Joseph Daigle's Answer is a good solution, but I found the following structure to be a bit tidier and less error prone.
catch(Exception ex)
{
if (!(ex is SomeException || ex is OtherException)) throw;
// Handle exception
}
There are a few advantages of inverting the expression:
*
*A return statement is not necessary
*The code isn't nested
*There's no risk of forgetting the 'throw' or 'return' statements that in Joseph's solution are separated from the expression.
It can even be compacted to a single line (though not very pretty)
catch(Exception ex) { if (!(ex is SomeException || ex is OtherException)) throw;
// Handle exception
}
Edit:
The exception filtering in C# 6.0 will make the syntax a bit cleaner and comes with a number of other benefits over any current solution. (most notably leaving the stack unharmed)
Here is how the same problem would look using C# 6.0 syntax:
catch(Exception ex) when (ex is SomeException || ex is OtherException)
{
// Handle exception
}
A: Exception filters are now available in c# 6+. You can do
try
{
WebId = new Guid(queryString["web"]);
}
catch (Exception ex) when(ex is FormatException || ex is OverflowException)
{
WebId = Guid.Empty;
}
In C# 7.0+, you can combine this with pattern matching too
try
{
await Task.WaitAll(tasks);
}
catch (Exception ex) when( ex is AggregateException ae &&
ae.InnerExceptions.Count > tasks.Count/2)
{
//More than half of the tasks failed maybe..?
}
A: @Micheal
Slightly revised version of your code:
catch (Exception ex)
{
Type exType = ex.GetType();
if (exType == typeof(System.FormatException) ||
exType == typeof(System.OverflowException)
{
WebId = Guid.Empty;
} else {
throw;
}
}
String comparisons are ugly and slow.
A: For the sake of completeness, since .NET 4.0 the code can rewritten as:
Guid.TryParse(queryString["web"], out WebId);
TryParse never throws exceptions and returns false if format is wrong, setting WebId to Guid.Empty.
Since C# 7 you can avoid introducing a variable on a separate line:
Guid.TryParse(queryString["web"], out Guid webId);
You can also create methods for parsing returning tuples, which aren't available in .NET Framework yet as of version 4.6:
(bool success, Guid result) TryParseGuid(string input) =>
(Guid.TryParse(input, out Guid result), result);
And use them like this:
WebId = TryParseGuid(queryString["web"]).result;
// or
var tuple = TryParseGuid(queryString["web"]);
WebId = tuple.success ? tuple.result : DefaultWebId;
Next useless update to this useless answer comes when deconstruction of out-parameters is implemented in C# 12. :)
A: How about
try
{
WebId = Guid.Empty;
WebId = new Guid(queryString["web"]);
}
catch (FormatException)
{
}
catch (OverflowException)
{
}
A: Cautioned and Warned: Yet another kind, functional style.
What is in the link doesn't answer your question directly, but it's trivial to extend it to look like:
static void Main()
{
Action body = () => { ...your code... };
body.Catch<InvalidOperationException>()
.Catch<BadCodeException>()
.Catch<AnotherException>(ex => { ...handler... })();
}
(Basically provide another empty Catch overload which returns itself)
The bigger question to this is why. I do not think the cost outweighs the gain here :)
A: Update 2015-12-15: See https://stackoverflow.com/a/22864936/1718702 for C#6. It's a cleaner and now standard in the language.
Geared for people that want a more elegant solution to catch once and filter exceptions, I use an extension method as demonstrated below.
I already had this extension in my library, originally written for other purposes, but it worked just perfectly for type checking on exceptions. Plus, imho, it looks cleaner than a bunch of || statements. Also, unlike the accepted answer, I prefer explicit exception handling so ex is ... had undesireable behaviour as derrived classes are assignable to there parent types).
Usage
if (ex.GetType().IsAnyOf(
typeof(FormatException),
typeof(ArgumentException)))
{
// Handle
}
else
throw;
IsAnyOf.cs Extension (See Full Error Handling Example for Dependancies)
namespace Common.FluentValidation
{
public static partial class Validate
{
/// <summary>
/// Validates the passed in parameter matches at least one of the passed in comparisons.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p_parameter">Parameter to validate.</param>
/// <param name="p_comparisons">Values to compare against.</param>
/// <returns>True if a match is found.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)
{
// Validate
p_parameter
.CannotBeNull("p_parameter");
p_comparisons
.CannotBeNullOrEmpty("p_comparisons");
// Test for any match
foreach (var item in p_comparisons)
if (p_parameter.Equals(item))
return true;
// Return no matches found
return false;
}
}
}
Full Error Handling Example (Copy-Paste to new Console app)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.FluentValidation;
namespace IsAnyOfExceptionHandlerSample
{
class Program
{
static void Main(string[] args)
{
// High Level Error Handler (Log and Crash App)
try
{
Foo();
}
catch (OutOfMemoryException ex)
{
Console.WriteLine("FATAL ERROR! System Crashing. " + ex.Message);
Console.ReadKey();
}
}
static void Foo()
{
// Init
List<Action<string>> TestActions = new List<Action<string>>()
{
(key) => { throw new FormatException(); },
(key) => { throw new ArgumentException(); },
(key) => { throw new KeyNotFoundException();},
(key) => { throw new OutOfMemoryException(); },
};
// Run
foreach (var FooAction in TestActions)
{
// Mid-Level Error Handler (Appends Data for Log)
try
{
// Init
var SomeKeyPassedToFoo = "FooParam";
// Low-Level Handler (Handle/Log and Keep going)
try
{
FooAction(SomeKeyPassedToFoo);
}
catch (Exception ex)
{
if (ex.GetType().IsAnyOf(
typeof(FormatException),
typeof(ArgumentException)))
{
// Handle
Console.WriteLine("ex was {0}", ex.GetType().Name);
Console.ReadKey();
}
else
{
// Add some Debug info
ex.Data.Add("SomeKeyPassedToFoo", SomeKeyPassedToFoo.ToString());
throw;
}
}
}
catch (KeyNotFoundException ex)
{
// Handle differently
Console.WriteLine(ex.Message);
int Count = 0;
if (!Validate.IsAnyNull(ex, ex.Data, ex.Data.Keys))
foreach (var Key in ex.Data.Keys)
Console.WriteLine(
"[{0}][\"{1}\" = {2}]",
Count, Key, ex.Data[Key]);
Console.ReadKey();
}
}
}
}
}
namespace Common.FluentValidation
{
public static partial class Validate
{
/// <summary>
/// Validates the passed in parameter matches at least one of the passed in comparisons.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p_parameter">Parameter to validate.</param>
/// <param name="p_comparisons">Values to compare against.</param>
/// <returns>True if a match is found.</returns>
/// <exception cref="ArgumentNullException"></exception>
public static bool IsAnyOf<T>(this T p_parameter, params T[] p_comparisons)
{
// Validate
p_parameter
.CannotBeNull("p_parameter");
p_comparisons
.CannotBeNullOrEmpty("p_comparisons");
// Test for any match
foreach (var item in p_comparisons)
if (p_parameter.Equals(item))
return true;
// Return no matches found
return false;
}
/// <summary>
/// Validates if any passed in parameter is equal to null.
/// </summary>
/// <param name="p_parameters">Parameters to test for Null.</param>
/// <returns>True if one or more parameters are null.</returns>
public static bool IsAnyNull(params object[] p_parameters)
{
p_parameters
.CannotBeNullOrEmpty("p_parameters");
foreach (var item in p_parameters)
if (item == null)
return true;
return false;
}
}
}
namespace Common.FluentValidation
{
public static partial class Validate
{
/// <summary>
/// Validates the passed in parameter is not null, throwing a detailed exception message if the test fails.
/// </summary>
/// <param name="p_parameter">Parameter to validate.</param>
/// <param name="p_name">Name of tested parameter to assist with debugging.</param>
/// <exception cref="ArgumentNullException"></exception>
public static void CannotBeNull(this object p_parameter, string p_name)
{
if (p_parameter == null)
throw
new
ArgumentNullException(
string.Format("Parameter \"{0}\" cannot be null.",
p_name), default(Exception));
}
}
}
namespace Common.FluentValidation
{
public static partial class Validate
{
/// <summary>
/// Validates the passed in parameter is not null or an empty collection, throwing a detailed exception message if the test fails.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="p_parameter">Parameter to validate.</param>
/// <param name="p_name">Name of tested parameter to assist with debugging.</param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static void CannotBeNullOrEmpty<T>(this ICollection<T> p_parameter, string p_name)
{
if (p_parameter == null)
throw new ArgumentNullException("Collection cannot be null.\r\nParameter_Name: " + p_name, default(Exception));
if (p_parameter.Count <= 0)
throw new ArgumentOutOfRangeException("Collection cannot be empty.\r\nParameter_Name: " + p_name, default(Exception));
}
/// <summary>
/// Validates the passed in parameter is not null or empty, throwing a detailed exception message if the test fails.
/// </summary>
/// <param name="p_parameter">Parameter to validate.</param>
/// <param name="p_name">Name of tested parameter to assist with debugging.</param>
/// <exception cref="ArgumentException"></exception>
public static void CannotBeNullOrEmpty(this string p_parameter, string p_name)
{
if (string.IsNullOrEmpty(p_parameter))
throw new ArgumentException("String cannot be null or empty.\r\nParameter_Name: " + p_name, default(Exception));
}
}
}
Two Sample NUnit Unit Tests
Matching behaviour for Exception types is exact (ie. A child IS NOT a match for any of its parent types).
using System;
using System.Collections.Generic;
using Common.FluentValidation;
using NUnit.Framework;
namespace UnitTests.Common.Fluent_Validations
{
[TestFixture]
public class IsAnyOf_Tests
{
[Test, ExpectedException(typeof(ArgumentNullException))]
public void IsAnyOf_ArgumentNullException_ShouldNotMatch_ArgumentException_Test()
{
Action TestMethod = () => { throw new ArgumentNullException(); };
try
{
TestMethod();
}
catch (Exception ex)
{
if (ex.GetType().IsAnyOf(
typeof(ArgumentException), /*Note: ArgumentNullException derrived from ArgumentException*/
typeof(FormatException),
typeof(KeyNotFoundException)))
{
// Handle expected Exceptions
return;
}
//else throw original
throw;
}
}
[Test, ExpectedException(typeof(OutOfMemoryException))]
public void IsAnyOf_OutOfMemoryException_ShouldMatch_OutOfMemoryException_Test()
{
Action TestMethod = () => { throw new OutOfMemoryException(); };
try
{
TestMethod();
}
catch (Exception ex)
{
if (ex.GetType().IsAnyOf(
typeof(OutOfMemoryException),
typeof(StackOverflowException)))
throw;
/*else... Handle other exception types, typically by logging to file*/
}
}
}
}
A: It is worth mentioning here. You can respond to the multiple combinations (Exception error and exception.message).
I ran into a use case scenario when trying to cast control object in a datagrid, with either content as TextBox, TextBlock or CheckBox. In this case the returned Exception was the same, but the message varied.
try
{
//do something
}
catch (Exception ex) when (ex.Message.Equals("the_error_message1_here"))
{
//do whatever you like
}
catch (Exception ex) when (ex.Message.Equals("the_error_message2_here"))
{
//do whatever you like
}
A: I want to suggest shortest answer (one more functional style):
Catch<FormatException, OverflowException>(() =>
{
WebId = new Guid(queryString["web"]);
},
exception =>
{
WebId = Guid.Empty;
});
For this you need to create several "Catch" method overloads, similar to System.Action:
[DebuggerNonUserCode]
public static void Catch<TException1, TException2>(Action tryBlock,
Action<Exception> catchBlock)
{
CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
}
[DebuggerNonUserCode]
public static void Catch<TException1, TException2, TException3>(Action tryBlock,
Action<Exception> catchBlock)
{
CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
}
and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).
And CatchMany implementation:
[DebuggerNonUserCode]
public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,
params Type[] exceptionTypes)
{
try
{
tryBlock();
}
catch (Exception exception)
{
if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
else throw;
}
}
p.s. I haven't put null checks for code simplicity, consider to add parameter validations.
p.s.2
If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.
A: try
{
WebId = new Guid(queryString["web"]);
}
catch (Exception ex)
{
string ExpTyp = ex.GetType().Name;
if (ExpTyp == "FormatException")
{
WebId = Guid.Empty;
}
else if (ExpTyp == "OverflowException")
{
WebId = Guid.Empty;
}
}
A: In c# 6.0,Exception Filters is improvements for exception handling
try
{
DoSomeHttpRequest();
}
catch (System.Web.HttpException e)
{
switch (e.GetHttpCode())
{
case 400:
WriteLine("Bad Request");
case 500:
WriteLine("Internal Server Error");
default:
WriteLine("Generic Error");
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2507"
}
|
Q: Prevent visual studio creating browse info (.ncb) files Is there a way to prevent VS2008 creating browse info file files for C++ projects.
I rarely use the class browser and it isn't worth the time it takes to recreate it after every build, especially since it runs even if the build failed.
EDIT - it's also needed for go to declaration/definition
A: In the project properties, you will find the browse information under:
Configuration Properties -> C/C++ -> Browse Information
Just tell it not to generate browse information. All it is used for is quickly browsing between code components (like using 'Go to Definition') and so forth. I personally like being able to quickly jump between the components, but if it is adding unnecessary time to your compile don't worry about turning it off.
A: There is a registry key for this as well: [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]
Intellisense ON
"IntellisenseOptions"=dword:00000000
Intellisense OFF
"IntellisenseOptions"=dword:00000007
Intellisense ON - NO Background UPDATE
"IntellisenseOptions"=dword:00000005
More flags are available and you can Control Intellisense through Macros as well.
ISENSE_NORMAL = 0 'normal (Intellisense On)
ISENSE_NOBG = &H1 'no bg parsing (Intellisense Updating Off - although NCB file will be opened r/w and repersisted at shutdown)
ISENSE_NOQUERY = &H2 'no queries (don't run any ISense queries)
ISENSE_NCBRO = &H4 'no saving of NCB (must be set before opening NCB, doesn't affect updating or queries, just persisting of NCB)
ISENSE_OFF = &H7
A: Try creating a folder with the same name of the ncb file (you'll have to delete the file, of course). I used this trick in the past to prevent intellisense from locking VS2005. You'll lose intellisense, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How do I format a String in an email so Outlook will print the line breaks? I'm trying to send an email in Java but when I read the body of the email in Outlook, it's gotten rid of all my linebreaks. I'm putting \n at the ends of the lines but is there something special I need to do other than that? The receivers are always going to be using Outlook.
I found a page on microsoft.com that says there's a 'Remove line breaks' "feature" in Outlook so does this mean there's no solution to get around that other than un-checking that setting?
Thanks
A: I have used html line break instead of "\n" . It worked fine.
A: Adding "\t\r\n" ( \t for TAB) instead of "\r\n" worked for me on Outlook 2010 . Note : adding 3 spaces at end of each line also do same thing but that looks like a programming hack!
A: You can force a line break in outlook when attaching one (or two?) tab characters (\t) just before the line break (CRLF).
Example:
This is my heading in the mail\t\n
Just here Outlook is forced to begin a new line.
It seems to work on Outlook 2010. Please test if this works on other versions.
See also Outlook autocleaning my line breaks and screwing up my email format
A: You need to use \r\n as a solution.
A: Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.
This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.
For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:
Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543
Your Outlook recipient will see the information all smashed together, as follows:
Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543
There doesn't seem to be an easy solution. Alternatives are:
*
*You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
*You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
*You can give up on using a plain text format, and use an html format.
A: I've just been fighting with this today. Let's call the behavior of removing the extra line breaks "continuation." A little experimenting finds the following behavior:
*
*Every message starts with continuation off.
*Lines less than 40 characters long do not trigger continuation, but if continuation is on, they will have their line breaks removed.
*Lines 40 characters or longer turn continuation on. It remains on until an event occurs to turn it off.
*Lines that end with a period, question mark, exclamation point or colon turn continuation off. (Outlook assumes it's the end of a sentence?)
*Lines that turn continuation off will start with a line break, but will turn continuation back on if they are longer than 40 characters.
*Lines that start or end with a tab turn continuation off.
*Lines that start with 2 or more spaces turn continuation off.
*Lines that end with 3 or more spaces turn continuation off.
Please note that I tried all of this with Outlook 2007. YMMV.
So if possible, end all bullet items with a sentence-terminating punctuation mark, a tab, or even three spaces.
A: You need to send HTML emails. With <br />s in the email, you will always have your line breaks.
A: I had been struggling with all of the above solutions and nothing helped here, because I used a String variable (plain text from a JTextPane) in combination with "text/html" formatting in my e-mail library.
So, the solution to this problem is to use "text/plain", instead of "text/html" and no need to replace return characters at all:
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/plain");
A: The trick is to use the encodeURIComponent() functionality from js:
var formattedBody = "FirstLine \n Second Line \n Third Line";
var mailToLink = "mailto:x@y.com?body=" + encodeURIComponent(formattedBody);
RESULT:
FirstLine
SecondLine
ThirdLine
A: I had the same issue, and found a solution. Try this: %0D%0A to add a line break.
A: For Outlook 2010 and later versions, use \t\n rather than using \r\n.
A: Try \r\c instead of \n.
EDIT: I think @Robert Wilkinson had it right. \r\n. Memory just isn't what it used to be.
A: The \n largely works for us, but Outlook does sometimes take it upon itself to remove the line breaks as you say.
A: If you can add in a '.' (dot) character at the end of each line, this seems to prevent Outlook ruining text formatting.
A: I also had this issue with plain/text mail type. Earlier, I used "\n\n" but there was two line breaks. Then, I used "\t\n" and it worked. I was using StringBuffer in java to append content.
The content got printed in next line in Outlook 2010 mail.
A: Put the text in <pre> Tags and outlook will format and display the text correctly.
i defined it in CSS inline in HTML Body like:
CSS:
pre {
font-family: Verdana, Geneva, sans-serif;
}
i defined the font-family to have to font set.
HTML:
<td width="70%"><pre>Entry Date/Time: 2013-09-19 17:06:25
Entered By: Chris
worklog mania
____________________________________________________________________________________________________
Entry Date/Time: 2013-09-19 17:05:42
Entered By: Chris
this is a new Worklog Entry</pre></td>
A: Because it is a query, only percent escaped characters work, means %0A gives you a line break. For example,
<a href="mailto:someone@gmail.com?Subject=TEST&amp;body=Hi there,%0A%0AHow are you?%0A%0AThanks">email to me</a>
A: I also had this issue with plain/text mail type.Form Feed \f worked for me.
A: Sometimes you have to enter \r\n twice to force outlook to do the break.
This will add one empty line but all the lines will have break.
A: \r\n will not work until you set body type as text.
message.setBody(MessageBody.getMessageBodyFromText(msg));
BodyType type = BodyType.Text;
message.getBody().setBodyType(type);
A: I was facing the same issue and here is the code that resolved it:
\t\n - for new line in Email service JavaMailSender
String mailMessage = JSONObject.toJSONString("Your message").replace(",", "\t\n").trim();
A: Try this:
message.setContent(new String(body.getBytes(), "iso-8859-1"),
"text/html; charset=\"iso-8859-1\"");
Regards,
Mohammad Rasool Javeed
A: RESOLVED IN MY APPLICATION
In my application, I was trying to send an email whose message body was typed by the user in text area. When mail was send, outlook automatically removed line break entered by user.
e.g if user entered
Yadav
Mahesh
outlook displayed it as
YadavMahesh
Resolution: I changed the line break character "\r\n" with "\par " ( remember to hit space at the end of RTF code "\par" )and line breaks are restrored.
Cheers,
Mahesh
A: I have a good solution that I tried it, it is just add the Char(13) at end of line like the following example:
Dim S As String
S = "Some Text" & Chr(13)
S = S + "Some Text" & Chr(13)
A: if the message is text/plain using, \r\n should work;
if the message type is text\html, use < p/>
A: if work need to be done with formatted text with out html encoding.
it can be easy achieved with following scenario that creates div element on the fly and using <pre></pre> html element to keep formatting.
var email_body = htmlEncode($("#Body").val());
function htmlEncode(value) {
return "<pre>" + $('<div/>').text(value).html() + "</pre>";
}
A: Not sure if it was mentioned above but Outlook has a checkbox setting called "Remove extra line breaks in plain text messages" and is checked by default. It is located in a different spot for different versions of Outlook but for 2010 go to the "File" tab. Select "Options => Mail" Scroll down to "Message format" Uncheck the checkbox.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "81"
}
|
Q: How to check if a file has the win2003 "blocked" option on it How do I check from within my NSIS installer if my installer has the blocked option in preferences on it.
Even if you know of a way to check this without NSIS, please let me know so I can script it myself.
See this question to find out more info about this blocked option.
A: Using Hitscan's related answer here...
You can check if an EXE has this property simply by checking for the existance of the alternate data stream (ADS):
file.exe:Zone.Identifier
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I profile a Perl web app? I am working on a web app that uses Perl and I need to look into speeding up portions of the app.
I thought I'd start profiling the particular calls for the portion I wish to investigate. I've done some searching on profiling Perl code, but unfortunately most of what I find says that I should run my perl code with -d:DProf myapp from the command line. That doesn't quite work for me since my code is within a web app. I did find a way to get the profiling to work with apache, but unfortunately, the "most used" modules that came back from the profiler were all CPAN modules -- Class::xyz, etc etc etc. Not terribly helpful.
Does anyone know of a good way besides me injecting "timer" code into the methods I wish to profile to target just these methods? I've thought of writing a test script and profiling that but due to the nature of the code I'm working on that would require a bit more work than I'm hoping to have to do.
A: Have you tried Devel::NYTProf (much better than Devel::DProf), which can work under Apache? Which webserver are you using? Is this a vanilla CGI script, a mod_perl thing, or something else?
If you're doing database stuff, the DBI::Profile can benchmark your queries, which is work happening in another program.
The real trick, however, is to organize the code so that you can do the full spectrum of testing and profiling without having to put it all together at the end to find out something is slow. That won't help you much in the short term to fight fires, but it does prevent things from becoming fires in the long run. There are also various ways to fake the webserver environment and so on, but that's a different question. :)
A: If you're using CGI.pm, you can pass arguments to your perl script on the command line and CGI.pm will interpret them as if they were passed as parameters over HTTP. So if you're debugging, e.g.
http://example.com/scripts/example.pl?action=browse&search=grommet&restrict=blah
then you could just call from the command line, e.g.
perl -d:NYTProf documentroot/scripts/example.pl 'action=browse&search=grommet&restrict=blah'
A: You can use the Benchmark core module with the :hireswallclock option if you really want to time things internally. But really, you should be able to profile from the command line. You might have to write test scripts to emulate certain portions of a CGI request, but DProf can be extremely useful when looking for performance bottlenecks.
In particular, look for where your code is calling the CPAN module code. You may be doing this in loops far more than necessary, so while the time is spent in the CPAN module, refactoring your code can fix the problem.
A: I realize it's a bit late for it at this point, but this is one of the reasons why it's good to use CGI::Application or another architecture in which the web app is just a very brief bit of web-facing code which makes use of a bunch of modules you've written to implement the actual functionality. Using such a design makes it very straightforward to profile (or simply test) any modules from the command line, either individually or collectively, without having to worry about the web aspect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: Python web development - with or without a framework I am planning on porting a PHP application over to Python. The application is mostly about data collection and processing. The main application runs as a stand alone command line application. There is a web interface to the application which is basically a very light weight reporting interface.
I did not use a framework in the PHP version, but being new to Python, I am wondering if it would be advantageous to use something like Django or at the very least Genshi. The caveat is I do not want my application distribution to be overwhelmed by the framework parts I would need to distribute with the application.
Is using only the cgi import in Python the best way to go in this circumstance? I would tend to think a framework is too much overhead, but perhaps I'm not thinking in a very "python" way about them. What suggestions do you have in this scenario?
A: Depends on the size of the project. If you had only a few previous php-scripts which called your stand alone application then I'd probably go for a cgi-app.
If you have use for databases, url rewriting, templating, user management and such, then using a framework is a good idea.
And of course, before you port it, consider if it's worth it just to switch the language or if there are specific Python features you need.
Good luck!
A: I recently ported a PHP app to Python using web.py. As frameworks go it is extremely lightweight with minimal dependencies, and it tends to stay out of your way, so it might be the compromise you're looking for.
It all depends on your initial application though, because with a large application the advantages of having a full-featured framework handling the plumbing tend to outweigh the disadvantages involved in having to drag around all the framework code.
A: Django makes it possible to whip out a website rapidly, that's for sure. You don't need to be a Python master to use it, and since it's very pythonic in it's design, and there is not really any "magic" going on, it will help you learn Python along the way.
Start with the examples, check out some django screencasts from TwiD and you'll be on your way.
Start slow, tweaking the admin, and playing with it via shell is the way to start. Once you have a handle on the ORM and get how things work, start building the real stuff!
The framework isn't going to cause any performance problems, like S. Lott said, it's code you don't have to maintain, and that's the best kind.
A: Go for a framework. Basic stuffs like session handling are a nightmare if you don't use a one because Python is not web specialized like PHP.
If you think django is too much, you can try a lighter one like the very small but still handy web.py.
A: For the love of pete, use a framework! There are literally dozens of frameworks out there, from cherrypy to django to albatross to ... well.. you name it. In fact, the huge number of web frameworks are what people point to when they whine about the popularity of Rails.
The Python web development community is divided up with no single voice. But that's another topic alltogether! The point is, there are "web toolkits" (e.g. albatross) that are fairly lightweight but powerful enough to get you through the day (e.g. auto-verifying a bot didn't do a simple form submission fake, or helping with keeping MVC clean).
If you want something that's not "too much framework" look here:
http://wiki.python.org/moin/WebFrameworks
Look under "Basic Frameworks Providing Templating". They're all lightweight and do all the "don't reinvent the wheel" stuff without forcing a Mac truck on you.
A: The command-line Python, IMO, definitely comes first. Get that to work, since that's the core of what you're doing.
The issue is that using a web framework's ORM from a command line application isn't obvious. Django provides specific instructions for using their ORM from a command-line app. Those are annoying at first, but I think they're a life-saver in the long run. I use it heavily for giant uploads of customer-supplied files.
Don't use bare CGI. It's not impossible, but too many things can go wrong, and they've all been solved by the frameworks. Why reinvent something? Just use someone else's code.
Frameworks involve learning, but no real "overhead". They're not slow. They're code you don't have to write or debug.
*
*Learn some Python.
*Do the Django tutorial.
*Start to build a web app.
a. Start a Django project. Build a small application in that project.
b. Build your new model using the Django ORM. Create a Django unit test for the model. Be sure that it works. You'll be able to use the default admin pages and do a lot of playing around. Just don't build the entire web site yet.
*Get your command-line app to work using Django ORM. Essentially, you have to finesse the settings file for this app to work nicely. See the settings/configuration section.
*Once you've got your command line and the default admin running, you can finish
the web app.
Here's the golden rule of frameworks: It's code you don't have to write, debug or maintain. Use them.
A: You might consider using something like web.py which would be easy to distribute (since it's small) and it would also be easy to adapt your other tools to it since it doesn't require you to submit to the framework so much like Django does.
Be forewarned, however, it's not the most loved framework in the Python community, but it might be just the thing for you. You might also check out web2py, but I know less about that.
A: It depends on the way you are going to distribute your application.
If it will only be used internally, go for django. It's a joy to work with it.
However, django really falls short at the distribution-task; django-applications are a pain to set up.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Difference between @staticmethod and @classmethod What is the difference between a method decorated with @staticmethod and one decorated with @classmethod?
A: Here is a short article on this question
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance. That’s because the first argument for @classmethod function must always be cls (class).
A: A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument. It is basically useless in Python -- you can just use a module function instead of a staticmethod.
A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:
>>> class DictSubclass(dict):
... def __repr__(self):
... return "DictSubclass"
...
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>>
A: @classmethod : can be used to create a shared global access to all the instances created of that class..... like updating a record by multiple users....
I particulary found it use ful when creating singletons as well..:)
@static method: has nothing to do with the class or instance being associated with ...but for readability can use static method
A: My contribution demonstrates the difference amongst @classmethod, @staticmethod, and instance methods, including how an instance can indirectly call a @staticmethod. But instead of indirectly calling a @staticmethod from an instance, making it private may be more "pythonic." Getting something from a private method isn't demonstrated here but it's basically the same concept.
#!python3
from os import system
system('cls')
# % % % % % % % % % % % % % % % % % % % %
class DemoClass(object):
# instance methods need a class instance and
# can access the instance through 'self'
def instance_method_1(self):
return 'called from inside the instance_method_1()'
def instance_method_2(self):
# an instance outside the class indirectly calls the static_method
return self.static_method() + ' via instance_method_2()'
# class methods don't need a class instance, they can't access the
# instance (self) but they have access to the class itself via 'cls'
@classmethod
def class_method(cls):
return 'called from inside the class_method()'
# static methods don't have access to 'cls' or 'self', they work like
# regular functions but belong to the class' namespace
@staticmethod
def static_method():
return 'called from inside the static_method()'
# % % % % % % % % % % % % % % % % % % % %
# works even if the class hasn't been instantiated
print(DemoClass.class_method() + '\n')
''' called from inside the class_method() '''
# works even if the class hasn't been instantiated
print(DemoClass.static_method() + '\n')
''' called from inside the static_method() '''
# % % % % % % % % % % % % % % % % % % % %
# >>>>> all methods types can be called on a class instance <<<<<
# instantiate the class
democlassObj = DemoClass()
# call instance_method_1()
print(democlassObj.instance_method_1() + '\n')
''' called from inside the instance_method_1() '''
# # indirectly call static_method through instance_method_2(), there's really no use
# for this since a @staticmethod can be called whether the class has been
# instantiated or not
print(democlassObj.instance_method_2() + '\n')
''' called from inside the static_method() via instance_method_2() '''
# call class_method()
print(democlassObj.class_method() + '\n')
''' called from inside the class_method() '''
# call static_method()
print(democlassObj.static_method())
''' called from inside the static_method() '''
"""
# whether the class is instantiated or not, this doesn't work
print(DemoClass.instance_method_1() + '\n')
'''
TypeError: TypeError: unbound method instancemethod() must be called with
DemoClass instance as first argument (got nothing instead)
'''
"""
A: You might want to consider the difference between:
class A:
def foo(): # no self parameter, no decorator
pass
and
class B:
@staticmethod
def foo(): # no self parameter
pass
This has changed between python2 and python3:
python2:
>>> A.foo()
TypeError
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()
python3:
>>> A.foo()
>>> A().foo()
TypeError
>>> B.foo()
>>> B().foo()
So using @staticmethod for methods only called directly from the class has become optional in python3. If you want to call them from both class and instance, you still need to use the @staticmethod decorator.
The other cases have been well covered by unutbus answer.
A: A class method receives the class as implicit first argument, just like an instance method receives the instance. It is a method which is bound to the class and not the object of the class.It has access to the state of the class as it takes a class parameter that points to the class and not the object instance. It can modify a class state that would apply across all the instances of the class. For example it can modify a class variable that will be applicable to all the instances.
On the other hand, a static method does not receive an implicit first argument, compared to class methods or instance methods. And can’t access or modify class state. It only belongs to the class because from design point of view that is the correct way. But in terms of functionality is not bound, at runtime, to the class.
as a guideline, use static methods as utilities, use class methods for example as factory . Or maybe to define a singleton. And use instance methods to model the state and behavior of instances.
Hope I was clear !
A:
What is the difference between @staticmethod and @classmethod in Python?
You may have seen Python code like this pseudocode, which demonstrates the signatures of the various method types and provides a docstring to explain each:
class Foo(object):
def a_normal_instance_method(self, arg_1, kwarg_2=None):
'''
Return a value that is a function of the instance with its
attributes, and other arguments such as arg_1 and kwarg2
'''
@staticmethod
def a_static_method(arg_0):
'''
Return a value that is a function of arg_0. It does not know the
instance or class it is called from.
'''
@classmethod
def a_class_method(cls, arg1):
'''
Return a value that is a function of the class and other arguments.
respects subclassing, it is called with the class it is called from.
'''
The Normal Instance Method
First I'll explain a_normal_instance_method. This is precisely called an "instance method". When an instance method is used, it is used as a partial function (as opposed to a total function, defined for all values when viewed in source code) that is, when used, the first of the arguments is predefined as the instance of the object, with all of its given attributes. It has the instance of the object bound to it, and it must be called from an instance of the object. Typically, it will access various attributes of the instance.
For example, this is an instance of a string:
', '
if we use the instance method, join on this string, to join another iterable,
it quite obviously is a function of the instance, in addition to being a function of the iterable list, ['a', 'b', 'c']:
>>> ', '.join(['a', 'b', 'c'])
'a, b, c'
Bound methods
Instance methods can be bound via a dotted lookup for use later.
For example, this binds the str.join method to the ':' instance:
>>> join_with_colons = ':'.join
And later we can use this as a function that already has the first argument bound to it. In this way, it works like a partial function on the instance:
>>> join_with_colons('abcde')
'a:b:c:d:e'
>>> join_with_colons(['FF', 'FF', 'FF', 'FF', 'FF', 'FF'])
'FF:FF:FF:FF:FF:FF'
Static Method
The static method does not take the instance as an argument.
It is very similar to a module level function.
However, a module level function must live in the module and be specially imported to other places where it is used.
If it is attached to the object, however, it will follow the object conveniently through importing and inheritance as well.
An example of a static method is str.maketrans, moved from the string module in Python 3. It makes a translation table suitable for consumption by str.translate. It does seem rather silly when used from an instance of a string, as demonstrated below, but importing the function from the string module is rather clumsy, and it's nice to be able to call it from the class, as in str.maketrans
# demonstrate same function whether called from instance or not:
>>> ', '.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
>>> str.maketrans('ABC', 'abc')
{65: 97, 66: 98, 67: 99}
In python 2, you have to import this function from the increasingly less useful string module:
>>> import string
>>> 'ABCDEFG'.translate(string.maketrans('ABC', 'abc'))
'abcDEFG'
Class Method
A class method is a similar to an instance method in that it takes an implicit first argument, but instead of taking the instance, it takes the class. Frequently these are used as alternative constructors for better semantic usage and it will support inheritance.
The most canonical example of a builtin classmethod is dict.fromkeys. It is used as an alternative constructor of dict, (well suited for when you know what your keys are and want a default value for them.)
>>> dict.fromkeys(['a', 'b', 'c'])
{'c': None, 'b': None, 'a': None}
When we subclass dict, we can use the same constructor, which creates an instance of the subclass.
>>> class MyDict(dict): 'A dict subclass, use to demo classmethods'
>>> md = MyDict.fromkeys(['a', 'b', 'c'])
>>> md
{'a': None, 'c': None, 'b': None}
>>> type(md)
<class '__main__.MyDict'>
See the pandas source code for other similar examples of alternative constructors, and see also the official Python documentation on classmethod and staticmethod.
A: I started learning programming language with C++ and then Java and then Python and so this question bothered me a lot as well, until I understood the simple usage of each.
Class Method: Python unlike Java and C++ doesn't have constructor overloading. And so to achieve this you could use classmethod. Following example will explain this
Let's consider we have a Person class which takes two arguments first_name and last_name and creates the instance of Person.
class Person(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
Now, if the requirement comes where you need to create a class using a single name only, just a first_name, you can't do something like this in Python.
This will give you an error when you will try to create an object (instance).
class Person(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def __init__(self, first_name):
self.first_name = first_name
However, you could achieve the same thing using @classmethod as mentioned below
class Person(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def get_person(cls, first_name):
return cls(first_name, "")
Static Method: This is rather simple, it's not bound to instance or class and you can simply call that using class name.
So let's say in above example you need a validation that first_name should not exceed 20 characters, you can simply do this.
@staticmethod
def validate_name(name):
return len(name) <= 20
and you could simply call using class name
Person.validate_name("Gaurang Shah")
A: Only the first argument differs:
*
*normal method: the current object is automatically passed as an (additional) first argument
*classmethod: the class of the current object is automatically passed as an (additional) fist argument
*staticmethod: no extra arguments are automatically passed. What you passed to the function is what you get.
In more detail...
normal method
The "standard" method, as in every object oriented language. When an object's method is called, it is automatically given an extra argument self as its first argument. That is, method
def f(self, x, y)
must be called with 2 arguments. self is automatically passed, and it is the object itself. Similar to the this that magically appears in eg. java/c++, only in python it is shown explicitly.
actually, the first argument does not have to be called self, but it's the standard convention, so keep it
class method
When the method is decorated
@classmethod
def f(cls, x, y)
the automatically provided argument is not self, but the class of self.
static method
When the method is decorated
@staticmethod
def f(x, y)
the method is not given any automatic argument at all. It is only given the parameters that it is called with.
usages
*
*classmethod is mostly used for alternative constructors.
*staticmethod does not use the state of the object, or even the structure of the class itself. It could be a function external to a class. It only put inside the class for grouping functions with similar functionality (for example, like Java's Math class static methods)
class Point
def __init__(self, x, y):
self.x = x
self.y = y
@classmethod
def frompolar(cls, radius, angle):
"""The `cls` argument is the `Point` class itself"""
return cls(radius * cos(angle), radius * sin(angle))
@staticmethod
def angle(x, y):
"""this could be outside the class, but we put it here
just because we think it is logically related to the class."""
return atan(y, x)
p1 = Point(3, 2)
p2 = Point.frompolar(3, pi/4)
angle = Point.angle(3, 2)
A: Class methods, as the name suggests, are used to make changes to classes and not the objects. To make changes to classes, they will modify the class attributes(not object attributes), since that is how you update classes.
This is the reason that class methods take the class(conventionally denoted by 'cls') as the first argument.
class A(object):
m=54
@classmethod
def class_method(cls):
print "m is %d" % cls.m
Static methods on the other hand, are used to perform functionalities that are not bound to the class i.e. they will not read or write class variables. Hence, static methods do not take classes as arguments. They are used so that classes can perform functionalities that are not directly related to the purpose of the class.
class X(object):
m=54 #will not be referenced
@staticmethod
def static_method():
print "Referencing/calling a variable or function outside this class. E.g. Some global variable/function."
A: I think giving a purely Python version of staticmethod and classmethod would help to understand the difference between them at language level (Refers to Descriptor Howto Guide).
Both of them are non-data descriptors (It would be easier to understand them if you are familiar with descriptors first).
class StaticMethod(object):
"Emulate PyStaticMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
return self.f
class ClassMethod(object):
"Emulate PyClassMethod_Type() in Objects/funcobject.c"
def __init__(self, f):
self.f = f
def __get__(self, obj, cls=None):
def inner(*args, **kwargs):
if cls is None:
cls = type(obj)
return self.f(cls, *args, **kwargs)
return inner
A: I think a better question is "When would you use @classmethod vs @staticmethod?"
@classmethod allows you easy access to private members that are associated to the class definition. this is a great way to do singletons, or factory classes that control the number of instances of the created objects exist.
@staticmethod provides marginal performance gains, but I have yet to see a productive use of a static method within a class that couldn't be achieved as a standalone function outside the class.
A: Static Methods:
*
*Simple functions with no self argument.
*Work on class attributes; not on instance attributes.
*Can be called through both class and instance.
*The built-in function staticmethod()is used to create them.
Benefits of Static Methods:
*
*It localizes the function name in the classscope
*It moves the function code closer to where it is used
*More convenient to import versus module-level functions since each method does not have to be specially imported
@staticmethod
def some_static_method(*args, **kwds):
pass
Class Methods:
*
*Functions that have first argument as classname.
*Can be called through both class and instance.
*These are created with classmethod in-built function.
@classmethod
def some_class_method(cls, *args, **kwds):
pass
A: Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:
class A(object):
def foo(self, x):
print(f"executing foo({self}, {x})")
@classmethod
def class_foo(cls, x):
print(f"executing class_foo({cls}, {x})")
@staticmethod
def static_foo(x):
print(f"executing static_foo({x})")
a = A()
Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument.
a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>, 1)
With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.
a.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
You can also call class_foo using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:
A.class_foo(1)
# executing class_foo(<class '__main__.A'>, 1)
One use people have found for class methods is to create inheritable alternative constructors.
With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:
a.static_foo(1)
# executing static_foo(1)
A.static_foo('hi')
# executing static_foo(hi)
Staticmethods are used to group functions which have some logical connection with a class to the class.
foo is just a function, but when you call a.foo you don't just get the function,
you get a "partially applied" version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument.
a is bound to foo. That is what is meant by the term "bound" below:
print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>
With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.
print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>
Here, with a staticmethod, even though it is a method, a.static_foo just returns
a good 'ole function with no arguments bound. static_foo expects 1 argument, and
a.static_foo expects 1 argument too.
print(a.static_foo)
# <function static_foo at 0xb7d479cc>
And of course the same thing happens when you call static_foo with the class A instead.
print(A.static_foo)
# <function static_foo at 0xb7d479cc>
A: @decorators were added in python 2.4 If you're using python < 2.4 you can use the classmethod() and staticmethod() function.
For example, if you want to create a factory method (A function returning an instance of a different implementation of a class depending on what argument it gets) you can do something like:
class Cluster(object):
def _is_cluster_for(cls, name):
"""
see if this class is the cluster with this name
this is a classmethod
"""
return cls.__name__ == name
_is_cluster_for = classmethod(_is_cluster_for)
#static method
def getCluster(name):
"""
static factory method, should be in Cluster class
returns a cluster object for the given name
"""
for cls in Cluster.__subclasses__():
if cls._is_cluster_for(name):
return cls()
getCluster = staticmethod(getCluster)
Also observe that this is a good example for using a classmethod and a static method,
The static method clearly belongs to the class, since it uses the class Cluster internally.
The classmethod only needs information about the class, and no instance of the object.
Another benefit of making the _is_cluster_for method a classmethod is so a subclass can decide to change it's implementation, maybe because it is pretty generic and can handle more than one type of cluster, so just checking the name of the class would not be enough.
A: Let me tell the similarity between a method decorated with @classmethod vs @staticmethod first.
Similarity: Both of them can be called on the Class itself, rather than just the instance of the class. So, both of them in a sense are Class's methods.
Difference: A classmethod will receive the class itself as the first argument, while a staticmethod does not.
So a static method is, in a sense, not bound to the Class itself and is just hanging in there just because it may have a related functionality.
>>> class Klaus:
@classmethod
def classmthd(*args):
return args
@staticmethod
def staticmthd(*args):
return args
# 1. Call classmethod without any arg
>>> Klaus.classmthd()
(__main__.Klaus,) # the class gets passed as the first argument
# 2. Call classmethod with 1 arg
>>> Klaus.classmthd('chumma')
(__main__.Klaus, 'chumma')
# 3. Call staticmethod without any arg
>>> Klaus.staticmthd()
()
# 4. Call staticmethod with 1 arg
>>> Klaus.staticmthd('chumma')
('chumma',)
A: @staticmethod just disables the default function as method descriptor. classmethod wraps your function in a container callable that passes a reference to the owning class as first argument:
>>> class C(object):
... pass
...
>>> def f():
... pass
...
>>> staticmethod(f).__get__(None, C)
<function f at 0x5c1cf0>
>>> classmethod(f).__get__(None, C)
<bound method type.f of <class '__main__.C'>>
As a matter of fact, classmethod has a runtime overhead but makes it possible to access the owning class. Alternatively I recommend using a metaclass and putting the class methods on that metaclass:
>>> class CMeta(type):
... def foo(cls):
... print cls
...
>>> class C(object):
... __metaclass__ = CMeta
...
>>> C.foo()
<class '__main__.C'>
A: Analyze @staticmethod literally providing different insights.
A normal method of a class is an implicit dynamic method which takes the instance as first argument.
In contrast, a staticmethod does not take the instance as first argument, so is called 'static'.
A staticmethod is indeed such a normal function the same as those outside a class definition.
It is luckily grouped into the class just in order to stand closer where it is applied, or you might scroll around to find it.
A: One pretty important practical difference occurs when subclassing. If you don't mind, I'll hijack @unutbu's example:
class A:
def foo(self, x):
print("executing foo(%s, %s)" % (self, x))
@classmethod
def class_foo(cls, x):
print("executing class_foo(%s, %s)" % (cls, x))
@staticmethod
def static_foo(x):
print("executing static_foo(%s)" % x)
class B(A):
pass
In class_foo, the method knows which class it is called on:
A.class_foo(1)
# => executing class_foo(<class '__main__.A'>, 1)
B.class_foo(1)
# => executing class_foo(<class '__main__.B'>, 1)
In static_foo, there is no way to determine whether it is called on A or B:
A.static_foo(1)
# => executing static_foo(1)
B.static_foo(1)
# => executing static_foo(1)
Note that this doesn't mean you can't use other methods in a staticmethod, you just have to reference the class directly, which means subclasses' staticmethods will still reference the parent class:
class A:
@classmethod
def class_qux(cls, x):
print(f"executing class_qux({cls}, {x})")
@classmethod
def class_bar(cls, x):
cls.class_qux(x)
@staticmethod
def static_bar(x):
A.class_qux(x)
class B(A):
pass
A.class_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.class_bar(1)
# => executing class_qux(<class '__main__.B'>, 1)
A.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
B.static_bar(1)
# => executing class_qux(<class '__main__.A'>, 1)
A: tldr;
A staticmethod is essentially a function bound to a class (and consequently its instances)
A classmethod is essentially an inheritable staticmethod.
For details, see the excellent answers by others.
A: First let's start with an example code that we'll use to understand both concepts:
class Employee:
NO_OF_EMPLOYEES = 0
def __init__(self, first_name, last_name, salary):
self.first_name = first_name
self.last_name = last_name
self.salary = salary
self.increment_employees()
def give_raise(self, amount):
self.salary += amount
@classmethod
def employee_from_full_name(cls, full_name, salary):
split_name = full_name.split(' ')
first_name = split_name[0]
last_name = split_name[1]
return cls(first_name, last_name, salary)
@classmethod
def increment_employees(cls):
cls.NO_OF_EMPLOYEES += 1
@staticmethod
def get_employee_legal_obligations_txt():
legal_obligations = """
1. An employee must complete 8 hours per working day
2. ...
"""
return legal_obligations
Class method
A class method accepts the class itself as an implicit argument and -optionally- any other arguments specified in the definition. It’s important to understand that a class method, does not have access to object instances (like instance methods do). Therefore, class methods cannot be used to alter the state of an instantiated object but instead, they are capable of changing the class state which is shared amongst all the instances of that class.
Class methods are typically useful when we need to access the class itself — for example, when we want to create a factory method, that is a method that creates instances of the class. In other words, class methods can serve as alternative constructors.
In our example code, an instance of Employee can be constructed by providing three arguments; first_name , last_name and salary.
employee_1 = Employee('Andrew', 'Brown', 85000)
print(employee_1.first_name)
print(employee_1.salary)
'Andrew'
85000
Now let’s assume that there’s a chance that the name of an Employee can be provided in a single field in which the first and last names are separated by a whitespace. In this case, we could possibly use our class method called employee_from_full_name that accepts three arguments in total. The first one, is the class itself, which is an implicit argument which means that it won’t be provided when calling the method — Python will automatically do this for us:
employee_2 = Employee.employee_from_full_name('John Black', 95000)
print(employee_2.first_name)
print(employee_2.salary)
'John'
95000
Note that it is also possible to call employee_from_full_name from object instances although in this context it doesn’t make a lot of sense:
employee_1 = Employee('Andrew', 'Brown', 85000)
employee_2 = employee_1.employee_from_full_name('John Black', 95000)
Another reason why we might want to create a class method, is when we need to change the state of the class. In our example, the class variable NO_OF_EMPLOYEES keeps track of the number of employees currently working for the company. This method is called every time a new instance of Employee is created and it updates the count accordingly:
employee_1 = Employee('Andrew', 'Brown', 85000)
print(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')
employee_2 = Employee.employee_from_full_name('John Black', 95000)
print(f'Number of employees: {Employee.NO_OF_EMPLOYEES}')
Number of employees: 1
Number of employees: 2
Static methods
On the other hand, in static methods neither the instance (i.e. self) nor the class itself (i.e. cls) is passed as an implicit argument. This means that such methods, are not capable of accessing the class itself or its instances.
Now one could argue that static methods are not useful in the context of classes as they can also be placed in helper modules instead of adding them as members of the class. In object oriented programming, it is important to structure your classes into logical chunks and thus, static methods are quite useful when we need to add a method under a class simply because it logically belongs to the class.
In our example, the static method named get_employee_legal_obligations_txt simply returns a string that contains the legal obligations of every single employee of a company. This function, does not interact with the class itself nor with any instance. It could have been placed into a different helper module however, it is only relevant to this class and therefore we have to place it under the Employee class.
A static method can be access directly from the class itself
print(Employee.get_employee_legal_obligations_txt())
1. An employee must complete 8 hours per working day
2. ...
or from an instance of the class:
employee_1 = Employee('Andrew', 'Brown', 85000)
print(employee_1.get_employee_legal_obligations_txt())
1. An employee must complete 8 hours per working day
2. ...
References
*
*What's the difference between static and class methods in Python?
A: Another consideration with respect to staticmethod vs classmethod comes up with inheritance. Say you have the following class:
class Foo(object):
@staticmethod
def bar():
return "In Foo"
And you then want to override bar() in a child class:
class Foo2(Foo):
@staticmethod
def bar():
return "In Foo2"
This works, but note that now the bar() implementation in the child class (Foo2) can no longer take advantage of anything specific to that class. For example, say Foo2 had a method called magic() that you want to use in the Foo2 implementation of bar():
class Foo2(Foo):
@staticmethod
def bar():
return "In Foo2"
@staticmethod
def magic():
return "Something useful you'd like to use in bar, but now can't"
The workaround here would be to call Foo2.magic() in bar(), but then you're repeating yourself (if the name of Foo2 changes, you'll have to remember to update that bar() method).
To me, this is a slight violation of the open/closed principle, since a decision made in Foo is impacting your ability to refactor common code in a derived class (ie it's less open to extension). If bar() were a classmethod we'd be fine:
class Foo(object):
@classmethod
def bar(cls):
return "In Foo"
class Foo2(Foo):
@classmethod
def bar(cls):
return "In Foo2 " + cls.magic()
@classmethod
def magic(cls):
return "MAGIC"
print Foo2().bar()
Gives: In Foo2 MAGIC
Also: historical note: Guido Van Rossum (Python's creator) once referred to staticmethod's as "an accident": https://mail.python.org/pipermail/python-ideas/2012-May/014969.html
we all know how limited static methods are. (They're basically an accident -- back in the Python 2.2 days when I was inventing new-style classes and descriptors, I meant to implement class methods but at first I didn't understand them and accidentally implemented static methods first. Then it was too late to remove them and only provide class methods.
Also: https://mail.python.org/pipermail/python-ideas/2016-July/041189.html
Honestly, staticmethod was something of a mistake -- I was trying to do something like Java class methods but once it was released I found what was really needed was classmethod. But it was too late to get rid of staticmethod.
A: The definitive guide on how to use static, class or abstract methods in Python is one good link for this topic, and summary it as following.
@staticmethod function is nothing more than a function defined inside a class. It is callable without instantiating the class first. It’s definition is immutable via inheritance.
*
*Python does not have to instantiate a bound-method for object.
*It eases the readability of the code, and it does not depend on the state of object itself;
@classmethod function also callable without instantiating the class, but its definition follows Sub class, not Parent class, via inheritance, can be overridden by subclass. That’s because the first argument for @classmethod function must always be cls (class).
*
*Factory methods, that are used to create an instance for a class using for example some sort of pre-processing.
*Static methods calling static methods: if you split a static methods in several static methods, you shouldn't hard-code the class name but use class methods
A: Basically @classmethod makes a method whose first argument is the class it's called from (rather than the class instance), @staticmethod does not have any implicit arguments.
A: To decide whether to use @staticmethod or @classmethod you have to look inside your method. If your method accesses other variables/methods in your class then use @classmethod. On the other hand, if your method does not touches any other parts of the class then use @staticmethod.
class Apple:
_counter = 0
@staticmethod
def about_apple():
print('Apple is good for you.')
# note you can still access other member of the class
# but you have to use the class instance
# which is not very nice, because you have repeat yourself
#
# For example:
# @staticmethod
# print('Number of apples have been juiced: %s' % Apple._counter)
#
# @classmethod
# print('Number of apples have been juiced: %s' % cls._counter)
#
# @classmethod is especially useful when you move your function to another class,
# you don't have to rename the referenced class
@classmethod
def make_apple_juice(cls, number_of_apples):
print('Making juice:')
for i in range(number_of_apples):
cls._juice_this(i)
@classmethod
def _juice_this(cls, apple):
print('Juicing apple %d...' % apple)
cls._counter += 1
A: I will try to explain the basic difference using an example.
class A(object):
x = 0
def say_hi(self):
pass
@staticmethod
def say_hi_static():
pass
@classmethod
def say_hi_class(cls):
pass
def run_self(self):
self.x += 1
print self.x # outputs 1
self.say_hi()
self.say_hi_static()
self.say_hi_class()
@staticmethod
def run_static():
print A.x # outputs 0
# A.say_hi() # wrong
A.say_hi_static()
A.say_hi_class()
@classmethod
def run_class(cls):
print cls.x # outputs 0
# cls.say_hi() # wrong
cls.say_hi_static()
cls.say_hi_class()
1 - we can directly call static and classmethods without initializing
# A.run_self() # wrong
A.run_static()
A.run_class()
2- Static method cannot call self method but can call other static and classmethod
3- Static method belong to class and will not use object at all.
4- Class method are not bound to an object but to a class.
A: Official python docs:
@classmethod
A class method receives the class as
implicit first argument, just like an
instance method receives the instance.
To declare a class method, use this
idiom:
class C:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function
decorator – see the description of
function definitions in Function
definitions for details.
It can be called either on the class
(such as C.f()) or on an instance
(such as C().f()). The instance is
ignored except for its class. If a
class method is called for a derived
class, the derived class object is
passed as the implied first argument.
Class methods are different than C++
or Java static methods. If you want
those, see staticmethod() in this
section.
@staticmethod
A static method does not receive an
implicit first argument. To declare a
static method, use this idiom:
class C:
@staticmethod
def f(arg1, arg2, ...): ...
The @staticmethod form is a function
decorator – see the description of
function definitions in Function
definitions for details.
It can be called either on the class
(such as C.f()) or on an instance
(such as C().f()). The instance is
ignored except for its class.
Static methods in Python are similar
to those found in Java or C++. For a
more advanced concept, see
classmethod() in this section.
A: Python comes with several built-in decorators. The big three are:
@classmethod
@staticmethod
@property
First let's note that any function of a class can be called with instance of this class (after we initialized this class).
@classmethod is the way to call function not only as an instance of a class but also directly by the class itself as its first argument.
@staticmethod is a way of putting a function into a class (because it logically belongs there), while indicating that it does not require access to the class (so we don't need to use self in function definition).
Let's consider the following class:
class DecoratorTest(object):
def __init__(self):
pass
def doubler(self, x):
return x*2
@classmethod
def class_doubler(cls, x): # we need to use 'cls' instead of 'self'; 'cls' reference to the class instead of an instance of the class
return x*2
@staticmethod
def static_doubler(x): # no need adding 'self' here; static_doubler() could be just a function not inside the class
return x*2
Let's see how it works:
decor = DecoratorTest()
print(decor.doubler(5))
# 10
print(decor.class_doubler(5)) # a call with an instance of a class
# 10
print(DecoratorTest.class_doubler(5)) # a direct call by the class itself
# 10
# staticmethod could be called in the same way as classmethod.
print(decor.static_doubler(5)) # as an instance of the class
# 10
print(DecoratorTest.static_doubler(5)) # or as a direct call
# 10
Here you can see some use cases for those methods.
Bonus: you can read about @property decorator here
A: The difference occurs when there is inheritance.
Suppose that there are two classes-- Parent and Child. If one wants to use @staticmethod, print_name method should be written twice because the name of the class should be written in the print line.
class Parent:
_class_name = "Parent"
@staticmethod
def print_name():
print(Parent._class_name)
class Child(Parent):
_class_name = "Child"
@staticmethod
def print_name():
print(Child._class_name)
Parent.print_name()
Child.print_name()
However, for @classmethod, it is not required to write print_name method twice.
class Parent:
_class_name = "Parent"
@classmethod
def print_name(cls):
print(cls._class_name)
class Child(Parent):
_class_name = "Child"
Parent.print_name()
Child.print_name()
A: Instance Method:
+ Can modify object instance state
+ Can modify class state
Class Method:
- Can't modify object instance state
+ Can modify class state
Static Method:
- Can't modify object instance state
- Can't modify class state
class MyClass:
'''
Instance method has a mandatory first attribute self which represent the instance itself.
Instance method must be called by a instantiated instance.
'''
def method(self):
return 'instance method called', self
'''
Class method has a mandatory first attribute cls which represent the class itself.
Class method can be called by an instance or by the class directly.
Its most common using scenario is to define a factory method.
'''
@classmethod
def class_method(cls):
return 'class method called', cls
'''
Static method doesn’t have any attributes of instances or the class.
It also can be called by an instance or by the class directly.
Its most common using scenario is to define some helper or utility functions which are closely relative to the class.
'''
@staticmethod
def static_method():
return 'static method called'
obj = MyClass()
print(obj.method())
print(obj.class_method()) # MyClass.class_method()
print(obj.static_method()) # MyClass.static_method()
output:
('instance method called', <__main__.MyClass object at 0x100fb3940>)
('class method called', <class '__main__.MyClass'>)
static method called
The instance method we actually had access to the object instance , right so this was an instance off a my class object whereas with the class method we have access to the class itself. But not to any of the objects, because the class method doesn't really care about an object existing. However you can both call a class method and static method on an object instance. This is going to work it doesn't really make a difference, so again when you call static method here it's going to work and it's going to know which method you want to call.
The Static methods are used to do some utility tasks, and class methods are used for factory methods. The factory methods can return class objects for different use cases.
And finally, a short example for better understanding:
class Student:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@classmethod
def get_from_string(cls, name_string: str):
first_name, last_name = name_string.split()
if Student.validate_name(first_name) and Student.validate_name(last_name):
return cls(first_name, last_name)
else:
print('Invalid Names')
@staticmethod
def validate_name(name):
return len(name) <= 10
stackoverflow_student = Student.get_from_string('Name Surname')
print(stackoverflow_student.first_name) # Name
print(stackoverflow_student.last_name) # Surname
A: staticmethod has no access to attibutes of the object, of the class, or of parent classes in the inheritance hierarchy.
It can be called at the class directly (without creating an object).
classmethod has no access to attributes of the object. It however can access attributes of the class and of parent classes in the inheritance hierarchy.
It can be called at the class directly (without creating an object). If called at the object then it is the same as normal method which doesn't access self.<attribute(s)> and accesses self.__class__.<attribute(s)> only.
Think we have a class with b=2, we will create an object and re-set this to b=4 in it.
Staticmethod cannot access nothing from previous.
Classmethod can access .b==2 only, via cls.b.
Normal method can access both: .b==4 via self.b and .b==2 via self.__class__.b.
We could follow the KISS style (keep it simple, stupid): Don't use staticmethods and classmethods, don't use classes without instantiating them, access only the object's attributes self.attribute(s). There are languages where the OOP is implemented that way and I think it is not bad idea. :)
A: Definition of static method and class method from it's documentation. and When to use static method and when to use class method.
*
*Static method are like static method in java and C#, it won't use any initialize value of the class, all it need from outside to work fine.
*class method: are generally used for inheritance override, when we over-ride a method, and then we use CLS instance to tell if we want to call method of child or parent class. in case you want to use both the methods with same name and different signature.
staticmethod(function) -> method
Convert a function to be a static method.
A static method does not receive an implicit first argument.
To declare a static method, use this idiom:
class C:
@staticmethod
def f(arg1, arg2, ...):
...
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.
Static methods in Python are similar to those found in Java or C++.
For a more advanced concept, see the classmethod builtin.
"""
classmethod(function) -> method
Convert a function to be a class method.
A class method receives the class as implicit first argument,
just like an instance method receives the instance.
To declare a class method, use this idiom:
class C:
@classmethod
def f(cls, arg1, arg2, ...):
...
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()). The instance is ignored except for its class.
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.
Class methods are different than C++ or Java static methods.
If you want those, see the staticmethod builtin.
A: I'd like to add on top of all the previous answers the following, which is not official, but adheres to standards.
First of all you can look at always giving the least amount of privilege necessary. So if you don't need something specific to the instance, make it a class method. If you don't need something specific to the class, make it a static method.
Second thing is consider what you can communicate by the type of method that you make it. Static Method - helper function meant to be used outside of the class itself. Class function - can be called without instantiation however is meant to be used with that class only - otherwise would've been a static method ! Instance method - meant to be used only by instances.
This can help you in communicating patterns and how your code should be used.
class Foo:
@classmethod
def bar(cls, id: int = None):
query = session.query(
a.id,
a.name,
a.address,
)
if id is not None:
query = query.filter(a.id == id)
return query
For example the above -- there is no reason why the method bar could not be static. However by making it a class method you communicate that it should be used by the class itself, as opposed it being a helper function meant to be used elsewhere !
Remember the above is not official, rather my personal preference
A: @classmethod:
*
*can call class variables and instance, class and static methods both by cls and directly by class name but not instance variables.
*can be called both by object and directly by class name.
*needs cls for the 1st argument otherwise @classmethod cannot be called and the name of cls is used in convention so other names instead of cls still work.
@staticmethod:
*
*can be called both by an object and directly by class name.
*can call class variables and instance, class and static methods directly by class name but not instance variables.
*doesn't need self or cls.
*In detail, I also explain about instance method in my answer for What is an "instance method" in Python?
@classmethod:
For example, @classmethod can call the class variable and the instance, class and static methods both by cls and directly by class name and @classmethod can be called both by object and directly by class name as shown below:
class Person:
x = "Hello"
def __init__(self, name):
self.name = name
@classmethod # Here
def test1(cls):
print(cls.x) # Class variable by `cls`
cls.test2(cls) # Instance method by `cls`
cls.test3() # Class method by `cls`
cls.test4() # Static method by `cls`
print()
print(Person.x) # Class variable by class name
Person.test2("Test2") # Instance method by class name
Person.test3() # Class method by class name
Person.test4() # Static method by class name
def test2(self):
print("Test2")
@classmethod
def test3(cls):
print("Test3")
@staticmethod
def test4():
print("Test4")
obj = Person("John")
obj.test1() # By object
# Or
Person.test1() # By class name
Output:
Hello
Test2
Test3
Test4
Hello
Test2
Test3
Test4
And, @classmethod cannot call instance variables both by cls and directly by class name so if @classmethod tries to call the instance variable both by cls and directly by class name as shown below:
# ...
@classmethod
def test1(cls):
print(cls.name) # Instance variable by `cls`
# Or
print(Person.name) # Instance variable by class name
# ...
obj = Person("John")
obj.test1()
# Or
Person.test1()
The error below occurs:
AttributeError: type object 'Person' has no attribute 'name'
And, if @classmethod doesn't have cls:
# ...
@classmethod
def test1(): # Without "cls"
print("Test1")
# ...
obj = Person("John")
obj.test1()
# Or
Person.test1()
@classmethod cannot be called, then the error below occurs as shown below:
TypeError: test1() takes 0 positional arguments but 1 was given
And, the name of cls is used in convention so other name instead of cls still work as shown below:
# ...
@classmethod
def test1(orange):
print(orange.x) # Class variable
orange.test2(orange) # Instance method
orange.test3() # Class method
orange.test4() # Static method
# ...
obj = Person("John")
obj.test1()
# Or
Person.test1()
Output:
Hello
Test2
Test3
Test4
@staticmethod:
For example, @staticmethod can be called both by object and directly by class name as shown below:
class Person:
x = "Hello"
def __init__(self, name):
self.name = name
@staticmethod # Here
def test1():
print("Test1")
def test2(self):
print("Test2")
@classmethod
def test3(cls):
print("Test3")
@staticmethod
def test4():
print("Test4")
obj = Person("John")
obj.test1() # By object
# Or
Person.test1() # By class name
Output:
Test1
And, @staticmethod can call the class variable and the instance, class and static methods directly by class name but not instance variable as shown below:
# ...
@staticmethod
def test1():
print(Person.x) # Class variable
Person.test2("Test2") # Instance method
Person.test3() # Class method
Person.test4() # Static method
# ...
obj = Person("John")
obj.test1()
# Or
Person.test1()
Output:
Hello
Test2
Test3
Test4
And, if @staticmethod tries to call the instance variable as shown below:
# ...
@staticmethod
def test1():
print(Person.name) # Instance variable
# ...
obj = Person("John")
obj.test1()
# Or
Person.test1()
The error below occurs:
AttributeError: type object 'Person' has no attribute 'name'
And, @staticmethod doesn't need self or cls so if @staticmethod has self or cls, you need to pass an argument as shown below:
# ...
@staticmethod
def test1(self): # With "self"
print(self)
# Or
@staticmethod
def test1(cls): # With "cls"
print(cls)
# ...
obj = Person("John")
obj.test1("Test1") # With an argument
# Or
Person.test1("Test1") # With an argument
Output:
Test1
Otherwise, if you don't pass an argument as shown below:
# ...
@staticmethod
def test1(self): # With "self"
print("Test1")
# Or
@staticmethod
def test1(cls): # With "cls"
print("Test1")
# ...
obj = Person("John")
obj.test1() # Without an argument
# Or
Person.test1() # Without an argument
These errors below occur:
TypeError: test1() missing 1 required positional argument: 'self'
TypeError: test1() missing 1 required positional argument: 'cls'
A: A quick hack-up ofotherwise identical methods in iPython reveals that @staticmethod yields marginal performance gains (in the nanoseconds), but otherwise it seems to serve no function. Also, any performance gains will probably be wiped out by the additional work of processing the method through staticmethod() during compilation (which happens prior to any code execution when you run a script).
For the sake of code readability I'd avoid @staticmethod unless your method will be used for loads of work, where the nanoseconds count.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4504"
}
|
Q: Grails 1.0.3 console reports 'premature end of file' Browsing to a dynamic web page built using Grails version 1.0.3 the console log shows the following errors for each page request:
[Fatal Error] :-1:-1: Premature end of file.
How do I stop this error from appearing for each request?
A: The log entry occurs when http requests are made from Firefox 3 browsers.
The workaround on Grails 1.0.3 is to open Config.groovy in your project and find the following:
grails.mime.types = [ html: ['text/html','application/xhtml+xml'],
xml: ['text/xml', 'application/xml'], ...
The second line above, pertaining to xml should be removed.
This is a GRAILS 1.0.3 bug that has been resolved, see http://jira.codehaus.org/browse/GRAILS-3088 for full details.
A: This bug was already fixed:
http://jira.codehaus.org/browse/GRAILS-3088
Premature end of file
Affects Version/s: 1.0.3
Fix Version/s: 1.0.4
...Just a few implementation notes. We were defaulting to a q value of 0, which is incorrect according to the spec. So we now default to 1.0 which gives the correct precedence order in Firefox 3, but incorrect in Firefox 2. However, more specific XML types like application/xhtml+xml now take precendence over less specific ones if they have the same q value so this fixes the issue in Firefox 2...
A: Upgrading to a 1.0.4 snapshot is probably the best way to deal with this issue. Check out the instructions under "Grails Development Builds" at the Grails Download page.
It can also be ignored without too much difficulty.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why won't Visual Studio 2005 generate an Xml Serialization assembly? Why isn't Visual Studio 2005 generating a serialization setting when I set the project setting "Generate Serialization Assembly" to "On"?
A: It turns out that Dev Studio only honors this setting for Web Services.
For non-web services you can get this to work by adding an AfterBuild target to your project file:
<Target Name="AfterBuild" DependsOnTargets="AssignTargetPaths;Compile;ResolveKeySource" Inputs="$(MSBuildAllProjects);@(IntermediateAssembly)" Outputs="$(OutputPath)$(_SGenDllName)">
<SGen BuildAssemblyName="$(TargetFileName)" BuildAssemblyPath="$(OutputPath)" References="@(ReferencePath)" ShouldGenerateSerializer="true" UseProxyTypes="false" KeyContainer="$(KeyContainerName)" KeyFile="$(KeyOriginatorFile)" DelaySign="$(DelaySign)" ToolPath="$(SGenToolPath)">
<Output TaskParameter="SerializationAssembly" ItemName="SerializationAssembly" />
</SGen>
</Target>
See also:
*
*SGen MSBuild Task
*AfterBuild Event
A: It can be done manually with sgen.exe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Windows Forms: How do you change the font color for a disabled label I am trying to set the disabled font characteristics for a Label Control. I can set all of the Font characteristics (size, bold, etc), but the color is overridden by the default windows behavior which seems to be one of these two colors:
*
*If background color is transparent then ForeColor is same as TextBox disabled Color.
*If background color is set to anything else, ForeColor is a Dark Gray color.
The image below demonstrates the behavior -- Column 1 is Labels, Column 2 is TextBoxs, and Column 3 is ComboBoxes.
Edit -- Explaining the image: The first two rows are default styles for a label, textbox, and combobox. In the second two rows, I set the Background color to Red and Foreground to White. The disabled font style handling by Microsoft is inconsistent.
A: Have you tried implementing the EnabledChanged event? Or are you looking for more of a "styles" property on the control (as far as I know, they don't exist)?
A: For the textbox, you can set the readonly property to true while keeping the control enabled. You can then set the BackColor and ForeColor property to whatever you like. The user will still be able to click on the control and have a blinking cursor, but they won't be able to edit anything.
Not sure if this extrapolates out to other control types like combo boxes or whatnot as I haven't had a chance to experiment yet, but it's worth a shot.
A: Take a look at the ControlPaint.DrawStringDisabled method; it might be something helpful. I've used it when overriding the OnPaint event for custom controls.
ControlPaint.DrawStringDisabled(g, this.Text, this.Font, Color.Transparent,
new Rectangle(CustomStringWidth, 5, StringSize2.Width, StringSize2.Height), StringFormat.GenericTypographic);
A: Why is this an issue?
I would personally let windows handle it. People are used to disabled items looking a certain way, so if you start trying to change every aspect of the way they look, you might start confusing your users.
A: You will probably need to override the Paint event. All toolkits I've used so far have the same problem when the control is disabled. Just guess they let windows do the drawing of the text. As for the labels, well they are not an standard control, and that's why they are working.
A: I overrode the OnPaint method of my control with the OnPaint method below. I pasted the entire control class to make it easy to copy.
public partial class NewLabel : Label
{
public NewLabel()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs e)
{
TextRenderer.DrawText(e.Graphics, this.Text.ToString(), this.Font, ClientRectangle, ForeColor);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Better Way of Manipulating RichText in C#? I need to create and copy to the clipboard some RichText with standard "formatting" like bold/italics, indents and the like. The way I'm doing it now seems kind of inelegant... I'm creating a RichTextBox item and applying my formatting through that like so:
RichTextBox rtb = new RichTextBox();
Font boldfont = new Font("Times New Roman", 10, FontStyle.Bold);
rtb.Text = "sometext";
rtb.SelectAll()
rtb.SelectionFont = boldfont;
rtb.SelectionIndent = 12;
There has got to be a better way, but after a few hours of searching I was unable to come up with anything better. Any ideas?
Edit:
The RichTextBox (rtb) is not displayed/drawn anywhere on a form. I'm just using the object to format my RichText.
A: You may want to suspend the layout of the richtextbox before you do all of that, to avoid unecessary flicker. That's one of the common mistakes I used to make which made it seem "inelegant"
A: I think your technique is a great way to accomplish what you're looking to do. I know what you mean...it feels kind of "dirty" because you're using a Winforms control for something other than it was intended for, but it just works. I've used this technique for years. Interested to see if anyone else has viable options.
A: Is this project helpful?
http://www.codeproject.com/KB/string/nrtftree.aspx
A: You could create some utility extension methods to make it more 'elegant' :)
public static RichTextBox Set(this RichTextBox rtb, Font font, string text)
{
rtb.Text = text;
rtb.SelectAll();
rtb.SelectionFont = font;
rtb.SelectionIndent = 12;
return rtb;
}
And call like this:
someRtb.Set(yourFont, "The Text").AndThenYouCanAddMoreAndCHainThem();
Edit: I see now that you are not even displaying it. Hrm, interesting, sorry i wasnt of much help with providing a Non Rtb way.
A: You should also suspend the layout of the richtextbox just after creation and dispose it after use.
RichTextBox rtb = new RichTextBox();
rtb.SuspendLayout();
//richtext processing goes here...
rtb.Dispose();
And don't be shy to use richtextbox for richtext processing. Microsoft itself is doing this here in this tutorial. :-)
A: I know it's been a while, but check out this stackoverflow post on converting rtf to html. It would probably be way easier to get your stuff into html, manipulate it, then either display it using html or convert it back to rtf.
Convert Rtf to HTML
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: ASP.NET Custom Controls - Rendering Image from a Pool of Images at Design Time I have been working on a ImageRotator control and finished weeding out any oddities with it tonight, and it works great. However, there is one thing that is bugging me with it. It doesn't display anything at design time (I just get the image placeholder).
I have been Googling, and came across a good article from Rick Strahl (as always), and this works great for single images, where the path is explicit.
However, the ImageRotator will actually just take a path to a folder and scan that, and loop through those. Currently this doesnt work at design time because the image "pooling" doesn't work (I am thinking its because the designer doesn't give permission to the code to scan the filesystem).
So, can this be done? Would it be possible to implement a custom designer for the control and elevate permissions (or something) there?
Update Following Some Pondering While Sipping Tea (How Very British of Me!)
Would it be possible to create a Designer for the control, create an image, encode it to base64 and stick that in the code base and render it?
This way I wouldn't need to give a crap about the images in the pool because I would have my own ^_^
(Although grabbing and image from the pool would be nicer since, well, thats what the user has selected right?).
A: Hey Rick Stranl also has a post here that describes detecting design time. If its in design time just give it a fixed image from the pool. For example, alays take the first one or osmething like that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Regular expression to test whether a string consists of a valid real number in base 10 Examples:
"1" yes
"-1" yes
"- 3" no
"1.2" yes
"1.2.3" no
"7e4" no (though in some cases you may want to allow scientific notation)
".123" yes
"123." yes
"." no
"-.5" yes
"007" yes
"00" yes
A: This allows for optional "+" and "-" in front. And allows trailing or initial whitespace.
/^\s*[+-]?(?:\d+\.?\d*|\d*\.\d+)\s*$/
A: There are several alternatives. First, using a zero-width look-ahead assertion allows you to make the rest of the regex simpler:
/^[-+]?(?=\.?\d)\d*(?:\.\d*)?$/
If you want to avoid the look-ahead, then I'd try to discourage the regex from back-tracking:
/^[-+]?(?:\.\d+|\d+(?:\.\d*)?)$/
/^[-+]?(\.\d+|\d+(\.\d*)?)$/ # if you don't mind capturing parens
Note that you said "base 10" so you might actually want to disallow extra leading zeros since "014" might be meant to be octal:
/^[-+]?(?:\.\d+|(?:0|[1-9]\d*)(?:\.\d*)?)$/
/^[-+]?(\.\d+|(0|[1-9]\d*)(\.\d*)?)$/
Finally, you might want to replace \d with [0-9] since some regexes don't support \d or because some regexes allow \d to match Unicode "digits" other than 0..9 such as "ARABIC-INDIC DIGIT"s.
/^[-+]?(?:\.[0-9]+|(?:0|[1-9][0-9]*)(?:\.[0-9]*)?)$/
/^[-+]?(\.[0-9]+|(0|[1-9][0-9]*)(\.[0-9]*)?)$/
A: Matches all specified examples, doesn't capture any groups:
^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$
To not match "1." (etc):
^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$
Doesn't bother with whitespace (use a trim function).
A: The regular expression in perlfaq4: How do I determine whether a scalar is a number/whole/integer/float? does what you want, and it handles the "e" notation too.
while( <DATA> )
{
chomp;
print /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/ ?
"$_ Works\n"
:
"$_ Fails\n"
;
}
__DATA__
1
-1
- 3
1.2
1.2.3
7e4
.123
123.
.
-.5
A: Depending on the language you are coding in this functionality may already exist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Visual Studio 2008 Properties Window SLOW Even after all the hotfixes and updates that are supposed to fix this, my properties window in Visual Studio 2008 is still SLOW! What happens is a click on a table cell or something similar in the web editor, and regardless of the size of the page I'm working on, it takes a second or two for the properties window to show the properties for the selected item.
The most annoying thing about it is sometimes I'll click a cell, select a property and start typing, but it's still stuck on the wrong (unselected) item, so it ends up putting what I'm typing in the wrong place, and then it disappears once the proper item is selected.
Like I said, I'm running with all available hotfixes and service packs. Anyone run into this and had any luck fixing it?
A: I think I figured out the problem I was having - I turned off the startup page, and disabled the startup page refresh option (where it checks for latest content every 60 minutes or whatever), so that now when I load the environment, it just shows a blank page.
I have no idea why this would relate to the amount of time it takes an item selected in the HTML designer to appear in the properties window, but evidently the two things are connected.
A: Turn off all animation.
A: Didn't work - even with animation off, the property page is slow to switch to the new selected object. For instance, if you are inside a table and it is showing the properties, when you hit "Escape" so that the parent table is selected, it takes 2-3 seconds for the properties of the parent table to appear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get last n lines of a file, similar to tail I'm writing a log file viewer for a web application and for that I want to paginate through the lines of the log file. The items in the file are line based with the newest item at the bottom.
So I need a tail() method that can read n lines from the bottom and support an offset. This is hat I came up with:
def tail(f, n, offset=0):
"""Reads a n lines from f with an offset of offset lines."""
avg_line_length = 74
to_read = n + offset
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None]
avg_line_length *= 1.3
Is this a reasonable approach? What is the recommended way to tail log files with offsets?
A: Assumes a unix-like system on Python 2 you can do:
import os
def tail(f, n, offset=0):
stdin,stdout = os.popen2("tail -n "+n+offset+" "+f)
stdin.close()
lines = stdout.readlines(); stdout.close()
return lines[:,-offset]
For python 3 you may do:
import subprocess
def tail(f, n, offset=0):
proc = subprocess.Popen(['tail', '-n', n + offset, f], stdout=subprocess.PIPE)
lines = proc.stdout.readlines()
return lines[:, -offset]
A: Update @papercrane solution to python3.
Open the file with open(filename, 'rb') and:
def tail(f, window=20):
"""Returns the last `window` lines of file `f` as a list.
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
remaining_bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and remaining_bytes > 0:
if remaining_bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
bunch = f.read(BUFSIZ)
else:
# file too small, start from beginning
f.seek(0, 0)
# only read what was not read
bunch = f.read(remaining_bytes)
bunch = bunch.decode('utf-8')
data.insert(0, bunch)
size -= bunch.count('\n')
remaining_bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:]
A: The simplest way is to use deque:
from collections import deque
def tail(filename, n=10):
with open(filename) as f:
return deque(f, n)
A: Posting an answer at the behest of commenters on my answer to a similar question where the same technique was used to mutate the last line of a file, not just get it.
For a file of significant size, mmap is the best way to do this. To improve on the existing mmap answer, this version is portable between Windows and Linux, and should run faster (though it won't work without some modifications on 32 bit Python with files in the GB range, see the other answer for hints on handling this, and for modifying to work on Python 2).
import io # Gets consistent version of open for both Py2.7 and Py3.x
import itertools
import mmap
def skip_back_lines(mm, numlines, startidx):
'''Factored out to simplify handling of n and offset'''
for _ in itertools.repeat(None, numlines):
startidx = mm.rfind(b'\n', 0, startidx)
if startidx < 0:
break
return startidx
def tail(f, n, offset=0):
# Reopen file in binary mode
with io.open(f.name, 'rb') as binf, mmap.mmap(binf.fileno(), 0, access=mmap.ACCESS_READ) as mm:
# len(mm) - 1 handles files ending w/newline by getting the prior line
startofline = skip_back_lines(mm, offset, len(mm) - 1)
if startofline < 0:
return [] # Offset lines consumed whole file, nothing to return
# If using a generator function (yield-ing, see below),
# this should be a plain return, no empty list
endoflines = startofline + 1 # Slice end to omit offset lines
# Find start of lines to capture (add 1 to move from newline to beginning of following line)
startofline = skip_back_lines(mm, n, startofline) + 1
# Passing True to splitlines makes it return the list of lines without
# removing the trailing newline (if any), so list mimics f.readlines()
return mm[startofline:endoflines].splitlines(True)
# If Windows style \r\n newlines need to be normalized to \n, and input
# is ASCII compatible, can normalize newlines with:
# return mm[startofline:endoflines].replace(os.linesep.encode('ascii'), b'\n').splitlines(True)
This assumes the number of lines tailed is small enough you can safely read them all into memory at once; you could also make this a generator function and manually read a line at a time by replacing the final line with:
mm.seek(startofline)
# Call mm.readline n times, or until EOF, whichever comes first
# Python 3.2 and earlier:
for line in itertools.islice(iter(mm.readline, b''), n):
yield line
# 3.3+:
yield from itertools.islice(iter(mm.readline, b''), n)
Lastly, this read in binary mode (necessary to use mmap) so it gives str lines (Py2) and bytes lines (Py3); if you want unicode (Py2) or str (Py3), the iterative approach could be tweaked to decode for you and/or fix newlines:
lines = itertools.islice(iter(mm.readline, b''), n)
if f.encoding: # Decode if the passed file was opened with a specific encoding
lines = (line.decode(f.encoding) for line in lines)
if 'b' not in f.mode: # Fix line breaks if passed file opened in text mode
lines = (line.replace(os.linesep, '\n') for line in lines)
# Python 3.2 and earlier:
for line in lines:
yield line
# 3.3+:
yield from lines
Note: I typed this all up on a machine where I lack access to Python to test. Please let me know if I typoed anything; this was similar enough to my other answer that I think it should work, but the tweaks (e.g. handling an offset) could lead to subtle errors. Please let me know in the comments if there are any mistakes.
A: Here is my answer. Pure python. Using timeit it seems pretty fast. Tailing 100 lines of a log file that has 100,000 lines:
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10)
0.0014600753784179688
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100)
0.00899195671081543
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=1000)
0.05842900276184082
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=10000)
0.5394978523254395
>>> timeit.timeit('tail.tail(f, 100, 4098)', 'import tail; f = open("log.txt", "r");', number=100000)
5.377126932144165
Here is the code:
import os
def tail(f, lines=1, _buffer=4098):
"""Tail a file and get X lines from the end"""
# place holder for the lines found
lines_found = []
# block counter will be multiplied by buffer
# to get the block size from the end
block_counter = -1
# loop until we find X lines
while len(lines_found) < lines:
try:
f.seek(block_counter * _buffer, os.SEEK_END)
except IOError: # either file is too small, or too many lines requested
f.seek(0)
lines_found = f.readlines()
break
lines_found = f.readlines()
# we found enough lines, get out
# Removed this line because it was redundant the while will catch
# it, I left it for history
# if len(lines_found) > lines:
# break
# decrement the block counter to get the
# next X bytes
block_counter -= 1
return lines_found[-lines:]
A: An even cleaner python3 compatible version that doesn't insert but appends & reverses:
def tail(f, window=1):
"""
Returns the last `window` lines of file `f` as a list of bytes.
"""
if window == 0:
return b''
BUFSIZE = 1024
f.seek(0, 2)
end = f.tell()
nlines = window + 1
data = []
while nlines > 0 and end > 0:
i = max(0, end - BUFSIZE)
nread = min(end, BUFSIZE)
f.seek(i)
chunk = f.read(nread)
data.append(chunk)
nlines -= chunk.count(b'\n')
end -= nread
return b'\n'.join(b''.join(reversed(data)).splitlines()[-window:])
use it like this:
with open(path, 'rb') as f:
last_lines = tail(f, 3).decode('utf-8')
A: If reading the whole file is acceptable then use a deque.
from collections import deque
deque(f, maxlen=n)
Prior to 2.6, deques didn't have a maxlen option, but it's easy enough to implement.
import itertools
def maxque(items, size):
items = iter(items)
q = deque(itertools.islice(items, size))
for item in items:
del q[0]
q.append(item)
return q
If it's a requirement to read the file from the end, then use a gallop (a.k.a exponential) search.
def tail(f, n):
assert n >= 0
pos, lines = n+1, []
while len(lines) <= n:
try:
f.seek(-pos, 2)
except IOError:
f.seek(0)
break
finally:
lines = list(f)
pos *= 2
return lines[-n:]
A: Simple :
with open("test.txt") as f:
data = f.readlines()
tail = data[-2:]
print(''.join(tail)
A: S.Lott's answer above almost works for me but ends up giving me partial lines. It turns out that it corrupts data on block boundaries because data holds the read blocks in reversed order. When ''.join(data) is called, the blocks are in the wrong order. This fixes that.
def tail(f, window=20):
"""
Returns the last `window` lines of file `f` as a list.
f - a byte file-like object
"""
if window == 0:
return []
BUFSIZ = 1024
f.seek(0, 2)
bytes = f.tell()
size = window + 1
block = -1
data = []
while size > 0 and bytes > 0:
if bytes - BUFSIZ > 0:
# Seek back one whole BUFSIZ
f.seek(block * BUFSIZ, 2)
# read BUFFER
data.insert(0, f.read(BUFSIZ))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
data.insert(0, f.read(bytes))
linesFound = data[0].count('\n')
size -= linesFound
bytes -= BUFSIZ
block -= 1
return ''.join(data).splitlines()[-window:]
A: The code I ended up using. I think this is the best so far:
def tail(f, n, offset=None):
"""Reads a n lines from f with an offset of offset lines. The return
value is a tuple in the form ``(lines, has_more)`` where `has_more` is
an indicator that is `True` if there are more lines in the file.
"""
avg_line_length = 74
to_read = n + (offset or 0)
while 1:
try:
f.seek(-(avg_line_length * to_read), 2)
except IOError:
# woops. apparently file is smaller than what we want
# to step back, go to the beginning instead
f.seek(0)
pos = f.tell()
lines = f.read().splitlines()
if len(lines) >= to_read or pos == 0:
return lines[-to_read:offset and -offset or None], \
len(lines) > to_read or pos > 0
avg_line_length *= 1.3
A: based on S.Lott's top voted answer (Sep 25 '08 at 21:43), but fixed for small files.
def tail(the_file, lines_2find=20):
the_file.seek(0, 2) #go to end of file
bytes_in_file = the_file.tell()
lines_found, total_bytes_scanned = 0, 0
while lines_2find+1 > lines_found and bytes_in_file > total_bytes_scanned:
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
the_file.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += the_file.read(1024).count('\n')
the_file.seek(-total_bytes_scanned, 2)
line_list = list(the_file.readlines())
return line_list[-lines_2find:]
#we read at least 21 line breaks from the bottom, block by block for speed
#21 to ensure we don't get a half line
Hope this is useful.
A: I found the Popen above to be the best solution. It's quick and dirty and it works
For python 2.6 on Unix machine i used the following
def GetLastNLines(self, n, fileName):
"""
Name: Get LastNLines
Description: Gets last n lines using Unix tail
Output: returns last n lines of a file
Keyword argument:
n -- number of last lines to return
filename -- Name of the file you need to tail into
"""
p = subprocess.Popen(['tail','-n',str(n),self.__fileName], stdout=subprocess.PIPE)
soutput, sinput = p.communicate()
return soutput
soutput will have will contain last n lines of the code. to iterate through soutput line by line do:
for line in GetLastNLines(50,'myfile.log').split('\n'):
print line
A: There are some existing implementations of tail on pypi which you can install using pip:
*
*mtFileUtil
*multitail
*log4tailer
*...
Depending on your situation, there may be advantages to using one of these existing tools.
A: Simple and fast solution with mmap:
import mmap
import os
def tail(filename, n):
"""Returns last n lines from the filename. No exception handling"""
size = os.path.getsize(filename)
with open(filename, "rb") as f:
# for Windows the mmap parameters are different
fm = mmap.mmap(f.fileno(), 0, mmap.MAP_SHARED, mmap.PROT_READ)
try:
for i in xrange(size - 1, -1, -1):
if fm[i] == '\n':
n -= 1
if n == -1:
break
return fm[i + 1 if i else 0:].splitlines()
finally:
fm.close()
A: This may be quicker than yours. Makes no assumptions about line length. Backs through the file one block at a time till it's found the right number of '\n' characters.
def tail( f, lines=20 ):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = [] # blocks of size BLOCK_SIZE, in reverse order starting
# from the end of the file
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
# read the last block we haven't yet read
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
# file too small, start from begining
f.seek(0,0)
# only read what was not read
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count('\n')
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
all_read_text = ''.join(reversed(blocks))
return '\n'.join(all_read_text.splitlines()[-total_lines_wanted:])
I don't like tricky assumptions about line length when -- as a practical matter -- you can never know things like that.
Generally, this will locate the last 20 lines on the first or second pass through the loop. If your 74 character thing is actually accurate, you make the block size 2048 and you'll tail 20 lines almost immediately.
Also, I don't burn a lot of brain calories trying to finesse alignment with physical OS blocks. Using these high-level I/O packages, I doubt you'll see any performance consequence of trying to align on OS block boundaries. If you use lower-level I/O, then you might see a speedup.
UPDATE
for Python 3.2 and up, follow the process on bytes as In text files (those opened without a "b" in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)).:
eg: f = open('C:/.../../apache_logs.txt', 'rb')
def tail(f, lines=20):
total_lines_wanted = lines
BLOCK_SIZE = 1024
f.seek(0, 2)
block_end_byte = f.tell()
lines_to_go = total_lines_wanted
block_number = -1
blocks = []
while lines_to_go > 0 and block_end_byte > 0:
if (block_end_byte - BLOCK_SIZE > 0):
f.seek(block_number*BLOCK_SIZE, 2)
blocks.append(f.read(BLOCK_SIZE))
else:
f.seek(0,0)
blocks.append(f.read(block_end_byte))
lines_found = blocks[-1].count(b'\n')
lines_to_go -= lines_found
block_end_byte -= BLOCK_SIZE
block_number -= 1
all_read_text = b''.join(reversed(blocks))
return b'\n'.join(all_read_text.splitlines()[-total_lines_wanted:])
A: For efficiency with very large files (common in logfile situations where you may want to use tail), you generally want to avoid reading the whole file (even if you do do it without reading the whole file into memory at once) However, you do need to somehow work out the offset in lines rather than characters. One possibility is reading backwards with seek() char by char, but this is very slow. Instead, its better to process in larger blocks.
I've a utility function I wrote a while ago to read files backwards that can be used here.
import os, itertools
def rblocks(f, blocksize=4096):
"""Read file as series of blocks from end of file to start.
The data itself is in normal order, only the order of the blocks is reversed.
ie. "hello world" -> ["ld","wor", "lo ", "hel"]
Note that the file must be opened in binary mode.
"""
if 'b' not in f.mode.lower():
raise Exception("File must be opened using binary mode.")
size = os.stat(f.name).st_size
fullblocks, lastblock = divmod(size, blocksize)
# The first(end of file) block will be short, since this leaves
# the rest aligned on a blocksize boundary. This may be more
# efficient than having the last (first in file) block be short
f.seek(-lastblock,2)
yield f.read(lastblock)
for i in range(fullblocks-1,-1, -1):
f.seek(i * blocksize)
yield f.read(blocksize)
def tail(f, nlines):
buf = ''
result = []
for block in rblocks(f):
buf = block + buf
lines = buf.splitlines()
# Return all lines except the first (since may be partial)
if lines:
result.extend(lines[1:]) # First line may not be complete
if(len(result) >= nlines):
return result[-nlines:]
buf = lines[0]
return ([buf]+result)[-nlines:]
f=open('file_to_tail.txt','rb')
for line in tail(f, 20):
print line
[Edit] Added more specific version (avoids need to reverse twice)
A: you can go to the end of your file with f.seek(0, 2) and then read off lines one by one with the following replacement for readline():
def readline_backwards(self, f):
backline = ''
last = ''
while not last == '\n':
backline = last + backline
if f.tell() <= 0:
return backline
f.seek(-1, 1)
last = f.read(1)
f.seek(-1, 1)
backline = last
last = ''
while not last == '\n':
backline = last + backline
if f.tell() <= 0:
return backline
f.seek(-1, 1)
last = f.read(1)
f.seek(-1, 1)
f.seek(1, 1)
return backline
A: Based on Eyecue answer (Jun 10 '10 at 21:28): this class add head() and tail() method to file object.
class File(file):
def head(self, lines_2find=1):
self.seek(0) #Rewind file
return [self.next() for x in xrange(lines_2find)]
def tail(self, lines_2find=1):
self.seek(0, 2) #go to end of file
bytes_in_file = self.tell()
lines_found, total_bytes_scanned = 0, 0
while (lines_2find+1 > lines_found and
bytes_in_file > total_bytes_scanned):
byte_block = min(1024, bytes_in_file-total_bytes_scanned)
self.seek(-(byte_block+total_bytes_scanned), 2)
total_bytes_scanned += byte_block
lines_found += self.read(1024).count('\n')
self.seek(-total_bytes_scanned, 2)
line_list = list(self.readlines())
return line_list[-lines_2find:]
Usage:
f = File('path/to/file', 'r')
f.head(3)
f.tail(3)
A: Several of these solutions have issues if the file doesn't end in \n or in ensuring the complete first line is read.
def tail(file, n=1, bs=1024):
f = open(file)
f.seek(-1,2)
l = 1-f.read(1).count('\n') # If file doesn't end in \n, count it anyway.
B = f.tell()
while n >= l and B > 0:
block = min(bs, B)
B -= block
f.seek(B, 0)
l += f.read(block).count('\n')
f.seek(B, 0)
l = min(l,n) # discard first (incomplete) line if l > n
lines = f.readlines()[-l:]
f.close()
return lines
A: Here is a pretty simple implementation:
with open('/etc/passwd', 'r') as f:
try:
f.seek(0,2)
s = ''
while s.count('\n') < 11:
cur = f.tell()
f.seek((cur - 10))
s = f.read(10) + s
f.seek((cur - 10))
print s
except Exception as e:
f.readlines()
A: There is very useful module that can do this:
from file_read_backwards import FileReadBackwards
with FileReadBackwards("/tmp/file", encoding="utf-8") as frb:
# getting lines by lines starting from the last line up
for l in frb:
print(l)
A: Update for answer given by A.Coady
Works with python 3.
This uses Exponential Search and will buffer only N lines from back and is very efficient.
import time
import os
import sys
def tail(f, n):
assert n >= 0
pos, lines = n+1, []
# set file pointer to end
f.seek(0, os.SEEK_END)
isFileSmall = False
while len(lines) <= n:
try:
f.seek(f.tell() - pos, os.SEEK_SET)
except ValueError as e:
# lines greater than file seeking size
# seek to start
f.seek(0,os.SEEK_SET)
isFileSmall = True
except IOError:
print("Some problem reading/seeking the file")
sys.exit(-1)
finally:
lines = f.readlines()
if isFileSmall:
break
pos *= 2
print(lines)
return lines[-n:]
with open("stream_logs.txt") as f:
while(True):
time.sleep(0.5)
print(tail(f,2))
A: I had to read a specific value from the last line of a file, and stumbled upon this thread. Rather than reinventing the wheel in Python, I ended up with a tiny shell script, saved as
/usr/local/bin/get_last_netp:
#! /bin/bash
tail -n1 /home/leif/projects/transfer/export.log | awk {'print $14'}
And in the Python program:
from subprocess import check_output
last_netp = int(check_output("/usr/local/bin/get_last_netp"))
A: Not the first example using a deque, but a simpler one. This one is general: it works on any iterable object, not just a file.
#!/usr/bin/env python
import sys
import collections
def tail(iterable, N):
deq = collections.deque()
for thing in iterable:
if len(deq) >= N:
deq.popleft()
deq.append(thing)
for thing in deq:
yield thing
if __name__ == '__main__':
for line in tail(sys.stdin,10):
sys.stdout.write(line)
A: This is my version of tailf
import sys, time, os
filename = 'path to file'
try:
with open(filename) as f:
size = os.path.getsize(filename)
if size < 1024:
s = size
else:
s = 999
f.seek(-s, 2)
l = f.read()
print l
while True:
line = f.readline()
if not line:
time.sleep(1)
continue
print line
except IOError:
pass
A: import time
attemps = 600
wait_sec = 5
fname = "YOUR_PATH"
with open(fname, "r") as f:
where = f.tell()
for i in range(attemps):
line = f.readline()
if not line:
time.sleep(wait_sec)
f.seek(where)
else:
print line, # already has newline
A: import itertools
fname = 'log.txt'
offset = 5
n = 10
with open(fname) as f:
n_last_lines = list(reversed([x for x in itertools.islice(f, None)][-(offset+1):-(offset+n+1):-1]))
A: abc = "2018-06-16 04:45:18.68"
filename = "abc.txt"
with open(filename) as myFile:
for num, line in enumerate(myFile, 1):
if abc in line:
lastline = num
print "last occurance of work at file is in "+str(lastline)
A: Another Solution
if your txt file looks like this:
mouse
snake
cat
lizard
wolf
dog
you could reverse this file by simply using array indexing in python
'''
contents=[]
def tail(contents,n):
with open('file.txt') as file:
for i in file.readlines():
contents.append(i)
for i in contents[:n:-1]:
print(i)
tail(contents,-5)
result:
dog
wolf
lizard
cat
A: Well! I had a similar problem, though I only required LAST LINE ONLY,
so I came up with my own solution
def get_last_line(filepath):
try:
with open(filepath,'rb') as f:
f.seek(-1,os.SEEK_END)
text = [f.read(1)]
while text[-1] != '\n'.encode('utf-8') or len(text)==1:
f.seek(-2, os.SEEK_CUR)
text.append(f.read(1))
except Exception as e:
pass
return ''.join([t.decode('utf-8') for t in text[::-1]]).strip()
This function return last string in a file
I have a log file of 1.27gb and it took very very less time to find the last line (not even half a second)
A: Two solutions based on counting '\n' from file end, tail1 uses memory map, tail2 does not. Speed is similar, both are fast but mmap version is faster. Both functions return last n lines (from n+1 '\n' to EOF) as string.
import mmap
def tail1(fn, n=5, encoding='utf8'):
with open(fn) as f:
mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
nn = len(mm)
for i in range(n+1):
nn = mm.rfind(b'\n',0,nn)
if nn < 0: break
return mm[nn:].decode(encoding=encoding).strip()
def tail2(fn, n=5, encoding='utf8'):
with open(fn,'rb') as f:
for i in range(f.seek(0, 2), 0, -1):
_ = f.seek(i)
if f.read(1) == b'\n': n -= 1
if n < 0: break
return f.read().decode(encoding=encoding).strip()
A: Although this isn't really on the efficient side with big files, this code is pretty straight-forward:
*
*It reads the file object, f.
*It splits the string returned using newlines, \n.
*It gets the array lists last indexes, using the negative sign to stand for the last indexes, and the : to get a subarray.
def tail(f,n):
return "\n".join(f.read().split("\n")[-n:])
A: it's so simple:
def tail(fname,nl):
with open(fname) as f:
data=f.readlines() #readlines return a list
print(''.join(data[-nl:]))
A: On second thought, this is probably just as fast as anything here.
def tail( f, window=20 ):
lines= ['']*window
count= 0
for l in f:
lines[count%window]= l
count += 1
print lines[count%window:], lines[:count%window]
It's a lot simpler. And it does seem to rip along at a good pace.
A: I found a probably the easiest way to find the first or last N lines of a file
Last N lines of a file(For Ex:N=10)
file=open("xyz.txt",'r")
liner=file.readlines()
for ran in range((len(liner)-N),len(liner)):
print liner[ran]
First N lines of a file(For Ex:N=10)
file=open("xyz.txt",'r")
liner=file.readlines()
for ran in range(0,N+1):
print liner[ran]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "202"
}
|
Q: How do I use a common log4net reference in assemblies loaded at runtime? I have a single-threaded application that loads several assemblies at runtime using the following:
objDLL = Assembly.LoadFrom(strDLLs[i]);
I would like the assemblies loaded in this manner to use the same log4net.ILog reference as the rest of the assemblies do. But it appears the runtime loaded assemblies have a different reference altogether and need their own configuration. Does anyone know if a single log4net.ILog can be used across assemblies loaded at runtime using a .NET interface?
Here is the log4net.ILog creation and supporting code in the Program class:
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
public static class Program
{
private static log4net.ILog m_Log = null;
[STAThread]
public static void Main(string[] args)
{
try
{
m_Log = log4net.LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
}
}
}
A: If all your assemblies implement a common interface, then you could have a property or constructor parameter that allows you to pass your local instance of ILog to the dynamically loaded assemblies.
A: You can get the same logger by specifying a literal logger name string, thus getting the same logger instance.
log4net.LogManager.GetLogger("SomeLogger");
A: This answer comes 4 years late, but I just encountered the same issue. In my case, I discovered that the assembly that was being loaded (from a different folder than the calling assembly) was also loading its own instance of log4net.
I fixed the issue by deleting the log4net.dll file from the folder where the runtime assembly was being loaded.
A: Something about the runtime loaded class prevents the usual one ILog per class from working. I can get a valid ILog instance, but unlike all the other instances it appears not to be configured (all the Is**Enabled flags are set to false). Perhaps the "root" logger is not accessible to the classes loaded at runtime???
A: I have a stupid solution. You can set the XmlConfiguration to the main log4net config file.
[assembly: log4net.Config.XmlConfigurator(ConfigFile="<configpath>",Watch = true)]
It is not really beauty .. but it runs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Fastest small datastore on Windows My app keeps track of the state of about 1000 objects. Those objects are read from and written to a persistent store (serialized) in no particular order.
Right now the app uses the registry to store each object's state. This is nice because:
*
*It is simple
*It is very fast
*Individual object's state can be read/written without needing to read some larger entity (like pulling out a snippet from a large XML file)
*There is a decent editor (RegEdit) which allow easily manipulating individual items
Having said that, I'm wondering if there is a better way. SQLite seems like a possibility, but you don't have the same level of multiple-reader/multiple-writer that you get with the registry, and no simple way to edit existing entries.
Any better suggestions? A bunch of flat files?
A: If what you mean by 'multiple-reader/multiple-writer' is that you keep a lot of threads writing to the store concurrently, SQLite is threadsafe (you can have concurrent SELECTs and concurrent writes are handled transparently). See the [FAQ [1]] and grep for 'threadsafe'
[1]: http://www.sqlite.org/faq.html/ FAQ
A: If you do begin to experiment with SQLite, you should know that "out of the box" it might not seem as fast as you would like, but it can quickly be made to be much faster by applying some established optimization tips:
SQLite optimization
Depending on the size of the data and the amount of RAM available, one of the best performance gains will occur by setting sqlite to use an all-in-memory database rather than writing to disk.
For in-memory databases, pass NULL as the filename argument to sqlite3_open and make sure that TEMP_STORE is defined appropriately
On the other hand, if you tell sqlite to use the harddisk, then you will get a similar benefit to your current usage of RegEdit to manipulate the program's data "on the fly."
The way you could simulate your current RegEdit technique with sqlite would be to use the sqlite command-line tool to connect to the on-disk database. You can run UPDATE statements on the sql data from the command-line while your main program is running (and/or while it is paused in break mode).
A: I doubt any sane person would go this route these days, however some of what you describe could be done with Window's Structured/Compound Storage. I only mention this since you're asking about Windows - and this is/was an official Windows way to do this.
This is how DOC files were put together (but not the new DOCX format). From MSDN it'll appear really complicated, but I've used it, it isn't the worst API in Win32.
*
*it is not simple
*it is fast, I would guess it's faster then the registry.
*Individual object's state can be read/written without needing to read some larger entity.
*There is no decent editor, however there are some real basic stuff (VC++ 6.0 had the "DocFile Viewer" under Tools. (yeah, that's what that thing did) I found a few more online.
*You get a file instead of registry keys.
*You gain some old-school Windows developer geek-cred.
Other random thoughts:
I think XML is the way to go (despite the random access issue). Heck, INI files may work. The registry gives you very fine grain security if you need it - people seem to forget this when the claim using files are better. An embedded DB seems like overkill if I'm understanding what you're doing.
A: Do you need to persist the objects on each change event or just in memory and store on shutdown? If so, just load them up and serialize them at the end, assuming your app runs for a long time (and you don't share that state with another program) then in memory is going to be a winner.
If you've got fixed size structures then you could consider just using a memory mapped file and allocate memory from that?
A: If the only thing you do is serialize/deserialize individual objects (no fancy queries), then use a btree database, for example Berkeley DB. It is very fast at storing and retrieving chunks of data by key (I assume your objects have some id that can be used as a key) and access by multiple processes is supported.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How should I use git diff for long lines? I'm running git-diff on a file, but the change is at the end of a long line.
If I use cursor keys to move right, it loses colour-coding—and worse the lines don't line up—making it harder to track the change.
Is there a way to prevent that problem or to simply make the lines wrap instead?
I'm running Git 1.5.5 via mingw32.
A: With full credit to Josh Diehl in a comment to this answer, I nevertheless feel like this ought to be an answer unto itself, so adding it:
One way to deal with seeing differences in long lines is to use a word-oriented diff. This can be done with:
git diff --word-diff
In this case, you'll get a significantly different diff output, that shows you specifically what has changed within a line.
For example, instead of getting something like this:
diff --git a/test-file.txt b/test-file.txt
index 19e6adf..eb6bb81 100644
--- a/test-file.txt
+++ b/test-file.txt
@@ -1 +1 @@
-this is a short line
+this is a slightly longer line
You might get something like this:
diff --git a/test-file.txt b/test-file.txt
index 19e6adf..eb6bb81 100644
--- a/test-file.txt
+++ b/test-file.txt
@@ -1 +1 @@
this is a [-short-]{+slightly longer+} line
Or, with colorization, instead of this:
You might get this:
Now, if you're comparing a really long line, you may still have issues with the pager situation you originally described, and which has been addressed, apparently to satisfaction, in other answers. Hopefully this gives you a new tool, though, to more easily identify what on the line has changed.
A: Noone pointed out this till now. Its quite simple to remember and no extra configuration needs to be done in the git config
git diff --color | less -R
A: Eight years later I find a superior answer, from https://superuser.com/questions/777617/line-wrapping-less-in-os-x-specifically-for-use-with-git-diff:
git config core.pager `fold -w 80 | less`
Now you pipe the git diff through fold, first, then to less: wrapped, less page-height is correct, keep syntax highlighting.
A: When you are using "git diff" and it's showing several pages(you see ":" at the end of the page)in this case you can type "-S" and press enter.(S should be capital). it will toggle fold long lines.
A: To use less as the pager and make line wrapping permanent you can simply enable the fold-long-lines option:
git config --global core.pager 'less -+S'
This way you do not have to type it while using less.
Cheers
A: Not a perfect solution, but gitk and git-gui can both show this information,
and have scrollbars.
A: You could simply pipe the output of git diff to more:
git diff | more
A: Or if you use less as default pager just type -S while viewing the diff to reenable wrapping in less.
A: Just googled up this one. GIT_PAGER='less -r' works for me
A: Mac OSX: None of the other answers except someone45's '-S' while less is running worked for me. It took the following to make word-wrap persistent:
git config --global core.pager 'less -+$LESS -FRX'
A: The display of the output of git diff is handled by whatever pager you are using.
Commonly, under Linux, less would be used.
You can tell git to use a different pager by setting the GIT_PAGER environment variable. If you don't mind about paging (for example, your terminal allows you to scroll back) you might try explicitly setting GIT_PAGER to empty to stop it using a pager. Under Linux:
$ GIT_PAGER='' git diff
Without a pager, the lines will wrap.
If your terminal doesn't support coloured output, you can also turn this off using either the --no-color argument, or putting an entry in the color section of your git config file.
$ GIT_PAGER='' git diff --no-color
A: You can also use git config to setup pager to wrap.
$ git config core.pager 'less -r'
Sets the pager setting for the current project.
$ git config --global core.pager 'less -r'
Sets the pager globally for all projects
A: Since Git 1.5.3
(Sep 2007)
a --no-pager option has been available.
git --no-pager diff
How do I prevent git diff from using a pager?
Example
Starting with v2.1, wrap is the default
Git v2.1 Release Notes
A: list the current/default config:
$ git config --global core.pager
less -FXRS -x2
then update and leave out the -S like:
$ git config --global core.pager 'less -FXR -x2'
the -S: Causes lines longer than the screen width to be chopped rather than folded.
A: When in trouble, I often resort to DiffMerge. Excellent diff tool that has in-line diff highlighting. Also, in the latest versions they added a mode to have an horizontal mode.
I haven't been able to configure git to use it, though. So I do have to muck around to get both versions of the file first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "255"
}
|
Q: What is the best approach to centralzing error messages in an application? All throughout an application wherever error messages (or other user messages) are used I typically hard-code a string. Obviosly this can be really bad (especially when you may have to come back and localize an app). What is the best approach to centralize these strings? A static class? Constants? An XML File? Or a combination (like creating a static class with constants that are used to read from an xml file).
A: Create the strings in a resource file. You can then localise by adding additional resource files.
Check out http://geekswithblogs.net/dotNETPlayground/archive/2007/11/09/116726.aspx
A: Use string resources.
A: I've always defined constants wherever they make the most sense based on your language (a static class? application-wide controller? resource file?) and just call them where/whenever needed. Sure they're still "hard-coded" in a way at that point, but they're also nicely centralized, with naming conventions that make sense.
A: Create a Resource (.resx) file and add your strings there. VS will generate a class for you for easy access to these resources with full intellisence. You can then add localised resources in the same manner.
A: .net has a pretty good support for so-called ressource-files where you can store all strings for one language.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make this "Use of uninitialized value" warning go away? Let's say I want to write a regular expression to change all <abc>, <def>, and <ghi> tags into <xyz> tags.. and I also want to change their closing tags to </xyz>. This seems like a reasonable regex (ignore the backticks; StackOverflow has trouble with the less-than signs if I don't include them):
`s!<(/)?(abc|def|ghi)>!<${1}xyz>!g;`
And it works, too. The only problem is that for opening tags, the optional $1 variable gets assigned undef, and so I get a "Use of uninitialized value..." warning.
What's an elegant way to fix this? I'd rather not make this into two separate regexs, one for opening tags and another for closing tags, because then there are two copies of the taglist that need to be maintained, instead of just one.
Edit: I know I could just turn off warnings in this region of the code, but I don't consider that "elegant".
A: How about:
`s!(</?)(abc|def|ghi)>!${1}xyz>!g;`
A: Move the question mark inside the capturing bracket. That way $1 will always be defined, but may be a zero-length string.
A: You could just make your first match be (</?), and get rid of the hard-coded < on the "replace" side. Then $1 would always have either < or </. There may be more elegant solutions to address the warning issue, but this one should handle the practical problem.
A: Here is one way:
s!<(/?)(abc|def|ghi)>!<$1xyz>!g;
Update: Removed irrelevant comment about using (?:pattern).
A: s!<(/?)(abc|def|ghi)>!<${1}xyz>!g;
The only difference is changing "(/)?" to "(/?)". You have already identified several functional solution. This one has the elegance you asked for, I think.
A: To make the regex capture $1 in either case, try:
s!<(/|)?(abc|def|ghi)>!<${1}xyz>!g;
^
note the pipe symbol, meaning '/' or ''
For '' this will capture the '' between '<' and 'abc>', and for '', capture '/' between '<' and 'abc>'.
A:
I'd rather not make this into two
separate regexs, one for opening tags
and another for closing tags, because
then there are two copies of the
taglist that need to be maintained
Why? Put your taglist into a variable and interpolate that variable into as many regexes as you like. I'd consider this even whith a single regex because it's much more readable with a complicated regex (and what regex isn't complicated?).
A: Be careful in as much as HTML is a bit harder then it looks to be at first glance. For example, do you want to change "<abc foo='bar'>" to "<xyz foo='bar'>"? Your regex won't. Do you want to change "<img alt='<abc>'>"? The regex will. Instead, you might want to do something like this:
use HTML::TreeBuilder;
my $tree=HTML::TreeBuilder->new_from_content("<abc>asdf</abc>");
for my $tag (qw<abc def ghi>) {
for my $elem ($tree->look_down(_tag => $tag)) {
$elem->tag('xyz');
}
}
print $tree->as_HTML;
That keeps you from having to do the fiddly bits of parsing HTML yourself.
A: Add
no warnings 'uninitialized';
or
s!<(/)?(abc|def|ghi)>! join '', '<', ${1}||'', 'xyz>' !ge;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Trying to set/get a JavaScript variable in an ActiveX WebBrowser from C# We have a windows application that contains an ActiveX WebBrowser control. As part of the regular operation of this application modifications are made to the pages that are displayed by the ActiveX WebBrowser control. Part of these modifications involve setting a JavaScript variable in a web page being loaded into the ActiveX WebBrowser.
We need to initialize this variable within C# (originally, VB6 code was initializing the value). The value of this variable is a COM-visible class object.
However, for simplicity we've reduced the problem to setting a string value. Our original page involves frames and the like but the same problems happens in a page like this:
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<SCRIPT type="text/javascript">
var field = 'hello world';
</SCRIPT>
</HEAD>
<BODY>
<input type="button" value="See field" onclick="javascript:alert(field);"/>
</BODY>
</HTML>
We want to access the field variable and assign a value to it. In VB6 the code for this was pretty straightforward:
doc.Script.field = 'newValue'
However, in C# we've had to resort to other tricks, like this:
Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateSet(Script, null, "field",new object[] { "newValue"},null, null);
The point of the page is to test whether our variable was properly assigned by C#. Clicking on the button should yield whatever new value was injected by C#. So for example, clicking on the button in the page we get an alert showing: "newValue".
That works the first time, but it doesn't work if we reload the page. On subsequent calls we cannot set the value of the variable field.
Has anyone had any experience doing this type of operation before?
A: I think what you are looking for is the eval() method in Javascript. You can call it from C# like this:
webBrowser1.Document.InvokeScript("eval", new String[] {"1 + 2"});
This code will evaluate "1 + 2" and return "3". I would imagine that if you were to put in
InvokeScript("eval", new String[] {"varName = 3"})
you would get that variable assigned to 3 if it is globally visible in the file.
A: If you use the webBrowser control, you can assign a c# object to the
objectForScripting property
http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.objectforscripting.aspx
after that you can use window.external in your javascript to interact with your c# object from javascript
if you use an activeX version for some reason, you can pass javascript: urls to programmatically sets your variable, or you can syncronize your script using a webservice/ database/file or simply using the method you suggested.
A: These two articles helped us find a solution to our problem. They outline the basics of what one needs to know:
Microsoft Web Browser Automation using C#
Using MSHTML Advanced Hosting Interfaces
So we implemented a DocHostUIHandler interface and that allowed us to set a UIHandler, allowing us to reference the method from Javascript.
A: The usual method we use is to add a hidden text input box (the ASP.Net control version) on the page. That way you can easily set its value in the C# codebehind and read the value in client side JavaScript (and vice-versa, of course).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What's the point of Perl's map? Not really getting the point of the map function. Can anyone explain with examples its use?
Are there any performance benefits to using this instead of a loop or is it just sugar?
A: The map function is an idea from the functional programming paradigm. In functional programming, functions are first-class objects, meaning that they can be passed as arguments to other functions. Map is a simple but a very useful example of this. It takes as its arguments a function (lets call it f) and a list l. f has to be a function taking one argument, and map simply applies f to every element of the list l. f can do whatever you need done to every element: add one to every element, square every element, write every element to a database, or open a web browser window for every element, which happens to be a valid URL.
The advantage of using map is that it nicely encapsulates iterating over the elements of the list. All you have to do is say "do f to every element, and it is up to map to decide how best to do that. For example map may be implemented to split up its work among multiple threads, and it would be totally transparent to the caller.
Note, that map is not at all specific to Perl. It is a standard technique used by functional languages. It can even be implemented in C using function pointers, or in C++ using "function objects".
A: The map function runs an expression on each element of a list, and returns the list results. Lets say I had the following list
@names = ("andrew", "bob", "carol" );
and I wanted to capitalize the first letter of each of these names. I could loop through them and call ucfirst of each element, or I could just do the following
@names = map (ucfirst, @names);
A: "Just sugar" is harsh. Remember, a loop is just sugar -- if's and goto can do everything loop constructs do and more.
Map is a high enough level function that it helps you hold much more complex operations in your head, so you can code and debug bigger problems.
A: Any time you want to generate a list based another list:
# Double all elements of a list
my @double = map { $_ * 2 } (1,2,3,4,5);
# @double = (2,4,6,8,10);
Since lists are easily converted pairwise into hashes, if you want a hash table for objects based on a particular attribute:
# @user_objects is a list of objects having a unique_id() method
my %users = map { $_->unique_id() => $_ } @user_objects;
# %users = ( $id => $obj, $id => $obj, ...);
It's a really general purpose tool, you have to just start using it to find good uses in your applications.
Some might prefer verbose looping code for readability purposes, but personally, I find map more readable.
A: To paraphrase "Effective Perl Programming" by Hall & Schwartz,
map can be abused, but I think that it's best used to create a new list from an existing list.
Create a list of the squares of 3,2, & 1:
@numbers = (3,2,1);
@squares = map { $_ ** 2 } @numbers;
A: Generate password:
$ perl -E'say map {chr(32 + 95 * rand)} 1..16'
# -> j'k=$^o7\l'yi28G
A: You use map to transform a list and assign the results to another list, grep to filter a list and assign the results to another list. The "other" list can be the same variable as the list you are transforming/filtering.
my @array = ( 1..5 );
@array = map { $_+5 } @array;
print "@array\n";
@array = grep { $_ < 7 } @array;
print "@array\n";
A: It allows you to transform a list as an expression rather than in statements. Imagine a hash of soldiers defined like so:
{ name => 'John Smith'
, rank => 'Lieutenant'
, serial_number => '382-293937-20'
};
then you can operate on the list of names separately.
For example,
map { $_->{name} } values %soldiers
is an expression. It can go anywhere an expression is allowed--except you can't assign to it.
${[ sort map { $_->{name} } values %soldiers ]}[-1]
indexes the array, taking the max.
my %soldiers_by_sn = map { $->{serial_number} => $_ } values %soldiers;
I find that one of the advantages of operational expressions is that it cuts down on the bugs that come from temporary variables.
If Mr. McCoy wants to filter out all the Hatfields for consideration, you can add that check with minimal coding.
my %soldiers_by_sn
= map { $->{serial_number}, $_ }
grep { $_->{name} !~ m/Hatfield$/ }
values %soldiers
;
I can continue chaining these expression so that if my interaction with this data has to reach deep for a particular purpose, I don't have to write a lot of code that pretends I'm going to do a lot more.
A: It's used anytime you would like to create a new list from an existing list.
For instance you could map a parsing function on a list of strings to convert them to integers.
A: First of all, it's a simple way of transforming an array: rather than saying e.g.
my @raw_values = (...);
my @derived_values;
for my $value (@raw_values) {
push (@derived_values, _derived_value($value));
}
you can say
my @raw_values = (...);
my @derived_values = map { _derived_value($_) } @raw_values;
It's also useful for building up a quick lookup table: rather than e.g.
my $sentence = "...";
my @stopwords = (...);
my @foundstopwords;
for my $word (split(/\s+/, $sentence)) {
for my $stopword (@stopwords) {
if ($word eq $stopword) {
push (@foundstopwords, $word);
}
}
}
you could say
my $sentence = "...";
my @stopwords = (...);
my %is_stopword = map { $_ => 1 } @stopwords;
my @foundstopwords = grep { $is_stopword{$_} } split(/\s+/, $sentence);
It's also useful if you want to derive one list from another, but don't particularly need to have a temporary variable cluttering up the place, e.g. rather than
my %params = ( username => '...', password => '...', action => $action );
my @parampairs;
for my $param (keys %params) {
push (@parampairs, $param . '=' . CGI::escape($params{$param}));
}
my $url = $ENV{SCRIPT_NAME} . '?' . join('&', @parampairs);
you say the much simpler
my %params = ( username => '...', password => '...', action => $action );
my $url = $ENV{SCRIPT_NAME} . '?'
. join('&', map { $_ . '=' . CGI::escape($params{$_}) } keys %params);
(Edit: fixed the missing "keys %params" in that last line)
A: The map function is used to transform lists. It's basically syntactic sugar for replacing certain types of for[each] loops. Once you wrap your head around it, you'll see uses for it everywhere:
my @uppercase = map { uc } @lowercase;
my @hex = map { sprintf "0x%x", $_ } @decimal;
my %hash = map { $_ => 1 } @array;
sub join_csv { join ',', map {'"' . $_ . '"' } @_ }
A: See also the Schwartzian transform for advanced usage of map.
A: It's also handy for making lookup hashes:
my %is_boolean = map { $_ => 1 } qw(true false);
is equivalent to
my %is_boolean = ( true => 1, false => 1 );
There's not much savings there, but suppose you wanted to define %is_US_state?
A: map is used to create a list by transforming the elements of another list.
grep is used to create a list by filtering elements of another list.
sort is used to create a list by sorting the elements of another list.
Each of these operators receives a code block (or an expression) which is used to transform, filter or compare elements of the list.
For map, the result of the block becomes one (or more) element(s) in the new list. The current element is aliased to $_.
For grep, the boolean result of the block decides if the element of the original list will be copied into the new list. The current element is aliased to $_.
For sort, the block receives two elements (aliased to $a and $b) and is expected to return one of -1, 0 or 1, indicating whether $a is greater, equal or less than $b.
The Schwartzian Transform uses these operators to efficiently cache values (properties) to be used in sorting a list, especially when computing these properties has a non-trivial cost.
It works by creating an intermediate array which has as elements array references with the original element and the computed value by which we want to sort. This array is passed to sort, which compares the already computed values, creating another intermediate array (this one is sorted) which in turn is passed to another map which throws away the cached values, thus restoring the array to its initial list elements (but in the desired order now).
Example (creates a list of files in the current directory sorted by the time of their last modification):
@file_list = glob('*');
@file_modify_times = map { [ $_, (stat($_))[8] ] } @file_list;
@files_sorted_by_mtime = sort { $a->[1] <=> $b->[1] } @file_modify_times;
@sorted_files = map { $_->[0] } @files_sorted_by_mtime;
By chaining the operators together, no declaration of variables is needed for the intermediate arrays;
@sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { [ $_, (stat($_))[8] ] } glob('*');
You can also filter the list before sorting by inserting a grep (if you want to filter on the same cached value):
Example (a list of the files modified in the last 24 hours sorted the last modification time):
@sorted_files = map { $_->[0] } sort { $a->[1] <=> $b->[1] } grep { $_->[1] > (time - 24 * 3600 } map { [ $_, (stat($_))[8] ] } glob('*');
A: As others have said, map creates lists from lists. Think of "mapping" the contents of one list into another. Here's some code from a CGI program to take a list of patent numbers and print hyperlinks to the patent applications:
my @patents = ('7,120,721', '6,809,505', '7,194,673');
print join(", ", map { "<a href=\"http://patft.uspto.gov/netacgi/nph-Parser?Sect1=PTO1&Sect2=HITOFF&d=PALL&p=1&u=/netahtml/srchnum.htm&r=0&f=S&l=50&TERM1=$_\">$_</a>" } @patents);
A: As others have said, map is most useful for transforming a list. What hasn't been mentioned is the difference between map and an "equivalent" for loop.
One difference is that for doesn't work well for an expression that modifies the list its iterating over. One of these terminates, and the other doesn't:
perl -e '@x=("x"); map { push @x, $_ } @x'
perl -e '@x=("x"); push @x, $_ for @x'
Another small difference is that the context inside the map block is a list context, but the for loop imparts a void context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
}
|
Q: How can I write an SNMP agent or SNMP extension agent DLL in C# I need to write an SNMP agent for my application.
I read the CodeProject article on how to write an SNMP extension agent DLL using win32, but would like to know if it is possible to do it with managed code.
Also, is it possible to write my own SNMP agent in managed code and run it along windows SNMP service?
windows SNMP service is required to run on my server to provide the basic operating system management info.
What C# SNMP library would you recommend? I found a few C# SNMP protocol implementations, but could not find sample code on how to implement an SNMP agent - most samples are only about querying other agents or sending traps.
A: If you would like to use the SNMP protocol from the .Net Framework, regard this library: #SNMP.
It seems possibly to write your own SNMP server with it. But the standard SNMP Agent archictecture is not based on .Net und so - I assume - you cannot use the mentioned library to extend it. You must write your own and this looks possible with the mentioned library.
Hope this help.
br--mabra
A: *
*the best library I have used in 8
years of NMS development -
adventnet
*you can write your own, but you need to understand ASN. Good luck with that.
*SNMP agents do 2 things: query for data, send and receive traps. What else you want
them to do? wash your laundry?! (sorry couldn't resist that! :) ).
What are you trying to do with your SNMP agent?! Does you app need to send traps?! or query for data from a node?!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
}
|
Q: How do you manage your custom modules? I write tons of python scripts, and I find myself reusing lots code that I've written for other projects. My solution has been to make sure the code is separated into logical modules/packages (this one's a given). I then make them setuptools-aware and publish them on PyPI. This allows my other scripts to always have the most up-to-date code, I get a warm fuzzy feeling because I'm not repeating myself, and my development, in general, is made less complicated. I also feel good that there MAY be someone out there that finds my code handy for something they're working on, but it's mainly for selfish reasons :)
To all the pythonistas, how do you handle this? Do you use PyPI or setuptools (easy_install)? or something else?
A: I have been doing the same thing. Extract common functionality, pretty the code up with extra documentation and unit tests/ doctests, create an easy_install setup.py, and then release on PyPi. Recently, I created a single Google Code site where I manage the source and keep the wiki up to date.
A: What kind of modules are we talking about here? If you're planning on distributing your projects to other python developers, setuptools is great. But it's usually not a very good way to distribute apps to end users. Your best bet in the latter case is to tailor your packaging to the platforms you're distributing it for. Sure, it's a pain, but it makes life for end users far easier.
For example, in my Debian system, I usually don't use easy_install because it is a little bit more difficult to get eggs to work well with the package manager. In OS X and windows, you'd probably want to package everything up using py2app and py2exe respectively. This makes life for the end user better. After all, they shouldn't know or care what language your scripts are written in. They just need them to install.
A: I store it all offline in a logical directory structure, with commonly used modules grouped as utilities. This means it's easier to control which versions I publish, and manage. I also automate the build process to interpret the logical directory structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Silverlight Security- Sensitive Data Silverlight works on client side so putting any sensitive data like connection strings, passwords etc. in the code seems not to be a good thing. I want to build whole web app in Silverlight doing lots of authorization and database quering things. How to make it safe? Any tips&tricks and what things should I avoid?
A: I have never developed / used a silverlight app, but I would assume you would use a webservice to broker communication between your app and the database.
This is at least how Flex works.
Edit: This is how Silverlight works as well
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: redirect STDERR in tcsh from .aliases in tcsh I'm trying to redirect STDERR from a command from my .aliases file.
I found that I can redirect STDERR from the command line like this. . .
$ (xemacs > /dev/tty) >& /dev/null
. . . but when I put this in my .aliases file I get an alias loop. . .
$ cat .aliases
alias xemacs '(xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
Alias loop.
$
. . . so I put a backslash before the command in .aliases, which allows the command to run. . .
$ cat .aliases
alias xemacs '(\xemacs > /dev/tty ) >& /dev/null'
$ xemacs &
[1] 17295
$
. . . but now I can't give the command any arguments:
$ xemacs foo.txt &
Badly placed ()'s.
[1] Done ( \xemacs > /dev/tty ) >& /dev/null
$
Can anyone offer any solutions? Thank you in advance!
UPDATE: I'm still curious if it's possible to redirect STDERR in tcsh from .aliases, but as has been suggested here, I ended up with a shell script:
#!/bin/sh
# wrapper script to suppress messages sent to STDERR on launch
# from the command line.
/usr/bin/xemacs "$@" 2>/dev/null
A: I suspect this is a case where NOT using an alias is the best option - try using a shell script instead:
#!/bin/tcsh
(xemacs $* > /dev/tty ) >& /dev/null
A: Try
alias emacs '(\emacs \!* > /dev/tty) >& /dev/null'
The "badly placed ()'s" message comes from misplacing the input parameter to emacs. Without the "\!*" in the alias definition, "emacs abc" becomes
(/usr/bin/emacs > /dev/tty) >& /dev/null abc
With the "\!*" included, "emacs abc" becomes
(/usr/bin/emacs abc > /dev/tty) >& /dev/null
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Parsing a raw email message that may be in html or various strange encodings and converting it to plain text, the way, say, pine might display it The reason I want to do this is to make it easy to parse out instructions that are emailed to a bot, the kind of thing majordomo might do to parse commands like subscribing and unsubscribing. It turns out there are a lot of crazy formats and things to deal with, like quoted text, distinguishing between header and body, etc.
A perl module to do this would be ideal but solutions in any language are welcome.
A: Python has the email.
>>> import email
>>> p = email.Parser.Parser()
>>> msg = p.parsestr("From: me@example.com\nSubject: Hello\nDear Sir or Madam...")
>>> msg.get("Subject")
Hello
>>> msg.get_payload()
'Dear Sir or Madam...'
It supports MIME and pretty much all encodings that are included in Python. HTML will just be text to it, but you can use BeautifulSoup or Tidy+ElementTree to get the text out of it.
A: Can't say I have every done exactly what you are talking about, but maybe you should give this a read as it sounds like the author is doing what you describe.
Parsing MIME & HTML
A: You could do worse than look at CPAN for email-related modules.
One that I've used in the past for breaking out subjects, and bodies has been Email::Simple
A: Some ideas: http://news.ycombinator.com/item?id=666607
Here's my incomplete solution, which actually works for my purposes (parsing commands emailed to a bot). I'm keeping it here for reference until there's a definitively better answer.
# Take an email as a big string and turn it into a plain ascii equivalent.
# TODO: leave any html tags inside of quotes alone.
sub plainify {
my($email) = @_;
# translate quoted-printable or whatever this crap is to plain text.
$email =~ s/\=0D\=0A/\n/gs;
$email =~ s/\=0A/\n/gs;
$email =~ s/\=A0/ /gs;
$email =~ s/\=2E/\./gs;
$email =~ s/\=20/\ /gs;
$email =~ s/\=([\n\r]|\n\r|\r\n)//gs;
# translate html to plain text (or enough of it to parse commands).
$email =~ s/\ \;/ /gs;
$email =~ s/\<br\>/\n/gis;
$email =~ s/(\<[^\>]+\>)/\n$1\n/gs;
return $email
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Visual Studios Link.exe error: "extra operand" Our build process uses Visual Studios 2003 link.exe for linking. On one machine we're seeing the following error:
_X86_Win32/Debug/Intermediate/OurApp.exe LINK: extra operand `/subsystem:windows' Try `LINK --help' for more information
It appears to be using the same version of visual studios as the other machines. Has anyone encountered this problem before?
A: It looks like there's a copy of the GNU link utility somewhere in the search path. This message isn't from the Microsoft linker.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Trouble when adding a lot of Controls to a .NET Windows Form (C#) I have a Windows Form app written in C#. Its job is to send messages to a list of users. While those messages are being sent, I'd like to display status of the operation for each user. What I am doing (for each user) is creating a Label control and adding it to Panel. This works without a problem for a small set of users. When I increase the size to 1000 or more, the Visual Studio Debugger displays the following message:
A first chance exception of type 'System.ComponentModel.Win32Exception' occurred in
System.Windows.Forms.dll A first chance exception of type
'System.Reflection.TargetInvocationException' occurred in
mscorlib.dll
And then the application hangs. Any thoughts on what I'm doing wrong and how I can fix this?
A: Use DataGridView instead
A: Given the size, I would consider displaying your status in a RichTextBox.
What is happening is that you are generating too many handles and the Framework can't handle them all.
A: This is kind of a work around, but I don't think your users really want to look at a list of 1000 people. Show them the current/most recent and summary report for the rest. Or let them page through it.
A: Without seeing specific code, it is difficult to tell. If I were tasked with the same program, I would approach it differently.
I would use a Grid or a Listview to display the user and the status of his or her message being sent. These controls can handle an unlimited(well -- limited by system memory) number of rows. One row per user (or one row per message -- which ever works better).
That should be the only thing going on in the UI thread. Use a background worker (BacngroundWorker class), or a message queuing framework (MSMQ, SQL server) to have the messages sent asynchronously and report on the status back up through the BackgroundWorker.
As for your specific error -- I do not know why you are getting it. There should be no limit to the number of labels you can put on a WinForm. I suspect the error is caused by something else.
A: Put a ProgressBar on your form instead. If you're sending one message to 1000 people, just increment the ProgressBar by 1 each time you send a message.
If you're sending 5 messages to 1000 people, have one progress bar for messages and one for people (the second bar will cycle through its values once for each value on the first bar).
You can also have a label for each progress bar (saying "95% complete" or "Message 3 of 5" or whatever).
You can't have such a large number of controls on a .NET form, and even if you could, there's no way any user could look at them all at the same time anyway.
A: I like to use ListView in details mode. Usually, I'll make a routine for adding a row, make it selected, and call EnsureVisible() on the item to autoscroll to it.
Like already mentioned, controls correlate to one or more window handles and the OS can only hand out so many.
A: Too many controls! Make a single control to contain all those status messages. How about a multi-line textbox?
A: If you are literally only showing labels in the panel, I would suggest that you show the statuses using GDI. Write the text of the visible area in OnPaint and invalidate the area of a status label only when it changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why should you remove unnecessary C# using directives? For example, I rarely need:
using System.Text;
but it's always there by default. I assume the application will use more memory if your code contains unnecessary using directives. But is there anything else I should be aware of?
Also, does it make any difference whatsoever if the same using directive is used in only one file vs. most/all files?
Edit: Note that this question is not about the unrelated concept called a using statement, designed to help one manage resources by ensuring that when an object goes out of scope, its IDisposable.Dispose method is called. See Uses of "using" in C#.
A: There are few reasons for removing unused using(s)/namespaces, besides coding preference:
*
*removing the unused using clauses in a project, can make the compilation faster because the compiler has fewer namespaces to look-up types to resolve. (this is especially true for C# 3.0 because of extension methods, where the compiler must search all namespaces for extension methods for possible better matches, generic type inference and lambda expressions involving generic types)
*can potentially help to avoid name collision in future builds when new types are added to the unused namespaces that have the same name as some types in the used namespaces.
*will reduce the number of items in the editor auto completion list when coding, posibly leading to faster typing (in C# 3.0 this can also reduce the list of extension methods shown)
What removing the unused namespaces won't do:
*
*alter in any way the output of the compiler.
*alter in any way the execution of the compiled program (faster loading, or better performance).
The resulting assembly is the same with or without unused using(s) removed.
A: You may have name clashes if you call your classes like the (unused) classes in the namespace. In the case of System.Text, you'll have a problem if you define a class named "Encoder".
Anyways this is usually a minor problem, and detected by the compiler.
A: Code cleanliness is important.
One starts to get the feeling that the code may be unmaintained and on the browfield path when one sees superfluous usings. In essence, when I see some unused using statements, a little yellow flag goes up in the back of my brain telling me to "proceed with caution." And reading production code should never give you that feeling.
So clean up your usings. Don't be sloppy. Inspire confidence. Make your code pretty. Give another dev that warm-fuzzy feeling.
A: There's no IL construct that corresponds to using. Thus, the using statements do not increase your application memory, as there is no code or data that is generated for it.
Using is used at compile time only for the purposes of resolving short type names to fully qualified type names. Thus, the only negative effect unnecessary using can have is slowing the compile time a little bit and taking a bit more memory during compilation. I wouldn't be worried about that though.
Thus, the only real negative effect of having using statements you don't need is on intellisense, as the list of potential matches for completion while you type increases.
A: Your application will not use more memory. It's for the compiler to find classes you use in the code files. It really doesn't hurt beyond not being clean.
A: It’s personal preference mainly. I clean them up myself (ReSharper does a good job of telling me when there’s unneeded using statements).
One could say that it might decrease the time to compile, but with computer and compiler speeds these days, it just wouldn’t make any perceptible impact.
A: Leaving extra using directives is fine. There is a little value in removing them, but not much. For example, it makes my IntelliSense completion lists shorter, and therefore easier to navigate.
The compiled assemblies are not affected by extraneous using directives.
Sometimes I put them inside a #region, and leave it collapsed; this makes viewing the file a little cleaner. IMO, this is one of the few good uses of #region.
A: if you want to maintain your code clean, not used using statements should be removed from the file. the benefits appears very clear when you work in a collaborative team that need to understand your code, think all your code must be maintained, less code = less work, the benefits are long term.
A: It won't change anything when your program runs. Everything that's needed is loaded on demand. So even if you have that using statement, unless you actually use a type in that namespace / assembly, the assembly that using statement is correlated to won't be loaded.
Mainly, it's just to clean up for personal preference.
A: They are just used as a shortcut. For example, you'd have to write:
System.Int32 each time if you did not have a using System; on top.
Removing unused ones just makes your code look cleaner.
A: The using statement just keeps you from qualifying the types you use. I personally like to clean them up. Really it depends on how a loc metric is used
A: Having only the namespaces that you actually use allows you to keep your code documented.
You can easily find what parts of your code are calling one another by any search tool.
If you have unused namespaces this means nothing, when running a search.
I'm working on cleaning up namespaces now, because I'm constantly asked what parts of the application are accessing the same data one way or another.
I know which parts are accessing data each way due to the data access being separated by namespaces e.g. directly through a database and in-directly through a web service.
I can't think of a simpler way to do this all at once.
If you just want your code to be a black box (to the developers), then yes it doesn't matter. But if you need to maintain it over time it is valuable documentation like all other code.
A: The 'using' statement does not affect performance as it is merely a helper in qualifying the names of your identifiers. So instead of having to type, System.IO.Path.Combine(...), you can simply type, Path.Combine(...) if you have using System.IO.
A: Do not forget that the compiler do a lot of work to optimize everything when building your project. Using that is used in a lot of place or 1 shouldn't do a different once compiled.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "230"
}
|
Q: Ajax autocomplete extender populated from SQL OK, first let me state that I have never used this control and this is also my first attempt at using a web service.
My dilemma is as follows. I need to query a database to get back a certain column and use that for my autocomplete. Obviously I don't want the query to run every time a user types another word in the textbox, so my best guess is to run the query once then use that dataset, array, list or whatever to then filter for the autocomplete extender...
I am kinda lost any suggestions??
A: This question depends upon how transactional your data store is. Obviously if you are looking for US states (a data collection that would not change realistically through the life of the application) then I would either cache a System.Collection.Generic List<> type or if you wanted a DataTable.
You could easily set up a cache of the data you wish to query to be dependent upon an XML file or database so that your extender always queries the data object casted from the cache and the cache object is only updated when the datasource changes.
A: Why not keep track of the query executed by the user in a session variable, then use that to filter any further results?
The trick to preventing the database from overloading I think is really to just limit how frequently the auto updater is allowed to update, something like once per 2 seconds seems reasonable to me.
What I would do is this: Store the current list returned by the query for word A server side and tie that to a session variable. This should be basically the entire list I would think. Then, for each new word typed, so long as the original word A exists, you can filter the session info and spit the filtered results out without having to query again. So basically, only query again when word A changes.
I'm using "session" in a PHP sense, you may be using a different language with different terminology, but the concept should be the same.
A: RAM is cheap and SQL is harder to scale than IIS so cache everything in memory:
*
*your entire data source if is not
too large to load it in reasonable
time,
*precalculated data,
*autocomplete webservice responses.
Depending on your autocomplete desired behavior and performance you may want to precalculate data and create redundant structures optimized for reading. Make use of structs like SortedList (when you need sth like 'select top x ... where z like @query+'%'), Hashtable,...
A: While caching everything is certainly a good idea, your question about which data structure to use is an issue that wasn't fully answered here.
The best data structure for an autocomplete extender is a Trie.
You can find a good .NET article and code here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP/MySQL update a news record in a database problem I have this PHP code that I am trying to use to let a user edit a news record in a form and then when they hit the submit button, it will update the record in a database. The problem is that everything works but the record is not actually updated in the database.
Could someone look at my code and see where a problem could occur?
<?php
$title = "Edit News";
include("../includes/header.php");
include("../includes/database.php");
$done = false;
$expected = array('newstitle', 'newscontent', 'id');
if ($_GET && !$_POST) {
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = $_GET['id'];
}
else {
$id = NULL;
}
if ($id) {
$sql = "SELECT * FROM news WHERE id = $id";
$result = mysql_query($sql) or die ("Error connecting to database...");
$row = mysql_fetch_assoc($result);
}
// if form has been submitted, update record
if (array_key_exists('update', $_POST)) {
// prepare expected items for insertion into database
foreach ($_POST as $key => $value) {
if (in_array($key, $expected)) {
${$key} = mysql_real_escape_string($value);
}
}
// abandon the process if primary key invalid
if (!is_numeric($id)) {
die('Invalid request');
}
// prepare the SQL query
$query = "UPDATE news SET title = '$title', content = '$content' WHERE id = $id";
// submit the query
$done = mysql_query($query) or die("Error connecting to database...");
}
}
// redirect page if $id is invalid
if ($done) {
header("Location: $ROOT/admin/listnews.php");
exit;
}
?>
A: if ($_GET && !$_POST) {
...
if (array_key_exists('update', $_POST)) {
Won't that ensure the update code never fires?
A: If you run that UPDATE from the mysql cli with the same data the user sends does it update?
If not check for escaping characters.
A: Should $content and $title in the line below be $newstitle and $newscontent?
// prepare the SQL query
$query = "UPDATE news SET title = '$newstitle', content = '$newscontent' WHERE id = $id";
A: Couple of things to try and narrow down the problem:
*
*echo out some debug text just inside the if (array_key_exists('update', $_POST)) block to make sure you're actually getting in there. The top of your "if" is if($_GET && !$_POST), so you may need to change this $_POST to $_GET
*have you tried echoing out $query just before the db call? Does it run on the command line mysql interface ok?
*if my reading of your foreach ($_POST as $key => $value) is correct, you'll end up setting variables with the same names as those in $expected - ($newstitle, $newscontent, $id) - but in your sql reference $content and $title. They may be the cause of this bug, but something to keep an eye out for.
A: It's a little hard to know exactly what's going on without seeing the HTML source of your form, but I think that the
if (array_key_exists('update', $_POST)) {
block needs to be moved out of the outer if, since it will never be executed if it's there.
If you don't want to use some sort of testing framework, print() is your friend when it comes to debugging your code. Try to find what's executing and what's not; you'll quickly discover which of your assumptions are incorrect, and therefore where the bug is.
A: Take this if statement out of the nested if:
if (array_key_exists('update', $_POST)) {
...
}
and then add this conditional:
if (count($_POST) && array_key_exists('update', $_POST)) {
...
}
I'm pretty sure that will take care of your problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's required for a clean uninstall of Visual Studio 2005 Due to continuing crash problems, I'm about to uninstall and reinstall my copy of Visual Studio 2005. I know that just running the uninstaller leaves a lot of resources and settings on my machine and would like to be able to reinstall from a pristine state.
Is there any way to completely uninstall VS2k5 from my machine so that it's as if it was never there?
A: Visual Studio 2005 is known for not uninstalling so well (especially the Express editions). Use the technique found here to manually uninstall all of Visual Studio.
A: sure, it starts with 'format c:' :)
Seriously though, I've had that type of issue with various MS products. Clean uninstalls are almost impossible because even windows hasn't kept track of what shared DLLs were installed by VS2005. You could try installing VS express, hope that it overwrites whatever problem is there, and then reinstall VS2005, but I wouldn't hold my breath on it working.
The other possibility is that it's something local to your user. You could try moving your folder under documents and settings and getting it to regenerate and see if that works...
A: A hell of a lot of luck. I have tried many times to pull this off and each time I ended up just restoring to before I installed it or doing a fresh install.
A: If DevStudio is crashing a lot on you, you might try uninstalling any add-ins and extensions as a first step.
It might save you a lot of pain.
A: Rebuild your machine. Things just get mucked up after a while, and in the process you'll clean out all the muck you've accumulated in Windows in addition to the Visual Studio muck. It seems harsh, but after you do it a couple times it's really faster, less painful, and more complete than trying to track down a bunch of random issues.
A: Aaron Stebner's WebLog has a link to a specialist uninstaller for VS2005 here. More straight forward than the official MS solution of downloading MSIZap.exe and the Windows Server 2003 SDK.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to configure Tomcat JULI logging to roll log files? I have a several webapps which use java.util.logging. Tomcat 5.5 is configured to use the Juli logger so that each webapp has its own log file. The problem is that Juli does not have properties for maximum file size and file count. Using Juli the files will grow unbounded and only roll at the end of the day. Also, an unlimited number of log files are retained.
You can see the FileHandler properties on this page - Apache Tomcat 5.5 Documentation
There is no limit or count property (the following lines do nothing)
org.apache.juli.FileHandler.limit=102400
org.apache.juli.FileHandler.count=5
Without changing the webapps is there a way to get unique log files for each application with some type of bounds on the log file sizes?
UPDATE:
The solution I found was not use the Juli logger at all!
java.util.logging.FileHandler.limit=102400
java.util.logging.FileHandler.count=5
Thanks,
Greg
A: Update: I see your point now after reading more. "Tomcat's JULI implementation is not intended to be a fully-featured logging libary, only a simple bridge to those libraries. However, JULI does provide several properties for configuring the its handlers. These are listed below." Funny that they say that the default java.util.Logging implementation is too limited then they work around it by providing an even more limiting implementation.
FileHandler javadocs
*
*java.util.logging.FileHandler.limit specifies an approximate maximum amount to write (in bytes) to any one file. If this is zero, then there is no limit. (Defaults to no limit).
*java.util.logging.FileHandler.count specifies how many output files to cycle through (defaults to 1).
for the one file per web app, you probably want to separate it by the name of the logger and it depends on how the loggers are created for each app. If they're based off the package or class name then you can filter the logs based on that. It looks like the sample on the link you provided tells how to do this
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
2localhost.org.apache.juli.FileHandler
A: EDIT: Just realized you wanted per webapp logging which might not be possible with this setup...
My suggestion, assuming your are using Tomcat 6.0, is to compile the extra component for full commons-logging and use Log4j to configure rolling logs.
Building instructions here
http://tomcat.apache.org/tomcat-6.0-doc/building.html
Then replace the tomcat-juli.jar in the /bin directory of Tomcat and place the tomcat-juli-adapters.jar in the /lib directory along with log4j.jar and log4j.properties.
Then using something like:
<appender name="file" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="logfile.log"/>
<param name="Threshold" value="INFO"/>
<param name="MaxFileSize" value="10MB"/>
<param name="MaxBackupIndex" value="3"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ISO8601} %p %m%n"/>
</layout>
</appender>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How do you refresh maven dependencies from eclipse? We recently started using maven for dependency management. Our team uses eclipse as it's IDE. Is there an easy way to get eclipse to refresh the maven dependencies without running mvn eclipse:eclipse?
The dependencies are up to date in the local maven repository, but eclipse doesn't pick up the changes until we use the eclipse:eclipse command. This regenerates a lot of eclipse configuration files.
A: You generate the special eclipse files with mvn eclipse:eclipse, but once you've done that, you should let a plugin handle the dependencies while inside eclipse.
That's how we do it at my work place, and it generally works well.
A: Have you tried using the m2eclipse plugin? I use it with eclipse and it maintains the eclipse .classpath when I add dependencies. It'll also check for updated dependencies.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Is this a crazy way to handle multi Validation types with IDataError and WPF? We are using the standard method for our controls to report broken BO rules. This is done via the interface IDataError in our BO’s and in XAML the control is bound to the BO’s property etc. This approach works OK. But we need to show 2 types of visuals in the UI depending on the type (or category if you like) of the invalidation error. If it’s a required field then we show a CueBanner (water mark) but for other types we change the colour of the controls boarder. In both scenarios we set the tool type of the error message.
The Problem with IDataError is that it doesn’t support a method/property to distinguish between error types.
The only way I can do that is by examining the error text, required field text must contain the key word “required”. The following approach doesn’t feel right but it’s the only way I can determine the type of error and then deal with it accordingly. All required field rules must have as part of the error text “required field”.
To make this all work I have created a custom dependency property called ErrorMessage. In my ResourceDictionary I have a Style.Trigger for Validation.HasError. In there I set my dependency properties value to the ErrorContent. Now when my dependency properties value changes I can examine the text and set the Validation.SetErrorTemplate( myControl, newErrorTemplate) to the template to suit the error type. I have to wire up a few events to the control such as lost and got focus to manage removing or adding the cueBanner template but the whole thing will work. It’s just that I’m not sure it’s the best way to do it.
PS. When I set the ErrorTemplate i’m doing this in code, thats building and adding it. Is there a way to point Validation.SetErrorTemplate to a static resource keeping in mind that I need to switch between at least 2 types?
Your thoughts please..
A: Would it be possible to derive an interface IDataError that adds an extra property which is an enumeration of the error type. Then you could try and bind against it.
A: If you're okay with an (untested)approach that suffers a little bit of clarity, then you could do the following:
throw an exception instead of returning an string with the IDataErrorInfo Interface. In your ErrorTemplate, you can access the ValidationErrors (and the ValidationError.Exception Property).
Then, you use a DataTrigger on the Exception in combination with a converter, that checks for the right Exception-Type and return true or false. It should be enough to do the job.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Does a definitive list of design patterns exist? Where did the idea of design patterns come from, who decided what is and isn't a pattern and gave them their names? Is there an official organisation that defines them, or do they exist through some community consensus?
A: Short answer: No.
Long answer: Since if someone designs something, and it tends to be reused by others a new "design pattern" will be just created ( or discovered?? )
Actually the number of design patterns in existing applications might be enormous, but none has classified them yet.
I would add the the previous links these two:
http://martinfowler.com/eaaCatalog/
http://c2.com/ppr/
A: I think there's a basic "life cycle of a design pattern"
*
*Author writes about design pattern in a book.
*Book becomes well read, possibly best seller
*Design pattern enters public conscious, gains mindshare.
*Design pattern gets used. It works well. design pattern gets more mindshare
*Design pattern becomes panacea, gets over-used.
*Different Author writes "Design Pattern Considered Harmful"
*Design pattern becomes Anti Pattern
*Different Author becomes famous, writes book full of new design patterns...
A: The idea of Design Patterns was coined by Christopher Alexander, while writing about architectural patterns within buildings and towns. Similarly, patterns have emerged as engineers have gained more experience with object oriented design methodologies.
There is not one official consortium that defines what is a pattern and what is not a pattern. However, patterns typically have a long lifecycle before they are generally accepted. The development community is beginning to participate in things like PLOP (Pattern Languages of Programs) and their yearly conference: 2008 Conference, which
focus on pattern authors and enthusiasts to discuss the subject of patterns and new pattern development.
A: There's no definitive list. Patterns are discovered, not invented, so there's no organization that can say "this is a pattern" and "this is not a pattern". Even if there were one, it wouldn't be useful for anybody.
Despite that, the "famous" patterns are the ones described in Design Patterns, or the GOF book.
A: It can also be useful to recognize anti-patterns.
A: This is a good list of patterns (from the Patterns of Enterprise Application Architecture book):
http://martinfowler.com/eaaCatalog/
A: There is no definitive list - for there to be one would most likely require some authority to declare whether a pattern is a pattern or just a ... something else.
Some patterns make sense only in a subset of languages - the canonical GOF book concentrates on Java (or is it C++? The book's on my desk at the office) and some of the patterns described aren't very relevant in, for example, Ruby or VB6. And vice versa of course.
A: Most people would point to the "Gang of Four" (Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides) who wrote the book Design Patterns: Elements of Reusable Object-Oriented Software. There is no real definitive list as useful design patterns are certainly being discovered all the time.
A: Wikipedia has a good list. http://en.wikipedia.org/wiki/Design_pattern_(computer_science)
Most are by community consensus (that community being of people who have read design patterns or code complete :/)
A: I would say that the Union of the list in the Gang of Four book and Fowler's Patterns of Enterprise Arhitecture will give you 99% of what you would ever need to know.
A: There is a canonical book: Gamma, Helm, Johnson, Vlissides: "Dessign Patterns - Elements of Reusable Object-Oriented Software" which started it all. It contains 23 patterns.
A: There can't be a definitive list. Ever.
If you see some solutions to a problem that -- to you -- have a pattern that can be articulated, you've discovered a design pattern. You can always continue doing this.
Every clever, new solution could be the genesis for a similar solution which shares a common pattern. Patterns are something you use to summarize and capture a cool solution to a problem.
The human brain can find patterns in almost anything. It's a thing we do without thinking about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: Adding referenced Eclipse projects to Maven dependencies Right now, I have two Eclipse projects - they both use Maven 2 for all their jar-dependency goodness.
Inside Eclipse, I have project Foo included in project Bar's build path, so that I can use Foo's classes from project Bar. This works really well in Eclipse land, but when I try:
mvn compile
inside Bar's directory, it fails because Maven doesn't know about the project-to-project relationship in Eclipse's build path.
If I were using Ant, I would just use it to do something silly like copy foo.jar into project Bar's classpath, but as far as I can tell, things are done a lot less hackishly in Maven-land.
I'm wondering if there's a standard workaround for this type of problem - it seems like it would be fairly common, and I'm just missing something basic about how Maven works.
A: Check out the m2eclipse plugin. It will automatically and dynamically update the project build path when you change the pom. There is no need for running mvn eclipse:eclipse.
The plugin will also detect if any dependency is in the same workspace and add that project to the build path.
Ideally, if you use m2eclipse, you would never change the project build path manually. You would always edit pom.xml instead, which is the proper way to do it.
As has been previously stated, Maven will not know about the Eclipse project build path. You do need to add all dependencies to the pom, and you need to make sure all dependencies are built and installed first by running mvn install.
If you want to build both projects with a single command then you might find project aggregation interesting.
A: I just needed to do this and I needed it to build with the external mvn clean install command. Here is the proper way to configure this in Eclipse. (With project B as a dependency of A)
*
*Open the pom.xml for project A in Eclipse.
*Go to the Dependencies tab.
*Click the Add... button in the middle of the page (for the left side Dependencies box)
*In the popup, there should be a box under a line with text above it saying Enter groupId, artifactId or sha1 prefix or pattern (*):. Enter the artifact ID for project B into this box.
*Double click the jar you want to add as a dependency to this project
*
*You may need to update the project after.
*Right click project A in you Package explorer
*Maven -> Update Project...
*Then hit OK in the popup.
A: Maybe you are referencing the other project via Eclipse configure-> build path only. This works as long as you use Eclipse to build your project.
Try running first mvn install in project Bar (in order to put Bar in your Maven repository), and then add the dependency to Foo's pom.xml.
That should work!.
A: You might want to try an alternative approach, where you have a parent maven project and two children project. let's say:
Parent (pom.xml has references to both children projects/modules)
--> A (depends on B)
--> B
then when you run mvn eclipse:eclipse from the root of Parent, maven will generate eclipse projects for A and B, and it will have B as a required project in the classpath of A.
You can run mvn install from the root of Parent to get both projects to compile.
To complete your setup, you'll have to import both A and B into Eclipse, making sure you don't check "Copy projects into workspace".
A: I think the best way to handle it is to make Bar a Maven project just like Foo, and then mvn install it so it is available in your local Maven repository. The drawback is that you have to install that project every time you want Maven to see the changes you make to Bar.
A: Not a complete answer:
Bar's pom needs to include Foo in order to use maven to compile it.
I'm interested in this question too, but from the perspective of how to get eclipse to recognise a maven-added dependency is actually another project in the same workspace. I currently alter the build path after performing mvn eclipse:eclipse
A: If you reference a local project, but its version has been updated (usually increased), it could maybe only be found in your local repo and you have to update the (likely fixed) version of it in your POM(s).
We have a "common project" (used everywhere) which does not necessarily need to be versioned since we tag it via source control. so either
*
*keeping it at a fixed version or
*referencing it with the special LATEST version
are good workarounds to always be on the safe side.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: How can I leverage an ORM for a database whose schema is unknown until runtime? I am trying to leverage ORM given the following requirements:
1) Using .NET Framework (latest Framework is okay)
2) Must be able to use Sybase, Oracle, MSSQL interchangeably
3) The schema is mostly static, BUT there are dynamic parts.
I am somewhat familiar with SubSonic and NHibernate, but not deeply.
I get the nagging feeling that the ORM can do what I want, but I don't know how to leverage it at the moment.
SubSonic probably isn't optimal, since it doesn't currently support Sybase, and writing my own provider for it is beyond my resources and ability right now.
For #3 (above), there are a couple of metadata tables, which describe tables which the vendors can "staple on" to the existing database.
Let's call these MetaTables, and MetaFields.
There is a base static schema, which the ORM (NHibernate ATM) handles nicely.
However, a vendor can add a table to the database (physically) as long as they also add the data to the metadata tables to describe their structure.
What I'd really like is for me to be able to somehow "feed" the ORM with that metadata (in a way that it understands) and have it at that point allow me to manipulate the data.
My primary goal is to reduce the amount of generic SQL statement building I have to do on these dynamic tables.
I'd also like to avoid having to worry about the differences in SQL being sent to Sybase,Oracle, or MSSQL.
My primary problem is that I don't have a way to let ORM know about the dynamic tables until runtime, when I'll have access to the metadata
Edit: An example of the usage might be like the one outlined here:
IDataReader rdr=new Query("DynamicTable1").WHERE("ArbitraryId",2).ExecuteReader();
(However, it doesn't look like SubSonic will work, as there is no Sybase provider (see above)
A: We did some of the using NHibernate, however we stopped the project since it didn't provide us with the ROI we wanted. We ended up writing our own ORM/SQL layer which worked very well (worked since I no longer work there, I'm guessing it still works).
Our system used a open source project to generate the SQL (don't remember the name any more) and we built all our queries in our own Xml based language (Query Markup Language - QML). We could then build an xmlDocument with selects, wheres, groups etc. and then send that to the SqlEngine that would turn it into a Sql statement and execute it. We discusse, but never implemented, a cache in all of this. That would've allowed us to cache the Qmls for frequently used queries.
A: Acording to this blog you can in fact use NHibernate with dynamic mapping. It takes a bit of tweaking though...
A: I am a little confused as to how the orm would be used then at runtime? If the ORM would dynamically build something at runtime, how does the runtime code know what the orm did dynamically?
"have it at that point allow me to manipulate the data" - What is manipulating the data?
I may be missing something here and i aplogize if thats the case. (I only have really used bottom up approach with ORM)
A: IDataReader doesn't map anything to an object you know. So your example should be written using classic query builder.
A: Have you looked into using the ADO.NET Entity Framework?
MSDN: LINQ to Entities
It allows you to map database tables to an object model in such a manner that you can code without thinking about which database vendor is being used, and without worrying about minor variations made by a DBA to the actual tables. The mapping is kept in configuration files that can be modified when the db tables are modified without requiring a recompile.
Also, using LINQ to Entities, you can build queries in an OO manner, so you aren't writing actual SQL query strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Reversing an RSS feed This could be weird, Have you ever come across a blog which you wanted to read in the chronological order? And that blog could be old, with several hundred posts. When i add this feed to my feed reader, say googlereader, the latest feed comes on top and as i scroll down further, the older posts appear. This could be frustrating if you want to read it from the beginning. Is there any reader that does this? Or, i would love to do this as a pet project, (preferably in c#), how exactly should i go about it? Also, are there any .NET libraries which i can use to work on RSS feeds? I have not done any RSS feed programming before.
EDIT I would like to know if there are any technical limitations to this. This was jsut one interesting problem that I encountered that i thought could be tackled programmatically.
A: In Google Reader, when you're reading a feed, there is a "Feed settings..." menu with the options: "Sort by newest", "Sort by oldest".
Folders have the same options under the menu "Folder settings..."
No programming required.
A: I think you might have trouble with this. Many RSS feeds only keep the latest 10 or so posts, so there would be no way to provide the older data from the feed since the blog started.
A: If you do decide to roll your own C# application to do this, it is very straightforward in the current version of the .NET Framework.
Look for the System.ServiceModel.Syndication namespace. That has classes related to RSS and Atom feeds. I wrote some code recently that generates a feed from a database using these classes, and adds geocodes to the feed items. I had the same problem where i needed to reverse the order of the items in the feed, because my database query returned them in the opposite order I wanted my users to see.
What I did was to simply hold the list of SyndicationItem objects for the feed in my own List<SyndicationItem> data structure until right before I want to write the feed to disk. Then I would do something like this:
private SyndicationFeed m_feed;
private List<SyndicationItem> m_items;
...snip...
m_items.Reverse();
m_feed.Items = m_items;
A: In Google Reader, you can have it display the items in a folder (feed) from either Newest to Oldest, or Oldest to Newest. To do this, select the feed, select the "Feed settings" drop down, and select "Sort by oldest". I'm not sure how far back Google Reader goes, but possibly all the way since it first started monitoring the feed.
A: This should be fairly easy with any language...all you would need to do is read the feed xml into a DOM structure (nearly all languauges including C# have a DomDocument class)
You should then be able to simply loop through the item nodes in reverse order...
see: http://msdn.microsoft.com/en-us/library/ms756177(VS.85).aspx
As other said, depending on the rss feed, you may only get a finite amount of items.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flex - Avoid click event on container when enclosed component is clicked I have a Flex application where I'm using a Canvas to contain several other components. On that Canvas there is a Button which is used to invoke a particular flow through the system. Clicking anywhere else on the Canvas should cause cause a details pane to appear showing more information about the record represented by this control.
The problem I'm having is that because the button sits inside the Canvas any time the user clicks the Button the click event is fired on both the Button and the Canvas. Is there any way to avoid having the click event fired on the Canvas object if the user clicks on an area covered up by another component?
I've created a simple little test application to demonstrate the problem:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
private function onCanvasClick(event:Event):void {
text.text = text.text + "\n" + "Canvas Clicked";
}
private function onButtonClick(event:Event):void {
text.text = text.text + "\n" + "Button Clicked";
}
]]>
</mx:Script>
<mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)">
<mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/>
</mx:Canvas>
<mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/>
</mx:Application>
As it stands when you click the button you will see two entries made in the text box, "Button Clicked" followed by "Canvas Clicked" even though the mouse was clicked only once.
I'd like to find a way that I could avoid having the second entry made such that when I click the Button only the "Button Clicked" entry is made, but if I were to click anywhere else in the Canvas the "Canvas Clicked" entry would still appear.
A: The event continues on because event.bubbles is set to true. This means everything in the display heirarchy gets the event. To stop the event from continuing, you call
event.stopImmediatePropagation()
A: Laplie's answer worked like a charm. For those interested the updated code looks like this:
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:Script>
<![CDATA[
private function onCanvasClick(event:Event):void {
text.text = text.text + "\n" + "Canvas Clicked";
}
private function onButtonClick(event:Event):void {
text.text = text.text + "\n" + "Button Clicked";
event.stopImmediatePropagation();
}
]]>
</mx:Script>
<mx:Canvas x="97" y="91" width="200" height="200" backgroundColor="red" click="onCanvasClick(event)">
<mx:Button x="67" y="88" label="Button" click="onButtonClick(event)"/>
</mx:Canvas>
<mx:Text id="text" x="97" y="330" text="Text" width="200" height="129"/>
</mx:Application>
The only difference is the one additional line in the onButtonClick method.
A: I have 2 ideas, first try this:
btn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{
event.stopImmediatePropagation();
...
});
if that doesn't work, see if you can add the click listener to the canvas and not the button and check the target property on the event object. something like:
btn.addEventListener(MouseEvent.Click,function(event:MouseEvent):void{
if(event.target == btn){
...
}
else{
...
}
});
Again, these are some ideas of the top of my head...I'll create a small test app and see if these work...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Get integer value of the current year in Java I need to determine the current year in Java as an integer. I could just use java.util.Date(), but it is deprecated.
A: For Java 8 onwards:
int year = Year.now().getValue();
For older version of Java:
int year = Calendar.getInstance().get(Calendar.YEAR);
A: Use the following code for java 8 :
LocalDate localDate = LocalDate.now();
int year = localDate.getYear();
int month = localDate.getMonthValue();
int date = localDate.getDayOfMonth();
A: You can also use Java 8's LocalDate:
import java.time.LocalDate;
//...
int year = LocalDate.now().getYear();
A: If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date is mutable. java.util.Calendar has performance problems when its fields get updated, and is clunky for datetime arithmetic.
A: As some people answered above:
If you want to use the variable later, better use:
int year;
year = Calendar.getInstance().get(Calendar.YEAR);
If you need the year for just a condition you better use:
Calendar.getInstance().get(Calendar.YEAR)
For example using it in a do while that checks introduced year is not less than the current year-200 or more than the current year (Could be birth year):
import java.util.Calendar;
import java.util.Scanner;
public static void main (String[] args){
Scanner scannernumber = new Scanner(System.in);
int year;
/*Checks that the year is not higher than the current year, and not less than the current year - 200 years.*/
do{
System.out.print("Year (Between "+((Calendar.getInstance().get(Calendar.YEAR))-200)+" and "+Calendar.getInstance().get(Calendar.YEAR)+") : ");
year = scannernumber.nextInt();
}while(year < ((Calendar.getInstance().get(Calendar.YEAR))-200) || year > Calendar.getInstance().get(Calendar.YEAR));
}
A: This simplest (using Calendar, sorry) is:
int year = Calendar.getInstance().get(Calendar.YEAR);
There is also the new Date and Time API JSR, as well as Joda Time
A: Using Java 8's time API (assuming you are happy to get the year in your system's default time zone), you could use the Year::now method:
int year = Year.now().getValue();
A: You can also use 2 methods from java.time.YearMonth( Since Java 8 ):
import java.time.YearMonth;
...
int year = YearMonth.now().getYear();
int month = YearMonth.now().getMonthValue();
A: tl;dr
ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) )
.getYear()
Time Zone
The answer by Raffi Khatchadourian wisely shows how to use the new java.time package in Java 8. But that answer fails to address the critical issue of time zone in determining a date.
int year = LocalDate.now().getYear();
That code depends on the JVM's current default time zone. The default zone is used in determining what today’s date is. Remember, for example, that in the moment after midnight in Paris the date in Montréal is still 'yesterday'.
So your results may vary by what machine it runs on, a user/admin changing the host OS time zone, or any Java code at any moment changing the JVM's current default. Better to specify the time zone.
By the way, always use proper time zone names as defined by the IANA. Never use the 3-4 letter codes that are neither standardized nor unique.
java.time
Example in java.time of Java 8.
int year = ZonedDateTime.now( ZoneId.of( "Africa/Casablanca" ) ).getYear() ;
Joda-Time
Some idea as above, but using the Joda-Time 2.7 library.
int year = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).getYear() ;
Incrementing/Decrementing Year
If your goal is to jump a year at a time, no need to extract the year number. Both Joda-Time and java.time have methods for adding/subtracting a year at a time. And those methods are smart, handling Daylight Saving Time and other anomalies.
Example in java.time.
ZonedDateTime zdt =
ZonedDateTime
.now( ZoneId.of( "Africa/Casablanca" ) )
.minusYears( 1 )
;
Example in Joda-Time 2.7.
DateTime oneYearAgo = DateTime.now( DateTimeZone.forID( "Africa/Casablanca" ) ).minusYears( 1 ) ;
A: The easiest way is to get the year from Calendar.
// year is stored as a static member
int year = Calendar.getInstance().get(Calendar.YEAR);
A: If you want the year of any date object, I used the following method:
public static int getYearFromDate(Date date) {
int result = -1;
if (date != null) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
result = cal.get(Calendar.YEAR);
}
return result;
}
A: In my case none of the above is worked. So After trying lot of solutions i found below one and it worked for me
import java.util.Scanner;
import java.util.Date;
public class Practice
{
public static void main(String[] args)
{
Date d=new Date();
int year=d.getYear();
int currentYear=year+1900;
System.out.println(currentYear);
}
}
A: I may add that a simple way to get the current year as an integer is importing
java.time.LocalDate and, then:
import java.time.LocalDate;
int yourVariable = LocalDate.now().getYear()
Hope this helps!
A: I use special functions in my library to work with days/month/year ints -
int[] int_dmy( long timestamp ) // remember month is [0..11] !!!
{
Calendar cal = new GregorianCalendar(); cal.setTimeInMillis( timestamp );
return new int[] {
cal.get( Calendar.DATE ), cal.get( Calendar.MONTH ), cal.get( Calendar.YEAR )
};
};
int[] int_dmy( Date d ) {
...
}
A: In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD and java.time.Instant uses it, so (for UTC):
import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));
P.S. just in case (and shorted for getting String, not int), using Calendar looks better and can be made zone-aware.
A: You can do the whole thing using Integer math without needing to instantiate a calendar:
return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);
May be off for an hour or two at new year but I don't get the impression that is an issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "365"
}
|
Q: Don't wait for the process to exit I have a PHP script that is called from a cron job every minute. This script takes some info from the database and then calls another PHP script using the System function (passing it some parameters).
That means that I can start up to 10 scripts from this "main" one. And what I would like to do is that I would call the script and continue the execution of the main script, that is, not wait for the System call to complete and then call the next one.
How can this be done?
A: You may be able to use proc_open(), stream_select() and stream_set_blocking() in concert to achieve this kind of thing.
If that sounds vague, I was going to paste a big chunk of code in here that I used in a recent project that did something similar, but then felt it may hinder rather than help! In summary though, the code worked like this:
*
*cronjob calls cronjob_wrapper.php
*cronjob_wrapper.php creates a new Manager class and then calls start on it.
*Manager class start method check to see how many instances are running (looking for pid files in a particular location). If it's less than a given max number of instances it writes out it's own process id to a pid file and then carries on
*Manage class creates an instance of an appropriate Encoder class and calls exec on it.
*The exec method uses proc_open, stream_select and stream_set_blocking to run a system command in a non-blocking fashion (running ffmpeg in this case - and could take quite a while!)
*When it has finally run it cleans up its PID file and bails out.
Now the reason I'm being vague and handwavy is that our multiple instances here are being handled by the cronjob not by PHP. I was trying to do very much the kind of thing you are talking about, and got something working pretty well with pcntl_fork() and friends, but in the end I encountered a couple of problems (if I recall at least one was a bug in PHP) and decided that this approach was a much more rock-solid way to achieve the same thing. YMMV.
Well worth a look at those functions though, you can achieve a lot with them. Though somehow I don't think PHP will ever become the sockets programming language of choice... :)
A: If your OS supports it, you can use the pcntl_fork() function to spin off child processes that the parent doesn't wait for. Be careful though, it is easy to accidentally create too many child processes, especially if they take longer than expected to run!
A: I think the answer would be very similar to those already provided for Asynchronous PHP calls.
A: http://php.net/pcntl_fork
It's *NIX only but you can fork your script using the PCNTL extension.
A: use php's version of fork or threads.
A: I'm not sure that PHP supports threading. Check here.
A: You could run them in the background:
system('php yourscript.php &');
You just have to make sure that you check on the total number of processes running. All in all, not a super elegant solution. Instead cron you could let one script run for forever, I am thinking something like this:
<?php
while(true) {
// do whatever needs to be done.
}
?>
Careful though. PHP is not exactly known to be used as a daemon.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compressing HTTP request with LWP, Apache, and mod_deflate I have a client/server system that performs communication using XML transferred using HTTP requests and responses with the client using Perl's LWP and the server running Perl's CGI.pm through Apache. In addition the stream is encrypted using SSL with certificates for both the server and all clients.
This system works well, except that periodically the client needs to send really large amounts of data. An obvious solution would be to compress the data on the client side, send it over, and decompress it on the server. Rather than implement this myself, I was hoping to use Apache's mod_deflate's "Input Decompression" as described here.
The description warns:
If you evaluate the request body yourself, don't trust the Content-Length header! The Content-Length header reflects the length of the incoming data from the client and not the byte count of the decompressed data stream.
So if I provide a Content-Length value which matches the compressed data size, the data is truncated. This is because mod_deflate decompresses the stream, but CGI.pm only reads to the Content-Length limit.
Alternatively, if I try to outsmart it and override the Content-Length header with the decompressed data size, LWP complains and resets the value to the compressed length, leaving me with the same problem.
Finally, I attempted to hack the part of LWP which does the correction. The original code is:
# Set (or override) Content-Length header
my $clen = $request_headers->header('Content-Length');
if (defined($$content_ref) && length($$content_ref)) {
$has_content = length($$content_ref);
if (!defined($clen) || $clen ne $has_content) {
if (defined $clen) {
warn "Content-Length header value was wrong, fixed";
hlist_remove(\@h, 'Content-Length');
}
push(@h, 'Content-Length' => $has_content);
}
}
elsif ($clen) {
warn "Content-Length set when there is no content, fixed";
hlist_remove(\@h, 'Content-Length');
}
And I changed the push line to:
push(@h, 'Content-Length' => $clen);
Unfortunately this causes some problem where content (truncated or not) doesn't even get to my CGI script.
Has anyone made this work? I found this which does compression on a file before uploading, but not compressing a generic request.
A: I don't think you can change the Content-Length like that. It would confuse Apache, because mod_deflate wouldn't know how much compressed data to read. What about having the client add an X-Uncompressed-Length header, and then use a modified version of CGI.pm that uses X-Uncompressed-Length (if present) instead of Content-Length? (Actually, you probably don't need to modify CGI.pm. Just set $ENV{'CONTENT_LENGTH'} to the appropriate value before initializing the CGI object or calling any CGI functions.)
Or, use a lower-level module that uses the bucket brigade to tell how much data to read.
A: Although you said you didn't want to do the compression yourself, there are lots of perl modules which will do both sides for you, Compress::Zlib for example.
I have a cheat (with a .net part of the company) where I get passed XML as a separate parameter posted in, then can handle it as if it was a string rather than faffing about with SOAP like stuff.
A: I am not sure if I am following you with what you want, but I have a custom get/post module, that I use to do some non standard stuff. The below code will read in anything sent via post, or STDIN.
read(STDIN, $query_string, $ENV{'CONTENT_LENGTH'});
Instead of using using $ENV's value use your's. I hope this helps, and sorry if it doesn't.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Any way to make a WPF textblock selectable? How to allow TextBlock's text to be selectable?
I tried to get it to work by displaying the text using a read-only TextBox styled to look like a textblock but this will not work in my case because a TextBox does not have inlines. In other words, how to make it selectable?
A: All the answers here are just using a TextBox or trying to implement text selection manually, which leads to poor performance or non-native behaviour (blinking caret in TextBox, no keyboard support in manual implementations etc.)
After hours of digging around and reading the WPF source code, I instead discovered a way of enabling the native WPF text selection for TextBlock controls (or really any other controls). Most of the functionality around text selection is implemented in System.Windows.Documents.TextEditor system class.
To enable text selection for your control you need to do two things:
*
*Call TextEditor.RegisterCommandHandlers() once to register class
event handlers
*Create an instance of TextEditor for each instance of your class and pass the underlying instance of your System.Windows.Documents.ITextContainer to it
There's also a requirement that your control's Focusable property is set to True.
This is it! Sounds easy, but unfortunately TextEditor class is marked as internal. So I had to write a reflection wrapper around it:
class TextEditorWrapper
{
private static readonly Type TextEditorType = Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo IsReadOnlyProp = TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly PropertyInfo TextViewProp = TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
private static readonly MethodInfo RegisterMethod = TextEditorType.GetMethod("RegisterCommandHandlers",
BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);
private static readonly Type TextContainerType = Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
private static readonly PropertyInfo TextContainerTextViewProp = TextContainerType.GetProperty("TextView");
private static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);
public static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
{
RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
}
public static TextEditorWrapper CreateFor(TextBlock tb)
{
var textContainer = TextContainerProp.GetValue(tb);
var editor = new TextEditorWrapper(textContainer, tb, false);
IsReadOnlyProp.SetValue(editor._editor, true);
TextViewProp.SetValue(editor._editor, TextContainerTextViewProp.GetValue(textContainer));
return editor;
}
private readonly object _editor;
public TextEditorWrapper(object textContainer, FrameworkElement uiScope, bool isUndoEnabled)
{
_editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null, new[] { textContainer, uiScope, isUndoEnabled }, null);
}
}
I also created a SelectableTextBlock derived from TextBlock that takes the steps noted above:
public class SelectableTextBlock : TextBlock
{
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
private readonly TextEditorWrapper _editor;
public SelectableTextBlock()
{
_editor = TextEditorWrapper.CreateFor(this);
}
}
Another option would be to create an attached property for TextBlock to enable text selection on demand. In this case, to disable the selection again, one needs to detach a TextEditor by using the reflection equivalent of this code:
_editor.TextContainer.TextView = null;
_editor.OnDetach();
_editor = null;
A: According to Windows Dev Center:
TextBlock.IsTextSelectionEnabled property
[ Updated for UWP apps on Windows 10. For Windows 8.x articles, see
the archive ]
Gets or sets a value that indicates whether text selection is enabled
in the TextBlock, either through user action or calling
selection-related API.
A: While the question does say 'Selectable' I believe the intentional results is to get the text to the clipboard. This can easily and elegantly be achieved by adding a Context Menu and menu item called copy that puts the Textblock Text property value in clipboard. Just an idea anyway.
A: I have been unable to find any example of really answering the question. All the answers used a Textbox or RichTextbox. I needed a solution that allowed me to use a TextBlock, and this is the solution I created.
I believe the correct way to do this is to extend the TextBlock class. This is the code I used to extend the TextBlock class to allow me to select the text and copy it to clipboard. "sdo" is the namespace reference I used in the WPF.
WPF Using Extended Class:
xmlns:sdo="clr-namespace:iFaceCaseMain"
<sdo:TextBlockMoo x:Name="txtResults" Background="Black" Margin="5,5,5,5"
Foreground="GreenYellow" FontSize="14" FontFamily="Courier New"></TextBlockMoo>
Code Behind for Extended Class:
public partial class TextBlockMoo : TextBlock
{
TextPointer StartSelectPosition;
TextPointer EndSelectPosition;
public String SelectedText = "";
public delegate void TextSelectedHandler(string SelectedText);
public event TextSelectedHandler TextSelected;
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
Point mouseDownPoint = e.GetPosition(this);
StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true);
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
Point mouseUpPoint = e.GetPosition(this);
EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);
TextRange otr = new TextRange(this.ContentStart, this.ContentEnd);
otr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.GreenYellow));
TextRange ntr = new TextRange(StartSelectPosition, EndSelectPosition);
ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.White));
SelectedText = ntr.Text;
if (!(TextSelected == null))
{
TextSelected(SelectedText);
}
}
}
Example Window Code:
public ucExample(IInstanceHost host, ref String WindowTitle, String ApplicationID, String Parameters)
{
InitializeComponent();
/*Used to add selected text to clipboard*/
this.txtResults.TextSelected += txtResults_TextSelected;
}
void txtResults_TextSelected(string SelectedText)
{
Clipboard.SetText(SelectedText);
}
A: TextBlock does not have a template. So inorder to achieve this, we need to use a TextBox whose style is changed to behave as a textBlock.
<Style x:Key="TextBlockUsingTextBoxStyle" BasedOn="{x:Null}" TargetType="{x:Type TextBox}">
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBoxBorder}"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="AllowDrop" Value="true"/>
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="ScrollViewer.PanningMode" Value="VerticalFirst"/>
<Setter Property="Stylus.IsFlicksEnabled" Value="False"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<TextBox BorderThickness="{TemplateBinding BorderThickness}" IsReadOnly="True" Text="{TemplateBinding Text}" Background="{x:Null}" BorderBrush="{x:Null}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
A: Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.
<TextBox Background="Transparent"
BorderThickness="0"
Text="{Binding Text, Mode=OneWay}"
IsReadOnly="True"
TextWrapping="Wrap" />
A: Create ControlTemplate for the TextBlock and put a TextBox inside with readonly property set.
Or just use TextBox and make it readonly, then you can change the TextBox.Style to make it looks like TextBlock.
A: Apply this style to your TextBox and that's it (inspired from this article):
<Style x:Key="SelectableTextBlockLikeStyle" TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
<Setter Property="IsReadOnly" Value="True"/>
<Setter Property="IsTabStop" Value="False"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Padding" Value="-2,0,0,0"/>
<!-- The Padding -2,0,0,0 is required because the TextBox
seems to have an inherent "Padding" of about 2 pixels.
Without the Padding property,
the text seems to be 2 pixels to the left
compared to a TextBlock
-->
<Style.Triggers>
<MultiTrigger>
<MultiTrigger.Conditions>
<Condition Property="IsMouseOver" Value="False" />
<Condition Property="IsFocused" Value="False" />
</MultiTrigger.Conditions>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TextBox}">
<TextBlock Text="{TemplateBinding Text}"
FontSize="{TemplateBinding FontSize}"
FontStyle="{TemplateBinding FontStyle}"
FontFamily="{TemplateBinding FontFamily}"
FontWeight="{TemplateBinding FontWeight}"
TextWrapping="{TemplateBinding TextWrapping}"
Foreground="{DynamicResource NormalText}"
Padding="0,0,0,0"
/>
</ControlTemplate>
</Setter.Value>
</Setter>
</MultiTrigger>
</Style.Triggers>
</Style>
A: I'm not sure if you can make a TextBlock selectable, but another option would be to use a RichTextBox - it is like a TextBox as you suggested, but supports the formatting you want.
A: There is an alternative solution that might be adaptable to the RichTextBox oultined in this blog post - it used a trigger to swap out the control template when the use hovers over the control - should help with performance
A:
new TextBox
{
Text = text,
TextAlignment = TextAlignment.Center,
TextWrapping = TextWrapping.Wrap,
IsReadOnly = true,
Background = Brushes.Transparent,
BorderThickness = new Thickness()
{
Top = 0,
Bottom = 0,
Left = 0,
Right = 0
}
};
A: Here is what worked for me. I created a class TextBlockEx that is derived from TextBox and is set read-only, and text wrap in the constructor.
public class TextBlockEx : TextBox
{
public TextBlockEx()
{
base.BorderThickness = new Thickness(0);
IsReadOnly = true;
TextWrapping = TextWrapping.Wrap;
//Background = Brushes.Transparent; // Uncomment to get parent's background color
}
}
A: Really nice and easy solution, exactly what I wanted !
I bring some small modifications
public class TextBlockMoo : TextBlock
{
public String SelectedText = "";
public delegate void TextSelectedHandler(string SelectedText);
public event TextSelectedHandler OnTextSelected;
protected void RaiseEvent()
{
if (OnTextSelected != null){OnTextSelected(SelectedText);}
}
TextPointer StartSelectPosition;
TextPointer EndSelectPosition;
Brush _saveForeGroundBrush;
Brush _saveBackGroundBrush;
TextRange _ntr = null;
protected override void OnMouseDown(MouseButtonEventArgs e)
{
base.OnMouseDown(e);
if (_ntr!=null) {
_ntr.ApplyPropertyValue(TextElement.ForegroundProperty, _saveForeGroundBrush);
_ntr.ApplyPropertyValue(TextElement.BackgroundProperty, _saveBackGroundBrush);
}
Point mouseDownPoint = e.GetPosition(this);
StartSelectPosition = this.GetPositionFromPoint(mouseDownPoint, true);
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
Point mouseUpPoint = e.GetPosition(this);
EndSelectPosition = this.GetPositionFromPoint(mouseUpPoint, true);
_ntr = new TextRange(StartSelectPosition, EndSelectPosition);
// keep saved
_saveForeGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.ForegroundProperty);
_saveBackGroundBrush = (Brush)_ntr.GetPropertyValue(TextElement.BackgroundProperty);
// change style
_ntr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
_ntr.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.DarkBlue));
SelectedText = _ntr.Text;
}
}
A: public MainPage()
{
this.InitializeComponent();
...
...
...
//Make Start result text copiable
TextBlockStatusStart.IsTextSelectionEnabled = true;
}
A: Adding to @torvin's answer and as @Dave Huang mentioned in the comments if you have TextTrimming="CharacterEllipsis" enabled the application crashes when you hover over the ellipsis.
I tried other options mentioned in the thread about using a TextBox but it really doesn't seem to be the solution either as it doesn't show the 'ellipsis' and also if the text is too long to fit the container selecting the content of the textbox 'scrolls' internally which isn't a TextBlock behaviour.
I think the best solution is @torvin's answer but has the nasty crash when hovering over the ellipsis.
I know it isn't pretty, but subscribing/unsubscribing internally to unhandled exceptions and handling the exception was the only way I found of solving this problem, please share if somebody has a better solution :)
public class SelectableTextBlock : TextBlock
{
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
TextEditorWrapper.RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
private readonly TextEditorWrapper _editor;
public SelectableTextBlock()
{
_editor = TextEditorWrapper.CreateFor(this);
this.Loaded += (sender, args) => {
this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;
this.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
};
this.Unloaded += (sender, args) => {
this.Dispatcher.UnhandledException -= Dispatcher_UnhandledException;
};
}
private void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (!string.IsNullOrEmpty(e?.Exception?.StackTrace))
{
if (e.Exception.StackTrace.Contains("System.Windows.Controls.TextBlock.GetTextPositionFromDistance"))
{
e.Handled = true;
}
}
}
}
A: Just use a FlowDocument inside a FlowDocumentScrollViewer, passing your inlines to the element.
You can control the style of the element, in my case I added a small border.
<FlowDocumentScrollViewer Grid.Row="2" Margin="5,3" BorderThickness="1"
BorderBrush="{DynamicResource Element.Border}"
VerticalScrollBarVisibility="Auto">
<FlowDocument>
<Paragraph>
<Bold>Some bold text in the paragraph.</Bold>
Some text that is not bold.
</Paragraph>
<List>
<ListItem>
<Paragraph>ListItem 1</Paragraph>
</ListItem>
<ListItem>
<Paragraph>ListItem 2</Paragraph>
</ListItem>
<ListItem>
<Paragraph>ListItem 3</Paragraph>
</ListItem>
</List>
</FlowDocument>
</FlowDocumentScrollViewer>
A: I agree most answers here do not create a selectable TextBlock. @Billy Willoughby's worked well however it didn't have a visible cue for selection. I'd like to extend his extension which can highlight text as it is selected. It also incorporates double and triple click selection. You can add a context menu with a "Copy" if needed.
It uses the Background property to "highlight" the selection so it is limited in that it will overwrite Run.Background
https://github.com/mwagnerEE/WagnerControls
A: Added Selection & SelectionChanged Event to torvin's code
public class SelectableTextBlock : TextBlock
{
static readonly Type TextEditorType
= Type.GetType("System.Windows.Documents.TextEditor, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
static readonly PropertyInfo IsReadOnlyProp
= TextEditorType.GetProperty("IsReadOnly", BindingFlags.Instance | BindingFlags.NonPublic);
static readonly PropertyInfo TextViewProp
= TextEditorType.GetProperty("TextView", BindingFlags.Instance | BindingFlags.NonPublic);
static readonly MethodInfo RegisterMethod
= TextEditorType.GetMethod("RegisterCommandHandlers",
BindingFlags.Static | BindingFlags.NonPublic, null, new[] { typeof(Type), typeof(bool), typeof(bool), typeof(bool) }, null);
static readonly Type TextContainerType
= Type.GetType("System.Windows.Documents.ITextContainer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
static readonly PropertyInfo TextContainerTextViewProp
= TextContainerType.GetProperty("TextView");
static readonly PropertyInfo TextContainerTextSelectionProp
= TextContainerType.GetProperty("TextSelection");
static readonly PropertyInfo TextContainerProp = typeof(TextBlock).GetProperty("TextContainer", BindingFlags.Instance | BindingFlags.NonPublic);
static void RegisterCommandHandlers(Type controlType, bool acceptsRichContent, bool readOnly, bool registerEventListeners)
{
RegisterMethod.Invoke(null, new object[] { controlType, acceptsRichContent, readOnly, registerEventListeners });
}
static SelectableTextBlock()
{
FocusableProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata(true));
RegisterCommandHandlers(typeof(SelectableTextBlock), true, true, true);
// remove the focus rectangle around the control
FocusVisualStyleProperty.OverrideMetadata(typeof(SelectableTextBlock), new FrameworkPropertyMetadata((object)null));
}
//private readonly TextEditorWrapper _editor;
object? textContainer;
object? editor;
public TextSelection TextSelection { get; private set; }
public SelectableTextBlock()
{
textContainer = TextContainerProp.GetValue(this);
editor = Activator.CreateInstance(TextEditorType, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.CreateInstance,
null, new[] { textContainer, this, false }, null);
IsReadOnlyProp.SetValue(editor, true);
TextViewProp.SetValue(editor, TextContainerTextViewProp.GetValue(textContainer));
TextSelection = (TextSelection)TextContainerTextSelectionProp.GetValue(textContainer);
TextSelection.Changed += (s, e) => OnSelectionChanged?.Invoke(this, e);
}
public event EventHandler OnSelectionChanged;
}
A: I've implemented SelectableTextBlock in my opensource controls library. You can use it like this:
<jc:SelectableTextBlock Text="Some text" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "257"
}
|
Q: How do I run a series of processes in C# and keep their environment settings? I am developing an auto-builder that will run a series of steps in our build process and build our target application. We used to use a batch file which set up a bunch of environment variables or called tools that setup environment variables and ultimately runs a 'make'.
I've been using the 'Process' class which works great for running those commands but unfortunately every time one runs which makes changes to the environment (like adding something to the PATH) those variables are lost when the 'Process' completes. The next 'Process' is instantiated and inherits the env from the 'calling' app (my exe) again - which means all env setup by the last command are lost. How do you handle this situation? Is there a better way to run a series of batch-file like commands within C# and maintain the environment they set up?
Please note that unfortunately the old-schoolers have declared that nant/ant are not an option so "Hey, why not use Nant - it does that!" is not the answer I am looking for.
Thanks.
A: Well, the System.Environment.SetEnvironmentVariable() method will let you specify the scope for a variable that you set. Is this what you are looking for? Not sure that I understand.
A: We use CruiseControl.net to run an NAnt script. Highly recommended.
The NAnt script can be invoked using -D: command-line switch to set the equivalent of environment variables.
A: i would suggest some code that would save your environment variables to an external file, and then you can retrieve these variables via the external file at the start of following processes.
A: I think the problem is not in specifying custom environment variables here. (You can set them via ProcessStartInfo.) The problem is in reading the changes made to environment variables by the processes being run. I'm not sure if it's possible. The only ways I know set environment variables for the process itself and/or for its child processes. I don't know no way to set environment variables for a parent process.
A: Environment variables are never set and cannot be set for the parent process (*). Only for the current process and the ones it creates - that is part of the concept.
(*) apart from, maybe, messing around with OS-internals.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136436",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why doesn't IE7 copy blocks to the clipboard correctly? We've noticed that IE7 has an odd behavor with code blocks posted on Stack Overflow. For example, this little code block:
public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
Copy and pasted from IE7, ends up like this:
public PageSizer(string href, int index){ HRef = href; PageIndex = index; }
Not exactly what we had in mind.. the underlying HTML source actually looks fine; if you View Source, you'll see this:
<pre><code>public PageSizer(string href, int index)
{
HRef = href;
PageIndex = index;
}
</code></pre>
So what are we doing wrong? Why can't IE7 copy and paste this HTML in a rational way?
Update: this specifically has to do with <pre> <code> blocks that are being modified at runtime via JavaScript. The native HTML does render and copy correctly; it's the JavaScript modified version of that HTML which doesn't behave as expected. Note that copying and pasting into WordPad or Word works because IE is putting different content in the rich text clipboard compared to the plain text clipboard that Notepad gets its data from.
A: It seems that this is a known bug for IE6 and prettify.js has a workaround for it. Specifically it replaces the BR tags with '\r\n'.
By modifying the check to allow for IE6 or 7 then the cut-and-paste will work correctly from IE7, but it will render with a newline followed by a space. By checking for IE7 and providing just a '\r' instead of a '\r\n' it will continue to cut-and-paste and render correctly.
Add this code to prettify.js:
function _pr_isIE7() {
var isIE7 = navigator && navigator.userAgent &&
/\bMSIE 7\./.test(navigator.userAgent);
_pr_isIE7 = function () { return isIE7; };
return isIE7;
}
and then modify the prettyPrint function as follows:
function prettyPrint(opt_whenDone) {
var isIE6 = _pr_isIE6();
+ var isIE7 = _pr_isIE7();
...
- if (isIE6 && cs.tagName === 'PRE') {
+ if ((isIE6 || isIE7) && cs.tagName === 'PRE') {
var lineBreaks = cs.getElementsByTagName('br');
+ var newline;
+ if (isIE6) {
+ newline = '\r\n';
+ } else {
+ newline = '\r';
+ }
for (var j = lineBreaks.length; --j >= 0;) {
var lineBreak = lineBreaks[j];
lineBreak.parentNode.replaceChild(
- document.createTextNode('\r\n'), lineBreak);
+ document.createTextNode(newline), lineBreak);
}
You can see a working example here.
Note: I haven't tested the original workaround in IE6, so I'm guessing it renders without the space caused by the '\n' that is seen in IE7, otherwise the fix is simpler.
A: This looks like a bug in IE, BR tags inside the PRE or CODE are not being converted into newlines in the plain text copy buffer. The rich text copy buffer is fine, so the paste works as expected for applications like wordpad.
The prettify script, that colours the code, removes all the whitespace and replaces it with HTML tags for spaces and new lines. The generated code looks something like this:
<pre><code>code<br/> code<br/> code<br/>code</code></pre>
The PRE and CODE tags are rendered by defaults with the CSS style of {whitespace: pre}. In this case, IE is failing to turn the BR tags into newlines. It would work on your original HTML because IE will successfully turn actual newlines into newlines.
In order to fix it you have 3 options. (I am presuming you want nice HTML and the ability to work well with and without javascript enabled on the client):
*
*You could place the code inside a normal div and use CSS to render it using {whitespace: pre}. This is a simple solution, although might not please an HTML markup purist.
*You could have two copies of the code, one using proper PRE / CODE tags and another in a normal div. In your CSS you hide the normal div. Using javascript you prettify the normal div and hide the pre/code version.
*Modify the prettify script to recognise that it is acting on a PRE or CODE element and to not replace the whitespace in that event.
Notes:
*
*What is important is not the HTML in your source, but the HTML that is generated after the prettify script has ran on it.
*This bug is still present even if the white-space mode of the PRE is changed to normal using CSS.
A: Here's the issue:
Your code colorization script replaces line breaks with <br /> tags. When copying/pasting, IE7 apparently doesn't translate the <br /> tag into a linebreak like it does for the screen.
In other words, your code becomes this:
public PageSizer(string href, int index)<br />{<br /> HRef = href;<br /> PageIndex = index;<br /> }
But you want it to become this:
public PageSizer(string href, int index)<br />
{<br />
HRef = href;<br />
PageIndex = index;<br />
}<br />
In the latest version of prettify.js on Google Code, the line responsible is line 1001 (part of recombineTagsAndDecorations):
html.push(htmlChunk.replace(newlineRe, '<br />'));
Edited, based on the comments:
For IE7, this is what the line should probably be changed to:
html.push(htmlChunk.replace(newlineRe, '\n'));
(Assuming newlineRe is a placeholder).
This fix also holds up in Chrome, and FFX3... I'm not sure which (if any) browsers need the <br /> tags.
Update:
More information in my second response:
Why doesn't IE7 copy <pre><code> blocks to the clipboard correctly?
A: This site has addressed the issue: http://www.developerfusion.com/tools/convert/csharp-to-vb/
I suggest a "Copy to Clipboard" button as part of the code display box.
This button would copy version of the displayed information as plain text.
The plain text could be stored as an internal page property.
A: bad news : none of the proposed fixes work. Modifying prettify.js around line 1000
html.push(htmlChunk.replace(newlineRe, '\n'));
This causes double-spacing in other browsers, and still doesn't solve the IE7 copy to notepad problem! So even if I selectively detected IE7, this "fix" doesn't fix anything.
I guess maybe it is simply a bug in IE7 having to do with JavaScript rebuilding a <pre> element -- no matter how many \n newlines I put in there, nothing changes w/r/t to the paste to notepad behavior.
A: @Jeff Atwood
It's the right idea, but the implementation still needs work. I guess my air code just didn't cut it :)
I suspect that the fix I mentioned earlier doesn't work because prettify is doing some additional processing on the text after line ~1000 is called.
Trying to track the content backwards from when it's added to the page, I came across this comment around line 1227:
// Replace <br>s with line-feeds so that copying and pasting works
// on IE 6.
// Doing this on other browsers breaks lots of stuff since \r\n is
// treated as two newlines on Firefox, and doing this also slows
// down rendering.
When I took the isIE6 condition off of the code, it mostly worked in IE7 (there was an extra line break at the top and bottom), and Firefox 3... But I'd assume that it causes issues with older versions of FFX.
At the very least, it appears that IE7 will require \r\n, instead of just \n. Figuring out exactly what will work with which browsers will take a more extensive test setup than I have handy at the moment.
Anyway, inserting the \r\n for IE7 appears to be basically what needs to happen. I'll keep poking around prettify to see if I can narrow it down further.
UPDATE: IE7 appears to strip newline characters (\r or \n) from strings that are assigned to an innerHTML property. It looks like they need to be added back in, around line 1227.
A correct solution would probably mean inserting a placeholder tag around line 1000, and then replacing it around line 1227.
A: Remove the inner <code>. IE's copy/paste behavior could see that as an inline tag and forget about the visible whitespace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
}
|
Q: How do I send an ARP packet from a C program? I'm working on an embedded linux system in C, I'm looking for the source code to the equivalet of SendARP in Windows. Any pointers?
A: Take a look at arping. The quick and dirty way of sending an arp would be to do:
foo = system("/somepath/arping somehost");
But a look through the arping source should be able to give you a better solution.
For the all-out solution though, you can construct your own by hand and use either a raw socket or libpcap to send it.
btw. If all you're trying to do is force an arp to be sent (but necessarily from you) you could achieve that by deleting any arp entry that you already have for your host. The next access to that address will require an arp to be sent.
eg. /usr/sbin/arp -d destination_host_ip
A: This may be of interest: http://cvs.linux-ha.org/viewcvs/viewcvs.cgi/linux-ha/resources/heartbeat/SendArp.in?rev=1.4
It is an implmenetation in a Bourne Shell script.
A: I've never seen anything specifically for ARP, but I think you can send any kind of packet you want using libpcap and the appropriate RFCs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Probability problem - Duplicates when choosing from large basket I need to explain to the client why dupes are showing up between 2 supposedly different exams. It's been 20 years since Prob and Stats.
I have a generated Multiple choice exam.
There are 192 questions in the database,
100 are chosen at random (no dupes).
Obviously, there is a 100% chance of there being at least 8 dupes between any two exams so generated. (Pigeonhole principle)
How do I calculate the probability of there being
25 dupes?
50 dupes?
75 dupes?
-- Edit after the fact --
I ran this through excel, taking sums of the probabilities from n-100,
For this particular problem, the probabilities were
n P(n+ dupes)
40 97.5%
52 ~50%
61 ~0
A: Erm, this is really really hazy for me. But there are (192 choose 100) possible exams, right?
And there are (100 choose N) ways of picking N dupes, each with (92 choose 100-N) ways of picking the rest of the questions, no?
So isn't the probability of picking N dupes just:
(100 choose N) * (92 choose 100-N) / (192 choose 100)
EDIT: So if you want the chances of N or more dupes instead of exactly N, you have to sum the top half of that fraction for all values of N from the minimum number of dupes up to 100.
Errrr, maybe...
A: Its probably higher than you think. I won't attempt to duplicate this article: http://en.wikipedia.org/wiki/Birthday_paradox
A: Once you've created the first exam, there are 92 questions that have never been used, and 100 that have. If you now generate another exam, with 100 questions in in it, you are chosing from a set of 92 questions that have never been used, and 100 that have. Clearly you are going to get quite a few duplicates.
You would expect to get (100/192) * 100 duplicates, i.e. in any two randomly chosen exams, there will (on average) be 52 duplicate questions.
If you want the probability that there are 25, or 75, or whatever, then you have two choices.
a) Work out the maths
b) Simulate a few runs on a computer
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Change the URL in the browser without loading the new page using JavaScript How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark, then the new URL is used?
It would also be nice if the back button would reload the original URL.
I am trying to record JavaScript state in the URL.
A: Browser security settings prevent people from modifying the displayed url directly. You could imagine the phishing vulnerabilities that would cause.
Only reliable way to change the url without changing pages is to use an internal link or hash. e.g.: http://site.com/page.html becomes http://site.com/page.html#item1 . This technique is often used in hijax(AJAX + preserve history).
When doing this I'll often just use links for the actions with the hash as the href, then add click events with jquery that use the requested hash to determine and delegate the action.
I hope that sets you on the right path.
A: There is a Yahoo YUI component (Browser History Manager) which can handle this: http://developer.yahoo.com/yui/history/
A: window.location.href contains the current URL. You can read from it, you can append to it, and you can replace it, which may cause a page reload.
If, as it sounds like, you want to record javascript state in the URL so it can be bookmarked, without reloading the page, append it to the current URL after a # and have a piece of javascript triggered by the onload event parse the current URL to see if it contains saved state.
If you use a ? instead of a #, you will force a reload of the page, but since you will parse the saved state on load this may not actually be a problem; and this will make the forward and back buttons work correctly as well.
A: Facebook's photo gallery does this using a #hash in the URL. Here are some example URLs:
Before clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507
After clicking 'next':
/photo.php?fbid=496429237507&set=a.218088072507.133423.681812507&pid=5887027&id=681812507#!/photo.php?fbid=496435457507&set=a.218088072507.133423.681812507&pid=5887085&id=681812507
Note the hash-bang (#!) immediately followed by the new URL.
A: A more simple answer i present,
window.history.pushState(null, null, "/abc")
this will add /abc after the domain name in the browser URL. Just copy this code and paste it in the browser console and see the URL changing to "https://stackoverflow.com/abc"
A: I would strongly suspect this is not possible, because it would be an incredible security problem if it were. For example, I could make a page which looked like a bank login page, and make the URL in the address bar look just like the real bank!
Perhaps if you explain why you want to do this, folks might be able to suggest alternative approaches...
[Edit in 2011: Since I wrote this answer in 2008, more info has come to light regarding an HTML5 technique that allows the URL to be modified as long as it is from the same origin]
A: There's a jquery plugin http://www.asual.com/jquery/address/
I think this is what you need.
A: What is working for me is - history.replaceState() function which is as follows -
history.replaceState(data,"Title of page"[,'url-of-the-page']);
This will not reload page, you can make use of it with event of javascript
A: If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.
The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event, or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page. You will also need to check the hash value on page load to set up the initial content.
If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports. I'm sure there are plugins for other libraries as well.
One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.
A: With HTML 5, use the history.pushState function. As an example:
<script type="text/javascript">
var stateObj = { foo: "bar" };
function change_my_url()
{
history.pushState(stateObj, "page 2", "bar.html");
}
var link = document.getElementById('click');
link.addEventListener('click', change_my_url, false);
</script>
and a href:
<a href="#" id='click'>Click to change url to bar.html</a>
If you want to change the URL without adding an entry to the back button list, use history.replaceState instead.
A: jQuery has a great plugin for changing browsers' URL, called jQuery-pusher.
JavaScript pushState and jQuery could be used together, like:
history.pushState(null, null, $(this).attr('href'));
Example:
$('a').click(function (event) {
// Prevent default click action
event.preventDefault();
// Detect if pushState is available
if(history.pushState) {
history.pushState(null, null, $(this).attr('href'));
}
return false;
});
Using only JavaScript history.pushState(), which changes the referrer, that gets used in the HTTP header for XMLHttpRequest objects created after you change the state.
Example:
window.history.pushState("object", "Your New Title", "/new-url");
The pushState() method:
pushState() takes three parameters: a state object, a title (which is currently ignored), and (optionally) a URL. Let's examine each of these three parameters in more detail:
*
*state object — The state object is a JavaScript object which is associated with the new history entry created by pushState(). Whenever the user navigates to the new state, a popstate event is fired, and the state property of the event contains a copy of the history entry's state object.
The state object can be anything that can be serialized. Because Firefox saves state objects to the user's disk so they can be restored after the user restarts her browser, we impose a size limit of 640k characters on the serialized representation of a state object. If you pass a state object whose serialized representation is larger than this to pushState(), the method will throw an exception. If you need more space than this, you're encouraged to use sessionStorage and/or localStorage.
*title — Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.
*URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
A: I was wondering if it will posible as long as the parent path in the page is same, only something new is appended to it.
So like let's say the user is at the page: http://domain.com/site/page.html
Then the browser can let me do location.append = new.html
and the page becomes: http://domain.com/site/page.htmlnew.html and the browser does not change it.
Or just allow the person to change get parameter, so let's location.get = me=1&page=1.
So original page becomes http://domain.com/site/page.html?me=1&page=1 and it does not refresh.
The problem with # is that the data is not cached (at least I don't think so) when hash is changed. So it is like each time a new page is being loaded, whereas back- and forward buttons in a non-Ajax page are able to cache data and do not spend time on re-loading the data.
From what I saw, the Yahoo history thing already loads all of the data at once. It does not seem to be doing any Ajax requests. So when a div is used to handle different method overtime, that data is not stored for each history state.
A: my code is:
//change address bar
function setLocation(curLoc){
try {
history.pushState(null, null, curLoc);
return false;
} catch(e) {}
location.hash = '#' + curLoc;
}
and action:
setLocation('http://example.com/your-url-here');
and example
$(document).ready(function(){
$('nav li a').on('click', function(){
if($(this).hasClass('active')) {
} else {
setLocation($(this).attr('href'));
}
return false;
});
});
That's all :)
A: I've had success with:
location.hash="myValue";
It just adds #myValue to the current URL. If you need to trigger an event on page Load, you can use the same location.hash to check for the relevant value. Just remember to remove the # from the value returned by location.hash e.g.
var articleId = window.location.hash.replace("#","");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "303"
}
|
Q: DRY way of re-raising same set of exceptions in multiple places short:
Is there a way in Ruby to DRY-ify this:
def entry_point_one
begin
do_something
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
def entry_point_two
begin
do_something_else
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
end
longer:
I'm building an interpreter. This interpreter can be called using different entry points. If I feed this interpreter a 'dirty' string, I expect it to raise an error. However, it would be nice if I don't get spammed by the by the entire back trace of every method called directly or indirectly by do_something, especially since the interpreter makes use of recursion.
As you can see in the above snippet, I already know a way to re raise an error and thereby removing the back trace. What I would like do is remove the duplication in the above example. The closest I have come thus far is this:
def entry_point_one
re_raise_known_exceptions {do_something}
end
def entry_point_two
re_raise_known_exceptions {do_something_else}
end
def re_raise_known_exceptions
yield
rescue MySyntaxErrorOne, MySyntaxErrorTwo, MySyntaxErrorEtc => syn_err
raise syn_err.exception(syn_err.message)
end
But that makes the method re-raise-known-exceptions show up in the back trace.
edit: I guess what I want would be something like a C pre-processing macro
A: You can just use the splat on an array.
Straight from IRB:
COMMON_ERRORS = [ArgumentError, RuntimeError] # add your own
def f
yield
rescue *COMMON_ERRORS => err
puts "Got an error of type #{err.class}"
end
f{ raise ArgumentError.new }
Got an error of type ArgumentError
f{ raise 'abc' }
Got an error of type RuntimeError
A: while thinking about it a bit more, I came up with this:
interpreter_block {do_something}
def interpreter_block
yield
rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc
raise exc.exception(exc.message)
end
Although it's still not quiet what I would like to have, at least now the extra entry in the back trace has become somewhat better looking.
A: It might be slightly evil, but I think you can simply remove the line from the backtrace ;-)
COMMON_ERRORS = [ArgumentError, RuntimeError]
def interpreter_block
yield
rescue *COMMON_ERRORS => err
err.backtrace.delete_if{ |line| line=~/interpreter_block/ }
raise err
end
I'm not sure it's such a good idea though. You'll have a hell of a lot of fun debugging your interpreter afterward ;-)
Side note: Treetop may be of interest to you.
A: This is a touch hackish, but as far as cleaning up the backtrace goes, something like this works nicely:
class Interpreter
def method1
error_catcher{ puts 1 / 0 }
end
def error_catcher
yield
rescue => err
err.set_backtrace(err.backtrace - err.backtrace[1..2])
raise err
end
end
The main trick is this line err.set_backtrace(err.backtrace - err.backtrace[1..2]). Without it, we get the following (from IRB):
ZeroDivisionError: divided by 0
from (irb):43:in `/'
from (irb):43:in `block in method1'
from (irb):47:in `error_catcher'
from (irb):43:in `method1'
from (irb):54
from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'
What we don't want in there are the second and third lines. So we remove them, ending up with:
ZeroDivisionError: divided by 0
from (irb):73:in `/'
from (irb):73:in `method1'
from (irb):84
from /Users/peterwagenet/.ruby_versions/ruby-1.9.1-p129/bin/irb:12:in `<main>'
A: If you have all of the information you need in the exceptions, and you do not need the backtrace at all, you can just define your own error and raise that, instead of reraising the existing exception. This will give it a fresh backtrace. (Of course, presumably your sample code is incomplete and there is other processing happening in the rescue block -- otherwise your best bet is to just let the error bubble up naturally.)
class MyError < StandardError; end
def interpreter_block
yield
rescue ExceptionOne, ExceptionTwo, ExceptionEtc => exc
raise MyError
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: best way to pick a random subset from a collection? I have a set of objects in a Vector from which I'd like to select a random subset (e.g. 100 items coming back; pick 5 randomly). In my first (very hasty) pass I did an extremely simple and perhaps overly clever solution:
Vector itemsVector = getItems();
Collections.shuffle(itemsVector);
itemsVector.setSize(5);
While this has the advantage of being nice and simple, I suspect it's not going to scale very well, i.e. Collections.shuffle() must be O(n) at least. My less clever alternative is
Vector itemsVector = getItems();
Random rand = new Random(System.currentTimeMillis()); // would make this static to the class
List subsetList = new ArrayList(5);
for (int i = 0; i < 5; i++) {
// be sure to use Vector.remove() or you may get the same item twice
subsetList.add(itemsVector.remove(rand.nextInt(itemsVector.size())));
}
Any suggestions on better ways to draw out a random subset from a Collection?
A: @Jonathan,
I believe this is the solution you're talking about:
void genknuth(int m, int n)
{ for (int i = 0; i < n; i++)
/* select m of remaining n-i */
if ((bigrand() % (n-i)) < m) {
cout << i << "\n";
m--;
}
}
It's on page 127 of Programming Pearls by Jon Bentley and is based off of Knuth's implementation.
EDIT: I just saw a further modification on page 129:
void genshuf(int m, int n)
{ int i,j;
int *x = new int[n];
for (i = 0; i < n; i++)
x[i] = i;
for (i = 0; i < m; i++) {
j = randint(i, n-1);
int t = x[i]; x[i] = x[j]; x[j] = t;
}
sort(x, x+m);
for (i = 0; i< m; i++)
cout << x[i] << "\n";
}
This is based on the idea that "...we need shuffle only the first m elements of the array..."
A: If you're trying to select k distinct elements from a list of n, the methods you gave above will be O(n) or O(kn), because removing an element from a Vector will cause an arraycopy to shift all the elements down.
Since you're asking for the best way, it depends on what you are allowed to do with your input list.
If it's acceptable to modify the input list, as in your examples, then you can simply swap k random elements to the beginning of the list and return them in O(k) time like this:
public static <T> List<T> getRandomSubList(List<T> input, int subsetSize)
{
Random r = new Random();
int inputSize = input.size();
for (int i = 0; i < subsetSize; i++)
{
int indexToSwap = i + r.nextInt(inputSize - i);
T temp = input.get(i);
input.set(i, input.get(indexToSwap));
input.set(indexToSwap, temp);
}
return input.subList(0, subsetSize);
}
If the list must end up in the same state it began, you can keep track of the positions you swapped, and then return the list to its original state after copying your selected sublist. This is still an O(k) solution.
If, however, you cannot modify the input list at all and k is much less than n (like 5 from 100), it would be much better not to remove selected elements each time, but simply select each element, and if you ever get a duplicate, toss it out and reselect. This will give you O(kn / (n-k)) which is still close to O(k) when n dominates k. (For example, if k is less than n / 2, then it reduces to O(k)).
If k not dominated by n, and you cannot modify the list, you might as well copy your original list, and use your first solution, because O(n) will be just as good as O(k).
As others have noted, if you are depending on strong randomness where every sublist is possible (and unbiased), you'll definitely need something stronger than java.util.Random. See java.security.SecureRandom.
A: I wrote an efficient implementation of this a few weeks back. It's in C# but the translation to Java is trivial (essentially the same code). The plus side is that it's also completely unbiased (which some of the existing answers aren't) - a way to test that is here.
It's based on a Durstenfeld implementation of the Fisher-Yates shuffle.
A: Your second solution of using Random to pick element seems sound, however:
*
*Depending on how sensitive your data is, I suggest using some sort of hashing method to scramble the random number seed. For a good case study, see How We Learned to Cheat at Online Poker (but this link is 404 as of 2015-12-18). Alternative URLs (found via a Google search on the article title in double quotes) include:
*
*How We Learned to Cheat at Online Poker — apparently the original publisher.
*How We Learned to Cheat at Online Poker
*How We Learned to Cheat at Online Poker
*Vector is synchronized. If possible, use ArrayList instead to improve performance.
A: Jon Bentley discusses this in either 'Programming Pearls' or 'More Programming Pearls'. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions - which is a useful saving when N << M.
Knuth also discusses these algorithms - I believe that would be Vol 3 "Sorting and Searching", but my set is packed pending a move of house so I can't formally check that.
A: This is a very similar question on stackoverflow.
To summarize my favorite answers from that page (furst one from user Kyle):
*
*O(n) solution: Iterate through your list, and copy out an element (or reference thereto) with probability (#needed / #remaining). Example: if k = 5 and n = 100, then you take the first element with prob 5/100. If you copy that one, then you choose the next with prob 4/99; but if you didn't take the first one, the prob is 5/99.
*O(k log k) or O(k2): Build a sorted list of k indices (numbers in {0, 1, ..., n-1}) by randomly choosing a number < n, then randomly choosing a number < n-1, etc. At each step, you need to recallibrate your choice to avoid collisions and keep the probabilities even. As an example, if k=5 and n=100, and your first choice is 43, your next choice is in the range [0, 98], and if it's >=43, then you add 1 to it. So if your second choice is 50, then you add 1 to it, and you have {43, 51}. If your next choice is 51, you add 2 to it to get {43, 51, 53}.
Here is some pseudopython -
# Returns a container s with k distinct random numbers from {0, 1, ..., n-1}
def ChooseRandomSubset(n, k):
for i in range(k):
r = UniformRandom(0, n-i) # May be 0, must be < n-i
q = s.FirstIndexSuchThat( s[q] - q > r ) # This is the search.
s.InsertInOrder(q ? r + q : r + len(s)) # Inserts right before q.
return s
I'm saying that the time complexity is O(k2) or O(k log k) because it depends on how quickly you can search and insert into your container for s. If s is a normal list, one of those operations is linear, and you get k^2. However, if you're willing to build s as a balanced binary tree, you can get out the O(k log k) time.
A: How much does remove cost? Because if that needs to rewrite the array to a new chunk of memory, then you've done O(5n) operations in the second version, rather than the O(n) you wanted before.
You could create an array of booleans set to false, and then:
for (int i = 0; i < 5; i++){
int r = rand.nextInt(itemsVector.size());
while (boolArray[r]){
r = rand.nextInt(itemsVector.size());
}
subsetList.add(itemsVector[r]);
boolArray[r] = true;
}
This approach works if your subset is smaller than your total size by a significant margin. As those sizes get close to one another (ie, 1/4 the size or something), you'd get more collisions on that random number generator. In that case, I'd make a list of integers the size of your larger array, and then shuffle that list of integers, and pull off the first elements from that to get your (non-colliding) indeces. That way, you have the cost of O(n) in building the integer array, and another O(n) in the shuffle, but no collisions from an internal while checker and less than the potential O(5n) that remove may cost.
A: I'd personal opt for your initial implementation: very concise. Performance testing will show how well it scales. I've implemented a very similar block of code in a decently abused method and it scaled sufficiently. The particular code relied on arrays containing >10,000 items as well.
A: Set<Integer> s = new HashSet<Integer>()
// add random indexes to s
while(s.size() < 5)
{
s.add(rand.nextInt(itemsVector.size()))
}
// iterate over s and put the items in the list
for(Integer i : s)
{
out.add(itemsVector.get(i));
}
A: two solutions I don't think appear here - the corresponds is quite long, and contains some links, however, I don't think all of the posts relate to the problem of choosing a subst of K elemetns out of a set of N elements. [By "set", I refer to the mathematical term, i.e. all elements appear once, order is not important].
Sol 1:
//Assume the set is given as an array:
Object[] set ....;
for(int i=0;i<K; i++){
randomNumber = random() % N;
print set[randomNumber];
//swap the chosen element with the last place
temp = set[randomName];
set[randomName] = set[N-1];
set[N-1] = temp;
//decrease N
N--;
}
This looks similar to the answer daniel gave, but it actually is very different. It is of O(k) run time.
Another solution is to use some math:
consider the array indexes as Z_n and so we can choose randomly 2 numbers, x which is co-prime to n, i.e. chhose gcd(x,n)=1, and another, a, which is "starting point" - then the series: a % n,a+x % n, a+2*x % n,...a+(k-1)*x%n is a sequence of distinct numbers (as long as k<=n).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: Something Good & Something Bad about SharePoint I'm trying to wrap my head around SharePoint. Why is it good? Why is it bad?
At a glance it appears to offer some incredible collaboration tools. However, the cost looks astronomical and it seems to be rigid & difficult to customize.
To those who've worked with SharePoint; please describe something good and something bad about it.
A: Pros:
*
*Document management is its most well-known
function and integrates extremely
well with Office 2007.
*Create group calendars that can be
overlayed onto your personal Outlook
and managed on the web.
*Notifications in response to certain
actions on the group website
*Wiki-type functionality with full
integration into the Office stack.
*Full database backend which gives
you the reliability and safety of a
true RDBMS.
*Extremely customizable if you choose
to develop custom websites using
ASP.NET (not the built-in wizard/gui
editor).
*Form-data collection
Cons:
*
*Freebie version is somewhat limited
on customization.
*How to handle multiple editors to a
single file is not obvious.
*Workflow for offline editing of
documents is non-obvious.
*Very steep learning curve to use it
the right way.
*Getting people to use it is like
getting people to go to the dentist.
*Out-of-the-box templates don't do a
lot.
*Customizing without writing code
really limits your options.
*Integration with older versions of
office is ugly
*Mac integration is non-existant (has
this changed recently?)
A: It has pretty good Office 2007 integration. As an example, Excel understands when you have a file checked out and will let you check it in (with comments) when you close it. The document management features simplistic version control (although it's not required; you can go with a single version for each file).
In SharePoint, everything is essentially a list internally and it's very easy to create a custom one. On a related note, I haven't used either yet, but it supposedly works well with workflows and InfoPath.
On the downside, it's pretty much a resource beast. It requires multiple machines with powerful specs, particularly if you want to "really" use it for document management and to be the backbone of your intranet/internet site. It scales to an extent, but it's not pretty from my vantage point.
Customizing it presents it's own challenges. You really need people focused on it full time, as both administration and customization require their own impressive learning curves.
Lastly, some of the out of the box parts are poorly implemented. The wiki is a prime example; it's basically useless in my opinion. So one thing to keep in mind is that some may consider SharePoint as a whole package as "best in class" (not saying I do!), its individual features often are not.
A: Good
Out of the box, it offers a ton of functionality and power, even for the stock web parts. Just creating a library of documents that anyone can open/edit/upload to is simple...even for those non-web-savvy amongst us.
Bad
Pretty much everything else.
*
*The "Discussion Board" is a glorified Outlook email chain.
*The disconnect between achieving similar results in SharePoint Designer 2007 and using the web interface are jarring and annoying
*Attempting to customize the look and feel of a SharePoint site usually ends in complete disaster. Especially with WSS 3.0.
*The nickel & diming scheme between the WSS 3.0 and MOSS 2007 tiers is absolutely painful; WSS 3.0 is just barely functional enough to be extremely frustrating to use
*Changing MS styles is almost impossible due to their horribly-laid-out and obnoxiously large CSS file.
*IT IS 2009...GET RID OF THE TABLES FOR NON-TABULAR DATA ALREADY!
It's a beast to use. And handing two complete rebranding projects for two totally different areas of the company is driving me to the point of a nervous breakdown. Especially when opening the core.css file occasionally results in all the styles I've redefined getting reset to the defaults. Without anything done by me other than just OPENING the file. And there is no ability to undo these changes.
A: Good thing: Great communication tool. Instead of sending out a company wide email you can post an announcement to your SharePoint site. Users can subscribe to an RSS feed of the announcements or have a email alert sent to them when the list is updated.
Bad thing: Error messages displayed on a SharePoint site are generic and the link to help resolve the issue rarely is of any help.
A: Good:
It can be a great collaboration tool. Beginning developing for sharepoint is simple, assuming you are familar with ASP.NET webparts.
Bad:
The development lifecycle isn't fully implemented. There are no built-in facilities for testing, among other things.
A: SharePoint is evolving and becoming a better collaboration tool for Microsoft Office environments. It plays well in a small to medium sized business setting. It is critical to implement “best practices” on setup; otherwise it will quickly become a nightmare to maintain and to use.
For “best practices” here are two books that I recommend for SharePoint 2007:
*
*Essential SharePoint 2007
*Sharepoint 2007
A: A lot of the cool things in Sharepoint are avaialable in Windows Sharepoint Services 3.0, which is free with windows server 2003/2008. All you need extra is a license for SQL Server 2000 and later, which most mirosoft shops have. In WSS you can do document management, workflows, custom sites, blogs, wiki's, etc.
If you need Excel Services, Forms Server, CMS, or some of the other MOSS features, then that's another thing. And yes, it does cost a lot of money, but it' cheaper than doing it from scratch in most cases.
Pluses:
- Great object model.
- A lot of good features just come out of the box.
Minuses:
- Steap learning curve to do things the right way.
- It's very easy to hang yourself by doing things the wrong way.
- Debugging and deployment is about as pleasurable as root canal.
A: good :
A lot of things can be done. Wokflowks, InfoPath forms, Excel Services, Business Data Catalogs and etc.
Bad :
You won't be able to do these described easily. Must have sharepoint administrative and development skills for good solutions that don't improve quickly.
A: If you have a license for Microsoft Server 2003 then you can install the standalone version of Sharepoint for FREE!
Download Sharepoint
The install is very simple when using the internal database.
Microsoft Office Sharepoint Designer 2007 is a must have for any customization.
I have created a couple Company Intranets using Sharepoint and have been very pleased with its features.
Microsoft Office 2007 interfaces nicely with sharepoint.
I have found Sharepoint to be very powerful and easy to learn. There are lots of people developing sites using sharepoint. The level of customization is awesome. The simplest customization is done in your browser, the next level is using Microsoft Sharepoint Designer 2007, and finally using Visual Studio to create new apps(webparts).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Copy&paste from Office 2007 into I want to copy and paste text from a Office 2007 document (docx) into a textarea. On Window, using Firefox 3, there is additional jiberish that gets put into the field:
...Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal
0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 Normal 0 false
false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4 <!--[if gte mso 9]>...
Seems to be the style information and conditional comments from the newer document structure. Any ideas on how to parse this out, or prevent this from happening? Possibilities are Javascript on the front side, or Java on the back side.
A: Similar to Lincoln's idea, you can use PureText to automate the process. Basically, you press its hotkey instead of Ctrl+V (I have mine set to Win+V), and it pastes the plain text version of whatever is on your clipboard. I'm not sure if that will remove the extra data that Office has added, but it's worth a try.
A: I find the easiest way to eliminate this random jibberish is to copy the text you want, paste it into notepad or a similar plaintext editor, copy it from notepad, then paste it into the field.
Also, running it through a script or application that strips out the "smart" quotes and em/en dashes isn't a bad idea either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Does XSLT have a Split() function? I have a string in a node and I'd like to split the string on '?' and return the last item in the array.
For example, in the block below:
<a>
<xsl:attribute name="href">
/newpage.aspx?<xsl:value-of select="someNode"/>
</xsl:attribute>
Link text
</a>
I'd like to split the someNode value.
Edit:
Here's the VB.Net that I use to load the Xsl for my Asp.Net page:
Dim xslDocPath As String = HttpContext.Current.Server.MapPath("~/App_Data/someXslt.xsl")
Dim myXsltSettings As New XsltSettings()
Dim myXMLResolver As New XmlUrlResolver()
myXsltSettings.EnableScript = True
myXsltSettings.EnableDocumentFunction = True
myXslDoc = New XslCompiledTransform(False)
myXslDoc.Load(xslDocPath, myXsltSettings, myXMLResolver)
Dim myStringBuilder As New StringBuilder()
Dim myXmlWriter As XmlWriter = Nothing
Dim myXmlWriterSettings As New XmlWriterSettings()
myXmlWriterSettings.ConformanceLevel = ConformanceLevel.Auto
myXmlWriterSettings.Indent = True
myXmlWriterSettings.OmitXmlDeclaration = True
myXmlWriter = XmlWriter.Create(myStringBuilder, myXmlWriterSettings)
myXslDoc.Transform(xmlDoc, argumentList, myXmlWriter)
Return myStringBuilder.ToString()
Update: here's an example of splitting XML on a particular node
A: I ended up using the substring-after() function. Here's what worked for me:
<a>
<xsl:attribute name="href">
/newpage.aspx?<xsl:value-of select="substring-after(someNode, '?')"/>
</xsl:attribute>
Link text
</a>
Even after setting the version of my XSLT to 2.0, I still got a "'tokenize()' is an unknown XSLT function." error when trying to use tokenize().
A: Adding another possibility, if your template engine supports EXSLT, then you could use tokenize() from that.
For example:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:str="http://exslt.org/strings"
extension-element-prefixes="str">
...
<a>
<xsl:attribute name="href">
<xsl:text>/newpage.aspx?</xsl:text>
<xsl:value-of select="str:tokenize(someNode)[2]"/>
</xsl:attribute>
</a>
...
</xsl:stylesheet>
A: Use a recursive method:
<xsl:template name="output-tokens">
<xsl:param name="list" />
<xsl:variable name="newlist" select="concat(normalize-space($list), ' ')" />
<xsl:variable name="first" select="substring-before($newlist, ' ')" />
<xsl:variable name="remaining" select="substring-after($newlist, ' ')" />
<id>
<xsl:value-of select="$first" />
</id>
<xsl:if test="$remaining">
<xsl:call-template name="output-tokens">
<xsl:with-param name="list" select="$remaining" />
</xsl:call-template>
</xsl:if>
</xsl:template>
A: .NET doesn't support XSLT 2.0, unfortunately. I'm pretty sure that it supports EXSLT, which has a split() function. Microsoft has an older page on its implementation of EXSLT.
A: You can write a template using string-before and string-after functions and use it across. I wrote a blog on this.
Finally came up with a xslt template that would split a delimited string into substrings.
I don’t claim it’s the smartest script, but surely solves my problem.
Stylesheet:
<?xml version="1.0" encoding="iso-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<xsl:for-each select="Paths/Item">
<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="Path"/>
<xsl:with-param name="delimiter" select="Delimiter"/>
</xsl:call-template>
<br/>
</xsl:for-each>
</xsl:template>
<xsl:template name="SplitText">
<xsl:param name="inputString"/>
<xsl:param name="delimiter"/>
<xsl:choose>
<xsl:when test="contains($inputString, $delimiter)">
<xsl:value-of select="substring-before($inputString,$delimiter)"/>
<xsl:text disable-output-escaping = "no"> </xsl:text>
<xsl:call-template name="SplitText">
<xsl:with-param name="inputString" select="substring-after($inputString,$delimiter)"/>
<xsl:with-param name="delimiter" select="$delimiter"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:choose>
<xsl:when test="$inputString = ''">
<xsl:text></xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$inputString"/>
<xsl:text> </xsl:text>
</xsl:otherwise>
</xsl:choose>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
XML file (to be transformed) :
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/xsl" href="textSpliter.xslt"?>
<Paths>
<Item>
<Path>C:\ProgramFiles\SomeWierdSoftware</Path>
<Delimiter>\</Delimiter>
</Item>
</Paths>
A: If you can use XSLT 2.0 or higher, you can use tokenize(string, separator):
tokenize("XPath is fun", "\s+")
Result: ("XPath", "is", "fun")
See the w3schools XPath function reference.
By default, .NET does not support XSLT 2.0, let alone XSLT 3.0. The only known 2.0+ processors for .NET are Saxon for .NET with IKVM, Exselt, a .NET XSLT 3.0 processor currently in beta, and XMLPrime XSLT 2.0 processor.
A: XSLT 1.0 doesn't have a split function per se, but you could potentially achieve what you're trying to do with the substring-before and substring-after functions.
Alternatively, if you're using a Microsoft XSLT engine, you could use inline C#.
A: Just for the record, if you're doing this with 1.0, and you really need a split/tokenise, you need the xslt extensions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: Searching for UUIDs in text with regex I'm searching for UUIDs in blocks of text using a regex. Currently I'm relying on the assumption that all UUIDs will follow a patttern of 8-4-4-4-12 hexadecimal digits.
Can anyone think of a use case where this assumption would be invalid and would cause me to miss some UUIDs?
A: By definition, a UUID is 32 hexadecimal digits, separated in 5 groups by hyphens, just as you have described. You shouldn't miss any with your regular expression.
http://en.wikipedia.org/wiki/Uuid#Definition
A: Here is the working REGEX: https://www.regextester.com/99148
const regex = [0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}
A: So, I think Richard Bronosky actually has the best answer to date, but I think you can do a bit to make it somewhat simpler (or at least terser):
re_uuid = re.compile(r'[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}', re.I)
A: The regex for uuid is:
[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}
If you want to enforce the full string to match this regex, you will sometimes (your matcher API may have a method) need to surround above expression with ^...$, that is
^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$
A: Variant for C++:
#include <regex> // Required include
...
// Source string
std::wstring srcStr = L"String with GIUD: {4d36e96e-e325-11ce-bfc1-08002be10318} any text";
// Regex and match
std::wsmatch match;
std::wregex rx(L"(\\{[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}\\})", std::regex_constants::icase);
// Search
std::regex_search(srcStr, match, rx);
// Result
std::wstring strGUID = match[1];
A: For UUID generated on OS X with uuidgen, the regex pattern is
[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}
Verify with
uuidgen | grep -E "[A-F0-9]{8}-[A-F0-9]{4}-4[A-F0-9]{3}-[89AB][A-F0-9]{3}-[A-F0-9]{12}"
A: If using POSIX regex (grep -E, MySQL, etc.), this may be easier to read & remember:
[[:xdigit:]]{8}(-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}
Perl & PCRE flavours also support POSIX character classes so that'll work with them. For those, change the (…) to a non-capturing subgroup (?:…).
JavaScript (and other syntaxes that support Unicode properties) can use a similarly legible version:
/\p{Hex_Digit}{8}(?:-\p{Hex_Digit}{4}){3}-\p{Hex_Digit}{12}/u
A: I agree that by definition your regex does not miss any UUID. However it may be useful to note that if you are searching especially for Microsoft's Globally Unique Identifiers (GUIDs), there are five equivalent string representations for a GUID:
"ca761232ed4211cebacd00aa0057b223"
"CA761232-ED42-11CE-BACD-00AA0057B223"
"{CA761232-ED42-11CE-BACD-00AA0057B223}"
"(CA761232-ED42-11CE-BACD-00AA0057B223)"
"{0xCA761232, 0xED42, 0x11CE, {0xBA, 0xCD, 0x00, 0xAA, 0x00, 0x57, 0xB2, 0x23}}"
A: /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89AB][0-9a-f]{3}-[0-9a-f]{12}$/i
Gajus' regexp rejects UUID V1-3 and 5, even though they are valid.
A: For bash:
grep -E "[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}"
For example:
$> echo "f2575e6a-9bce-49e7-ae7c-bff6b555bda4" | grep -E "[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}"
f2575e6a-9bce-49e7-ae7c-bff6b555bda4
A: $UUID_RE = join '-', map { "[0-9a-f]{$_}" } 8, 4, 4, 4, 12;
BTW, allowing only 4 on one of the positions is only valid for UUIDv4.
But v4 is not the only UUID version that exists.
I have met v1 in my practice as well.
A: [\w]{8}(-[\w]{4}){3}-[\w]{12} has worked for me in most cases.
Or if you want to be really specific [\w]{8}-[\w]{4}-[\w]{4}-[\w]{4}-[\w]{12}.
A: @ivelin: UUID can have capitals. So you'll either need to toLowerCase() the string or use:
[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}
Would have just commented this but not enough rep :)
A:
Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal digit and y is one of 8, 9, A, or B. e.g. f47ac10b-58cc-4372-a567-0e02b2c3d479.
source: http://en.wikipedia.org/wiki/Uuid#Definition
Therefore, this is technically more correct:
/[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/
A: If you want to check or validate a specific UUID version, here are the corresponding regexes.
Note that the only difference is the version number, which is explained in 4.1.3. Version chapter of UUID 4122 RFC.
The version number is the first character of the third group : [VERSION_NUMBER][0-9A-F]{3} :
*
*UUID v1 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[1][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
*UUID v2 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[2][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
*UUID v3 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[3][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
*UUID v4 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
*UUID v5 :
/^[0-9A-F]{8}-[0-9A-F]{4}-[5][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i
A: In python re, you can span from numberic to upper case alpha. So..
import re
test = "01234ABCDEFGHIJKabcdefghijk01234abcdefghijkABCDEFGHIJK"
re.compile(r'[0-f]+').findall(test) # Bad: matches all uppercase alpha chars
## ['01234ABCDEFGHIJKabcdef', '01234abcdef', 'ABCDEFGHIJK']
re.compile(r'[0-F]+').findall(test) # Partial: does not match lowercase hex chars
## ['01234ABCDEF', '01234', 'ABCDEF']
re.compile(r'[0-F]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-f]+', re.I).findall(test) # Good
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-Fa-f]+').findall(test) # Good (with uppercase-only magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
re.compile(r'[0-9a-fA-F]+').findall(test) # Good (with no magic)
## ['01234ABCDEF', 'abcdef', '01234abcdef', 'ABCDEF']
That makes the simplest Python UUID regex:
re_uuid = re.compile("[0-F]{8}-([0-F]{4}-){3}[0-F]{12}", re.I)
I'll leave it as an exercise to the reader to use timeit to compare the performance of these.
Enjoy.
Keep it Pythonic™!
NOTE: Those spans will also match :;<=>?@' so, if you suspect that could give you false positives, don't take the shortcut. (Thank you Oliver Aubert for pointing that out in the comments.)
A: Wanted to give my contribution, as my regex cover all cases from OP and correctly group all relevant data on the group method (you don't need to post process the string to get each part of the uuid, this regex already get it for you)
([\d\w]{8})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{12})|[{0x]*([\d\w]{8})[0x, ]{4}([\d\w]{4})[0x, ]{4}([\d\w]{4})[0x, {]{5}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})
A: Official uuid library uses following regex:
/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i
See reference
A: Generalize one, where underscore is also neglected properly and only alphanumeric values are allowed with the pattern of 8-4-4-4-12.
^[^\W_]{8}(-[^\W_]{4}){4}[^\W_]{8}$
or
^[^\W_]{8}(-[^\W_]{4}){3}-[^\W_]{12}$
both give you the same result, but the last one is more readable. And I would like to recommend the website where one can learn as well as test the Regular expression properly: https://regexr.com/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "354"
}
|
Q: Java VNC Applet Does any one know of an opensource Java VNC server, that can be run from a web page, so requiring no installation on the server end, possibley applet based.
A: A signed Java applet (or application) can use the Robot class to get screenshots of the current window and use this for remote control. It will never be very efficient, but it can be done.
A: Unfortunately Tight VNC only offers an applet based client, and not server, and GSVNCJ is closed source.
A: The accepted answer is wrong — it is perfectly possible to build a VNC server in Java. Yes, Java is sandboxed, but this doesn't mean it cannot access screen contents if you want it to!
A: Checkout GSVNCJ
A: Check out Copilot. It requires no installation, works through firewalls, and works like vnc. They actually use VNC behind the scenes, I think.
A: http://vncj.com/default.aspx
Once you get it setup you wont know how you lived w/o it. The server and the client are using the same .jar file all in the html page pointing where your listen client is at.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using .NET's Reflection.Emit to generate an interface I need to generate a new interface at run-time with all the same members as an existing interface, except that I will be putting different attributes on some of the methods (some of the attribute parameters are not known until run-time). How can it be achieved?
A: Your question isn't very specific. If you update it with more information, I'll flesh out this answer with additional detail.
Here's an overview of the manual steps involved.
*
*Create an assembly with DefineDynamicAssembly
*Create a module with DefineDynamicModule
*Create the type with DefineType. Be sure to pass TypeAttributes.Interface to make your type an interface.
*Iterate over the members in the original interface and build similar methods in the new interface, applying attributes as necessary.
*Call TypeBuilder.CreateType to finish building your interface.
A: To dynamically create an assembly with an interface that has attributes:
using System.Reflection;
using System.Reflection.Emit;
// Need the output the assembly to a specific directory
string outputdir = "F:\\tmp\\";
string fname = "Hello.World.dll";
// Define the assembly name
AssemblyName bAssemblyName = new AssemblyName();
bAssemblyName.Name = "Hello.World";
bAssemblyName.Version = new system.Version(1,2,3,4);
// Define the new assembly and module
AssemblyBuilder bAssembly = System.AppDomain.CurrentDomain.DefineDynamicAssembly(bAssemblyName, AssemblyBuilderAccess.Save, outputdir);
ModuleBuilder bModule = bAssembly.DefineDynamicModule(fname, true);
TypeBuilder tInterface = bModule.DefineType("IFoo", TypeAttributes.Interface | TypeAttributes.Public);
ConstructorInfo con = typeof(FunAttribute).GetConstructor(new Type[] { typeof(string) });
CustomAttributeBuilder cab = new CustomAttributeBuilder(con, new object[] { "Hello" });
tInterface.SetCustomAttribute(cab);
Type tInt = tInterface.CreateType();
bAssembly.Save(fname);
That creates the following:
namespace Hello.World
{
[Fun("Hello")]
public interface IFoo
{}
}
Adding methods use the MethodBuilder class by calling TypeBuilder.DefineMethod.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Possible to retrieve IDENTITY column value on insert using SqlCommandBuilder (without using Stored Proc)? FYI: I am running on dotnet 3.5 SP1
I am trying to retrieve the value of an identity column into my dataset after performing an update (using a SqlDataAdapter and SqlCommandBuilder).
After performing SqlDataAdapter.Update(myDataset), I want to be able to read the auto-assigned value of myDataset.tables(0).Rows(0)("ID"), but it is System.DBNull (despite the fact that the row was inserted).
(Note: I do not want to explicitly write a new stored procedure to do this!)
One method often posted http://forums.asp.net/t/951025.aspx modifies the SqlDataAdapter.InsertCommand and UpdatedRowSource like so:
SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()"
InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
Apparently, this seemed to work for many people in the past, but does not work for me.
Another technique: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=619031&SiteID=1 doesn't work for me either, as after executing the SqlDataAdapter.Update, the SqlDataAdapter.InsertCommand.Parameters collection is reset to the original (losing the additional added parameter).
Does anyone know the answer to this???
A: The insert command can be instructed to update the inserted record using either output parameters or the first returned record (or both) using the UpdatedRowSource property...
InsertCommand.UpdatedRowSource = UpdateRowSource.Both;
If you wanted to use a stored procedure, you'd be done. But you want to use a raw command (aka the output of the command builder), which doesn't allow for either a) output parameters or b) returning a record. Why is this? Well for a) this is what your InsertCommand will look like...
INSERT INTO [SomeTable] ([Name]) VALUES (@Name)
There's no way to enter an output parameter in the command. So what about b)? Unfortunately, the DataAdapter executes the Insert command by calling the commands ExecuteNonQuery method. This does not return any records, so there is no way for the adapter to update the inserted record.
So you need to either use a stored proc, or give up on using the DataAdapter.
A: What works for me is configuring a MissingSchemaAction:
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(myDataAdapter);
myDataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
This lets me retrieve the primary key (if it is an identity, or autonumber) after an insert.
Good luck.
A: I found the answer that works for me here: http://www.dotnetmonster.com/Uwe/Forum.aspx/dotnet-ado-net/4933/Have-soln-but-need-understanding-return-IDENTITY-issue
Code that worked (from the site - attributed to Girish)
//_dataCommand is an instance of SqlDataAdapter
//connection is an instance of ConnectionProvider which has a property called DBConnection of type SqlConnection
//_dataTable is an instance of DataTable
SqlCommandBuilder bldr = new SqlCommandBuilder(_dataCommand);
SqlCommand cmdInsert = new SqlCommand(bldr.GetInsertCommand().CommandText, connection.DBConnection);
cmdInsert.CommandText += ";Select SCOPE_IDENTITY() as id";
SqlParameter[] aParams = new
SqlParameter[bldr.GetInsertCommand().Parameters.Count];
bldr.GetInsertCommand().Parameters.CopyTo(aParams, 0);
bldr.GetInsertCommand().Parameters.Clear();
for(int i=0 ; i < aParams.Length; i++)
{
cmdInsert.Parameters.Add(aParams[i]);
}
_dataCommand.InsertCommand = cmdInsert;
_dataCommand.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
_dataCommand.Update(_dataTable);
A: Actually, this works for me :
SqlDataAdapter.InsertCommand.CommandText += "; SELECT MyTableID = SCOPE_IDENTITY()" InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
Cheers.
A: I had the same problem. It was just solved when I cloned the command generated by the commandbuilder. It looks that even when you change the commandText of the insertcommand, it keeps getting the command generated by the Commandbuilder...
Here it's the code that I used to clone the command...
private static void CloneBuilderCommand(System.Data.Common.DbCommand toClone,System.Data.Common.DbCommand repository)
{
repository.CommandText = toClone.CommandText;
//Copying parameters
if (toClone.Parameters.Count == 0) return;//No parameters to clone? go away!
System.Data.Common.DbParameter[] parametersArray= new System.Data.Common.DbParameter[toClone.Parameters.Count];
toClone.Parameters.CopyTo(parametersArray, 0);
toClone.Parameters.Clear();//Removing association before link to the repository one
repository.Parameters.AddRange(parametersArray);
}
A: If you just want to (a) insert one record into table, (b) use a DataSet, and (c) not use a stored procedure, then you can follow this:
*
*Create your dataAdapter, but in the select statement add WHERE 1=0, so that you don't have to download the entire table - optional step for performance
*Create a custom INSERT statement with scope identity select statement and an output parameter.
*Do the normal processing, filling the dataset, adding the record and saving the table update.
*Should now be able to extract the identity from the parameter directly.
Example:
'-- post a new entry and return the column number
' get the table stucture
Dim ds As DataSet = New DataSet()
Dim da As SqlDataAdapter = New SqlDataAdapter(String.Concat("SELECT * FROM [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] WHERE 1=0"), sqlConnectionString)
Dim cb As SqlCommandBuilder = New SqlCommandBuilder(da)
' since we want the identity column back (FileID), we need to write our own INSERT statement
da.InsertCommand = New SqlCommand(String.Concat("INSERT INTO [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT @FileID = SCOPE_IDENTITY();"))
da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
With da.InsertCommand.Parameters
.Add("@FileName", SqlDbType.VarChar, 1024, "FileName")
.Add("@User", SqlDbType.VarChar, 24, "User")
.Add("@Date", SqlDbType.DateTime, 0, "Date")
.Add("@Table", SqlDbType.VarChar, 128, "FileName")
' allow the @FileID to be returned back to us
.Add("@FileID", SqlDbType.Int, 0, "FileID")
.Item("@FileID").Direction = ParameterDirection.Output
End With
' copy the table structure from the server and create a reference to the table(dt)
da.Fill(ds, fileRegisterTableName)
Dim dt As DataTable = ds.Tables(fileRegisterTableName)
' add a new record
Dim dr As DataRow = dt.NewRow()
dr("FileName") = fileName
dr("User") = String.Concat(Environment.UserDomainName, "\", Environment.UserName)
dr("Date") = DateTime.Now()
dr("Table") = targetTableName
dt.Rows.Add(dr)
' save the new record
da.Update(dt)
' return the FileID (Identity)
Return da.InsertCommand.Parameters("@FileID").Value
But thats pretty long winded to do the same thing as this...
' add the file record
Dim sqlCmd As SqlCommand = New SqlCommand(String.Concat("INSERT INTO [", fileRegisterSchemaName, "].[", fileRegisterTableName, "] (FileName, [User], [Date], [Table]) VALUES (@FileName, @User, @Date, @Table); SELECT SCOPE_IDENTITY();"), New SqlConnection(sqlConnectionString))
With sqlCmd.Parameters
.AddWithValue("@FileName", fileName)
.AddWithValue("@User", String.Concat(Environment.UserDomainName, "\", Environment.UserName))
.AddWithValue("@Date", DateTime.Now())
.AddWithValue("@Table", targetTableName)
End With
sqlCmd.Connection.Open()
Return sqlCmd.ExecuteScalar
A: The issue for me was where the code was placed.
Add the code in the RowUpdating event handler, something like this:
void dataSet_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
e.Command.CommandText += "; SELECT ID = SCOPE_IDENTITY()";
e.Command.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
}
}
A: This is a problem that I've run into before, the bug seems to be that when you call
da.Update(ds);
the parameters array of the insert command gets reset to the inital list that was created form your command builder, it removes your added output parameters for the identity.
The solution is to create a new dataAdapter and copy in the commands, then use this new one to do your da.update(ds);
like
SqlDataAdapter da = new SqlDataAdapter("select Top 0 " + GetTableSelectList(dt) +
"FROM " + tableName,_sqlConnectString);
SqlCommandBuilder custCB = new SqlCommandBuilder(da);
custCB.QuotePrefix = "[";
custCB.QuoteSuffix = "]";
da.TableMappings.Add("Table", dt.TableName);
da.UpdateCommand = custCB.GetUpdateCommand();
da.InsertCommand = custCB.GetInsertCommand();
da.DeleteCommand = custCB.GetDeleteCommand();
da.InsertCommand.CommandText = String.Concat(da.InsertCommand.CommandText,
"; SELECT ",GetTableSelectList(dt)," From ", tableName,
" where ",pKeyName,"=SCOPE_IDENTITY()");
SqlParameter identParam = new SqlParameter("@Identity", SqlDbType.BigInt, 0, pKeyName);
identParam.Direction = ParameterDirection.Output;
da.InsertCommand.Parameters.Add(identParam);
da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
//new adaptor for performing the update
SqlDataAdapter daAutoNum = new SqlDataAdapter();
daAutoNum.DeleteCommand = da.DeleteCommand;
daAutoNum.InsertCommand = da.InsertCommand;
daAutoNum.UpdateCommand = da.UpdateCommand;
daAutoNum.Update(dt);
A: If those other methods didn't work for you, the .Net provided tools (SqlDataAdapter) etc. don't really offer much else regarding flexibility. You generally need to take it to the next level and start doing stuff manually. Stored procedure would be one way to keep using the SqlDataAdapter. Otherwise, you need to move to another data access tool as the .Net data libraries have limits since they design to be simple. If your model doesn't work with their vision, you have to roll your own code at some point/level.
A: Another way using just a command object.
Dim sb As New StringBuilder
sb.Append(" Insert into ")
sb.Append(tbl)
sb.Append(" ")
sb.Append(cnames)
sb.Append(" values ")
sb.Append(cvals)
sb.Append(";Select SCOPE_IDENTITY() as id") 'add identity selection
Dim sql As String = sb.ToString
Dim cmd As System.Data.Common.DbCommand = connection.CreateCommand
cmd.Connection = connection
cmd.CommandText = sql
cmd.CommandType = CommandType.Text
cmd.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord
'retrieve the new identity value, and update the object
Dim dec as decimal = CType(cmd.ExecuteScalar, Decimal)
A: Actually, it's even easier, no need in any custom commands. When you create tableadapter in dataset designer, specify "refresh the data table" in Advanced Options of the wizard. With that, after you issue dataadapter.update mydataset , you will find identify column in the datatable populated with the new value from the database.
A: My solution:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Mytable;" , sqlConnection);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
da.DeleteCommand = (SqlCommand)cb.GetDeleteCommand().Clone();
da.UpdateCommand = (SqlCommand)cb.GetUpdateCommand().Clone();
SqlCommand insertCmd = (SqlCommand)cb.GetInsertCommand().Clone();
insertCmd.CommandText += ";SET @Id = SCOPE_IDENTITY();";
insertCmd.Parameters.Add("@Id", SqlDbType.Int, 0, "Id").Direction = ParameterDirection.Output;
da.InsertCommand = insertCmd;
da.InsertCommand.UpdatedRowSource = UpdateRowSource.OutputParameters;
cb.Dispose();
A: The problem is that the changes you made to the InsertCommand are not taken into consideration when using the SqlDataAdapter.Update(DataSet) Method.
the perfect solution is to clone the InsertCommand generated by the CommandBuilder.
SqlCommandBuilder cb = new SqlCommandBuilder(da);
cb.ConflictOption = ConflictOption.OverwriteChanges;
da.InsertCommand = cb.GetInsertCommand().Clone();
da.InsertCommand.CommandText += "; SELECT idTable = SCOPE_IDENTITY()";
da.InsertCommand.UpdatedRowSource = UpdateRowSource.FirstReturnedRecord;
da.Update(dt);
A: Have you looked into using LINQ instead? I understand this doesn't address your actual question, but if you are using .NET 3.5 you really ought to try using LINQ. In fact, with the advent of Code First EntityFramework, I think you could easily choose either LINQ to SQL or EF as relatively lightweight alternatives to rolling your own DAL.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: Determining if a folder is shared in .NET Is there a way through the .net framework to determine if a folder is shared or not?
Neither Diretory, DirectoryInfo or FileAttributes seem to have any corresponding field.
One thing I forgot to mention was that I want to be checking for network shares. But I'll investigate the WMI stuff.
A: You can use WMI Win32_Share.
Take a look at:
http://www.gamedev.net/community/forums/topic.asp?topic_id=408923
Shows a sample for querying, creating and deleting shared folders.
A: One more way to skin this cat is to use powershell (if you have it installed) to invoke the wmi call, include a reference to System.Management.Automation, it will most likley be in \program files\reference assemblies\microsoft\windowspowershell
private void button1_Click(object sender, EventArgs e)
{
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
Pipeline pl = rs.CreatePipeline();
pl.Commands.AddScript("get-wmiobject win32_share");
StringBuilder sb = new StringBuilder();
Collection<PSObject> list = pl.Invoke();
rs.Close();
foreach (PSObject obj in list)
{
string name = obj.Properties["Name"].Value as string;
string path = obj.Properties["Path"].Value as string;
string desc = obj.Properties["Description"].Value as string;
sb.AppendLine(string.Format("{0}{1}{2}",name, path, desc));
}
// do something with the results...
}
A: You can get a list of all the shared folders using the WMI Win32_Share and see if the folder you're looking for is between them. Here's a snippet that might help you with this:
public static List<string> GetSharedFolders()
{
List<string> sharedFolders = new List<string>();
// Object to query the WMI Win32_Share API for shared files...
ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from win32_share");
ManagementBaseObject outParams;
ManagementClass mc = new ManagementClass("Win32_Share"); //for local shares
foreach (ManagementObject share in searcher.Get()){
string type = share["Type"].ToString();
if (type == "0") // 0 = DiskDrive (1 = Print Queue, 2 = Device, 3 = IPH)
{
string name = share["Name"].ToString(); //getting share name
string path = share["Path"].ToString(); //getting share path
string caption = share["Caption"].ToString(); //getting share description
sharedFolders.Add(path);
}
}
return sharedFolders;
}
Please note that I brutally copy-pasted from this link on bytes
A: Try using WMI and doing a SELECT * FROM Win32_ShareToDirectory query.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Pro/con: Initializing a variable in a conditional statement In C++ you can initialize a variable in an if statement, like so:
if (CThing* pThing = GetThing())
{
}
Why would one consider this bad or good style? What are the benefits and disadvantages?
Personally i like this style because it limits the scope of the pThing variable, so it can never be used accidentally when it is NULL. However, i don't like that you can't do this:
if (CThing* pThing = GetThing() && pThing->IsReallySomeThing())
{
}
If there's a way to make the above work, please post. But if that's just not possible, i'd still like to know why.
Question borrowed from here, similar topic but PHP.
A: About the advantages:
It's always recommended to define variables when you first need them, not a line before. This is for improved readability of your code, since one can tell what CThing is without scrolling and searching where it was defined.
Also reducing scope to a loop/if block, causes the variable to be unreferenced after the execution of the code block, which makes it a candidate for Garbage Collection (if the language supports this feature).
A: if (CThing* pThing = GetThing())
It is bad style, because inside the if you are not providing a boolean expression. You are providing a CThing*.
CThing* pThing = GetThing();
if (pThing != NULL)
This is good style.
A: You can have initialization statements inside if and switch since C++17.
Your code would now be:
if (CThing* pThing = GetThing(); pThing->IsReallySomeThing())
{
// use pThing here
}
// pThing is out of scope here
A: The important thing is that a declaration in C++ is not an expression.
bool a = (CThing* pThing = GetThing()); // not legit!!
You can't do both a declaration and boolean logic in an if statement, C++ language spec specifically allows either an expression or a declaration.
if(A *a = new A)
{
// this is legit and a is scoped here
}
How can we know whether a is defined between one term and another in an expression?
if((A *a = new A) && a->test())
{
// was a really declared before a->test?
}
Bite the bullet and use an internal if. The scope rules are useful and your logic is explicit:
if (CThing* pThing = GetThing())
{
if(pThing->IsReallySomeThing())
{
}
}
A: This shoulddoesn't work in C++ sinceeven though it supports short circuiting evaluation. MaybeDon't try the following:
if ((CThing* pThing = GetThing()) && (pThing->IsReallySomeThing()))
{
}
err.. see Wesley Tarle's answer
A: One reason I don't normally do that is because of the common bug from a missed '=' in a conditional test. I use lint with the error/warnings set to catch those. It will then yell about all assignments inside conditionals.
A: Just an FYI some of the older Microsoft C++ compliers(Visual Studios 6, and .NET 2003 I think) don't quite follow the scoping rule in some instances.
for(int i = 0; i > 20; i++) {
// some code
}
cout << i << endl;
I should be out of scope, but that was/is valid code. I believe it was played off as a feature, but in my opinion it's just non compliance. Not adhering to the standards is bad. Just as a web developer about IE and Firefox.
Can someone with VS check and see if that's still valid?
A: So many things. First of all, bare pointers. Please avoid them by all means. Use references, optional, unique_ptr, shared_ptr. As the last resort, write your own class that deals with pointer ownership and nothing else.
Use uniform initialization if you can require C++11 (C++14 preferred to avoid C++11 defects): - it avoids = vs == confusion and it's stricter at checking the arguments if there are any.
if (CThing thing {})
{
}
Make sure to implement operator bool to get predictable conversion from CThing to bool. However, keep in mind that other people reading the code would not see operator bool right away. Explicit method calls are generally more readable and reassuring. If you can require C++17, use initializer syntax.
if (CThing thing {}; thing.is_good())
{
}
If C++17 is not an option, use a declaration above if as others have suggested.
{
CThing thing {};
if (thing.is_good())
{
}
}
A: You can also enclose the assignment in an extra set of ( ) to prevent the warning message.
A: I see that as kind of dangerous. The code below is much safer and the enclosing braces will still limit the scope of pThing in the way you want.
I'm assuming GetThing() sometimes returns NULL which is why I put that funny clause in the if() statement. It prevents IsReallySomething() being called on a NULL pointer.
{
CThing *pThing = GetThing();
if(pThing ? pThing->IsReallySomeThing() : false)
{
// Do whatever
}
}
A: also notice that if you're writing C++ code you want to make the compiler warning about "=" in a conditional statement (that isn't part of a declaration) an error.
A: It's acceptable and good coding practice. However, people who don't come from a low-level coding background would probably disagree.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Timeout doesn't work with '-re' flag in expect script I'm trying to get an expect script to work, and when I use the -re flag (to invoke regular expression parsing), the 'timeout' keyword seems to no longer work. When the following script is run, I get the message 'timed out at step 1', then 'starting step 2' and then it times out but does NOT print the 'timed out at step 2' I just get a new prompt.
Ideas?
#!/usr/bin/expect --
spawn $env(SHELL)
match_max 100000
set timeout 2
send "echo This will print timed out\r"
expect {
timeout { puts "timed out at step 1" }
"foo " { puts "it said foo at step 1"}
}
puts "Starting test two\r"
send "echo This will not print timed out\r"
expect -re {
timeout { puts "timed out at step 2" ; exit }
"foo " { puts "it said foo at step 2"}
}
A: Figured it out:
expect {
timeout { puts "timed out at step 2" ; exit }
-re "foo " { puts "it said foo at step 2"}
}
A: Yes, the "-re" flag as it appears in your question will apply to every pattern in the expect command. So the "timeout" pattern becomes "-re timeout", losing its specialness.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to have a Label inherite a Composite's GC in SWT I'm writing an app and our designers want to use gradients for some of the backgrounds on a few of our composites.
I wrote the following code:
composite.addListener (SWT.Paint, new Listener () {
public void handleEvent (Event e) {
GC gc = e.gc;
Rectangle rect = composite.getClientArea ();
Color color1 = new Color (display, 0, 0, 0);
Color color2 = new Color (display, 255, 255, 255);
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle (rect.x, rect.y, rect.width, rect.height , true);
}
});
This draws the gradient fine on the composite, but we have Label/CLabels, Canvases and Links on top of the composite.
In these areas, the background is just the plain gray you get when drawing an empty canvas.
I've tried forcing the Labels to inherit the background like so:
label.setBackgroundMode(SWT.INHERIT_DEFAULT) //SWT.INHERIT_FORCE Doesn't work either
But this leaves me with the same default gray and no gradient behind the components on top of the Composite.
Any suggestions for getting the gradient to be the background of each element?
I wouldn't be opposed to drawing the Gradient onto a gc with an image supplied and then setting the background to that Image. However that method just hasn't been working at all, composite or any of its elements.
Also it's not possible for me to set the gradient individually to my knowledge. We want the whole composite to be one uniform flowing gradient.
[edit] I uploaded an example upto twitpic here.
Thanks,
Brian Gianforcaro
A: Use composite.setBackgroundMode(SWT.INHERIT_DEFAULT), but do not paint the composite directly - paint an image and set it as the background image using composite.setBackgroundImage(Image). Unless I'm missing a trick, this means you only have to regenerate the image when the composite is resized too.
You should be able to cut'n'paste this code as is to see what I mean:
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
/**
* SWT composite with transparent label
*
* @author McDowell
*/
public class Sweet {
private Image imageGradient;
private Label label;
private Composite composite;
private void createComponents(Shell parent) {
composite = new Composite(parent, SWT.NONE);
composite.addListener(SWT.Resize, new Listener() {
public void handleEvent(Event e) {
changeImage();
}
});
composite.setLayout(new FormLayout());
composite.setBackgroundMode(SWT.INHERIT_DEFAULT);
label = new Label(composite, SWT.None);
label.setText("Hello, World!");
}
private void changeImage() {
Image oldImage = imageGradient;
Display display = composite.getDisplay();
Rectangle rect = composite.getClientArea();
imageGradient = new Image(display, rect.width, rect.height);
GC gc = new GC(imageGradient);
try {
Color color1 = new Color(display, 200, 200, 255);
try {
Color color2 = new Color(display, 255, 255, 255);
try {
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle(rect.x, rect.y, rect.width,
rect.height, true);
} finally {
color2.dispose();
}
} finally {
color1.dispose();
}
} finally {
gc.dispose();
}
composite.setBackgroundImage(imageGradient);
if (oldImage != null) {
oldImage.dispose();
}
}
private void openShell(Display display) {
Shell shell = new Shell(display);
try {
shell.setSize(200, 100);
shell.setLayout(new FillLayout());
createComponents(shell);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
} finally {
if (!shell.isDisposed()) {
shell.dispose();
}
}
}
public void run() {
Display display = Display.getDefault();
try {
openShell(display);
} finally {
display.dispose();
}
}
public void dispose() {
if (imageGradient != null) {
imageGradient.dispose();
}
}
public static void main(String[] args) {
Sweet sweet = new Sweet();
try {
sweet.run();
} finally {
sweet.dispose();
}
}
}
A: The first thing I would try is to capture an image from the widget and paint the portion of the image where the child widget is located onto the child widget directly.
If that doesn't work, try using the same paint listener for both widget, but before to set the GC's transform to after transforming the GC to translate coordinates to the label's coordinate space:
Listener listener = new Listener () {
public void handleEvent (Event e) {
GC gc = e.gc;
Rectangle rect = composite.getClientArea ();
Point offset = ((Control)e.widget).toControl(composite.toDisplay(0, 0));
Color color1 = new Color (display, 0, 0, 0);
Color color2 = new Color (display, 255, 255, 255);
gc.setForeground(color1);
gc.setBackground(color2);
gc.fillGradientRectangle (rect.x + offset.x, rect.y + offset.y,
rect.width, rect.height , true);
}
}
composite.addListener (SWT.Paint, listener);
label.addListener(SWT.Paint, listener);
Also, be careful to dispose any Color instances you create after you are done with them. Otherwise you will leak system resources and eventually run out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/136580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.